It is considered best practice for encapsulation to use private
fields with accessors (getters and setters), instead of protected
and public
fields.
So, by following this best practice, we never use protected
and public
anymore. Have they become useless, or else what are their use cases?
The only thing I can think of is for public static final
attributes (i.e. class constants).
Note: this is the case at least strongly in the Java world, but the question stands for all languages.
In terms of internal fields? Yes, they're useless in many cases. (Sometimes protected
is acceptable if you expect there to be subclasses, though.) And public static final
attributes are also perfectly okay.
That said, public
and protected
methods are absolutely necessary.
Best practices can change over time.
I can think in two use cases for public fields, both somehow controversial.
Adam Bien says in this post that if you are using a DTO, you may not use private + getter + setter but only public fields. This way you are sure that data is transported as is, without any changes. But in the same line he adds that this will cost you lots of meeting explaining why you do it that way...
Another use for non constant public fields is using public final fields (initialized in constructor) to ensure immutability. Making your classes like
public Person{
public final String lastName;
public final String firstName;
public Person(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
}
is some sort of a new best practice, advised in places like codemonkeyism.
But unless you are the absolute owner of the code and/or you can force new standards to be fulfilled, you should keep avoiding the use of public/protected fields...
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