Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are "protected" and "public" visibilities useless for class fields?

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.

like image 694
Matthieu Napoli Avatar asked Mar 28 '12 15:03

Matthieu Napoli


2 Answers

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.

like image 138
Louis Wasserman Avatar answered Sep 28 '22 00:09

Louis Wasserman


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...

like image 30
Pablo Grisafi Avatar answered Sep 28 '22 01:09

Pablo Grisafi