At my internship one of my colleagues gave me a hint. I want to know if this is good practice.
What I was doing was creating classes that are used only for the values they contain and don't have any functions that actually do something (apart from having getters, setters and a constructor). I declared my variables like this:
public class ObjectIUse{
Private String name;
public ObjectIUse(String name){
this.name = name;
}
public String getName(){
return name;
}
}
So I'm not using a setter because it should always stay the same. My colleague said that I can also do it this way:
public class ObjectIUse{
public final String name;
public ObjectIUse(String name){
this.name = name;
}
}
Because now we don't need to have any getters or setters because it is public, however it can also never be changed because it is final.
Which would be better? Or would it maybe be preferable to still make it private but also final? I mean all of the options work, obviously. I just want to know which is better and why.
Make the variable private, because by doing so you'll be encapsulating the variable in your class. This has many benefits, information hiding is among one, which you'll learn if you go to the above link.
If you want it to never change after creation, then make it final too.
This works now because a String
is immutable. But what happens when you expose the reference to a mutable class and that class is not thread safe ?. You cant even return a defensive copy if you want to.
Not to mention this also breaks encapsulation. Use a private variable and getters.
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