Archive for June, 2010
Addicted to final
Jun 25th
What can I say? I’m addicted to the final keyword. My code is littered with it. A typical class can end up looking like the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | public class SimpleClass { private static final Logger logger = Logger.getLogger("SimpleClass"); private final String foo; private final List<String> bars = new ArrayList<String>(); public SimpleClass(final String foo) { this.foo = foo; } public void addBar(final String bar) { bars.add(bar); } public void printFooBars() { final PrintStream out = System.out; try { out.println(getFoo()); } catch (final Exception e) { logger.info(e.toString()); } for (final String s : bars) { out.println(s); } } protected String getFoo() throws Exception { if (foo == null) { throw new Exception(); } return foo; } } |
Constants, variables, and parameters have final attached to them. I wasn’t always this addicted, but I’ve since learned through painful experience. With the final keyword spread liberally around my code, the compiler does the hard work and tells me when I’m doing something wrong. I can’t accidentally change a value or reassign a variable I didn’t mean to. I know that a lot of people will complain about how verbose this can be and they’re correct. That’s part of the language, though. I’d love to have all variables set as final by default. Until then, I’ll sprinkle it around every chance I get.
