Before we are software developers, we are people – and thus creatures of habits. It’s hard for someone to change one’s own habits, it’s harder for someone to change someone else’s habits – and for some of us, it’s even harder.

This, week, during a code review, I stumbled upon this kind of structure:

At this point, one realizes String are themselves immutable, which leads to the second proposal, which again save more lines of code:

public class MyStructure {
public final String myProp1;
public final String myProp2;
// A bunch of other String properties
public MyStructure(String myProp1, String myProp2 /* All other properties here */) {
this.myProp1 = myProp1;
this.myProp1 = myProp1;
// All other properties set there
}
}

Given that attributes are final and that Java Strings are immutable, the class still safe against unwanted changes. Note that it works only because Strings are immutable by definition in Java. With a Date property, it wouldn’t work as Dates are mutable.

The same can be done with stateless services, with embedded services that needs to be accessed from children classes. There’s no need to have a getter:

Note: This approach is 100% compatible with for Dependency Injections, either Spring or CDI.

Now, you cannot imagine the amount of back and forth comments this simple review caused. Why? Because even if that makes sense from a coding point of view, it’s completely different from what we usually do.

In that case, laziness and IDEs don’t serve us well. The latter make it too easy to create accessors. I’m pretty sure if we had to code getters and setters by hand, the above proposals would be more in favor.

This post could easily have been titled “Don’t let habits get the best of you”. The lesson here is to regularly challenge how you code, even for simple easy stuff. There might be better alternatives after all.