After I use IntelliJ to inspect my code, hundreds of "Declaration can have final modifier" warnings are issued. To resolve these warnings, I essentially need to turn most of my variables into final, and the following is one typical example. This provokes me to think that I should make member variables as 'final' by default. In most cases, members, especially container classes (i.e. List or Set) ,won't get changed once they are assigned. They change internally by inserting or removing elements from them, but the references to them won't change.
public class Attribute {
private final Insight insight;
private final Attribute attribute;
private final List<String> names;
public Attribute(Insight insight, Attribute attribute) {
attribute = attribute;
insight = insight;
names = new ArrayList<>();
}
}
Does it make sense to make most variables as final by default in design classes? Is it the case that most member variables can be defined as 'final' in Java?
If one were to redesign Java today variables should probably default to private and final rather than package and mutable.
Mutable variables are sometimes necessary but whenever possible you should prefer final, and I can't really think of many legitimate reasons to make variables anything but private.
Things might be different for different target environments but Java is designed to make good readable/maintainable long-lived code, and considering this they just made a few poor decisions on defaults.
But it's an old language and we didn't know as much as we do now. live and learn.
ps: I'd also throw out checked exceptions if I was in charge... probably a good thing I'm not.
If you think about most applications in a real world environment, most of the variables can be final. There are lots of benefits to declaring them final. But I would suggest you to do it as a habit rather than using IDE suggestions and features. As a habit always think of the variables whether they need to mutate or not, if not as part of defining the variable just add final. This habit makes you write finals independent of IDE suggestions. Most IDEs are pretty good at code completion, but you never know. PS: Do keep in mind inheritance of your objects when you make this a habit.
I accidentally declared a final on method once out of habit and paid a price for it :-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With