This question already has answers here:
When is using public fields acceptable?
(3 answers)
Closed 5 years ago.
Java has different access levels for fields:
public
protected
default
private
Due to encapsulation concept we always trying to use private modifier with getters and setters of needed access level. It has various advantages shown in this answer. Since getters and setters are so cool, when should we prefer public/protected/default Object field; to private Object field; with public/protected/default getters and setters?
Clarification: I perfectly understand why and what are getters, setters and access modifiers. I just want comprehensive answer for a certain question above.
We can achieve complete encapsulation in java by making members of a class private and access them outside the class only through getters and setters. Although a lesser degree of encapsulation can be achieved by making the members public or protected.
Related
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 3 years ago.
Looking and digging through my code, I noticed that we usually use the #Setter from Lombok thoroughly.
It made me wonder about the usage of #Setter.
Indeed, is it more interesting to use #Setter than simply making the field accessible through its visibility?
From what I understand, setters are preferable in one of those cases (thanks to Why use getters and setters/accessors?):
you want your object to react to a field being set
you want to lazily compute the value of a field
you make want to mock (although I deeply think testability should not lead your code design)
class may be inherited and setters overridden
But there are some object which does not match any of those cases.
In code terms, is this:
#Getter
#Setter
public class Person{
private String firstName;
private String lastName;
}
more preferable (in terms of maintainability and readability) than this:
public class Person{
public String firstName;
public String lastName;
}
As a side note, I would like to add that I find person.firstName = "Vincent" more readable than person.setFirstName("Vincent").
You are completely mixing encapsulation with visibility.
Firstly, it's not about lombok. Lombok avoid bolier plate code, in this case, having a setter method. Java beans or DTOs have getter and setter method usually by convention and lombok does it at generated class rather than the java file.
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 8 years ago.
I had been asked the following question in an interview and i am curious to know the answer.
There are two classes as following,
public class EmployeeA{
public int empId;
}
public class EmployeeB{
private int empId;
public void setEmpId(int empId){this.empId = empId;}
public int getEmpId(){return empId;}
}
There are two classes where one class has a public instance field and other have a private field with getters and setters. In this case, which is better implementation and why?
[I have learned that making instance variable private is the better idea. But in both cases i can modify the value of empId attribute. ]
The one-word answer they're probably looking for is "encapsulation".
By encapsulating the private field value, you have the opportunity to change the logic on how the value is set/retrieved in the future. Say, for example, you want to validate on set and filter on retrieval (get). By encapsulating the value, your creating an API which allows for better maintenance moving forward.
Maybe a bit off-topic, although people usually talk about "encapsulation" when talking about "getter/setter", "getter/setters" are actually still far from proper encapsulation.
This famous "why getter and setter methods are evil" is something worth to read. When we say getters and setters are evil, it doesn't mean that we should expose variable directly. It is about further hiding internal data by providing meaningful behavior in class, instead of providing accessors for properties. Although there are a lot of cases we still need accessors, this is something that worth giving attention when you are designing.
Going back to your question, if it is me, I will answer: providing getters and setters provides a minimal level of encapsulation and allow us to do extra work or derives data when we are setting and getting properties. However, for a proper encapsulation, I would rather design the Employee class to provide proper behaviors, instead of simply acting as a value object which only provides bunch of getters/setters.
The accesssor (getter) and mutator (setter) are JavaBean requirement but not all classes in Java must follow this design pattern. Why not creating this class as immutable by having a constructor that take the id (or even better, a static factory). You can then provide an accessor for the the id. That is generally not a good idea to be able to change the id of an object, if the id is used in a Map as the key and you change it, good luck to retrieve you object... Make the class immutable solve this kind of problem.
This question already has answers here:
Why Not Use Public Member Functions
(3 answers)
Closed 9 years ago.
I have question which has been going around in my mind since long.
My Model class should have properties private or public? (Below code is written in PHP but question applies in general for any language)
class Xyz extends Model {
public function __call() {
}
public $description;
public $title;
}
In above example I have public properties $description and $title. Should I make them private?
I update my model as follows
$x = new Xyz();
$x->title('Hello');
$x->description('Blah blah');
$x->save();
I can update and get them by using magic method __call. So why do we need to keep them public? I can make them private. But as I see all the frameworks around keep model properties public.
Any thoughts?
UPDATE:
In answers, everyone is saying follow encapsulation and use private methods. Good but no one has the answer why some PHP frameworks have model properties public ? There should be some reason, isn't it?
As per OOP, we need to follow encapsulation. Please make your properties private and have public accessors and mutators. but, it depends that your accessors and mutators can have other modifiers as well. But, The properties should be always private.
Class fields should always be private. Getters and setters for the fields should be public. Aside from being standard, it is also good to have it this way so that you have the control to do what ever you want to the values that the client classes wants to set to you private fields.
For example, if you want to persist an object to a database, and one column is stated to be not null, and you are not sure if your client class will really return a non-null value, you can handle the null check inside the setter so that the values that you are about to persist to the db contains no null field, as what the table of your db demands.
The fields should always be private as per OOP encapsulation principle. Now the thing is with the getter and setter accessor methods.
The getter is usually safe to make it public. The only downside of it is that you will have to maintain backward compatibility between versions, as this will be part of the public contract of the class. So if the field is something that is part of the implementation rather than interface, than maybe you want to keep it protected.
As for the setter the better question is if to create one or not. If you want to keep your class immutable (or at least some parts of it) with all the advantages and disadvantages that comes from it, then you'll not be creating a setter at all.
You have to make all properties as private in model class and if you have to encapsulate their value then you have to use appropriate getters and setters to get and set their values.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What should the accessablity of Fields in a Abstract Class be?
Is it bad practice to use public fields in abstract classes? The reason I'm asking this is because when I inherit from an abstract class I cannot access a private field from the subclass, the only way(s) around this as far as I can tell is to either make the field public, or create get/set methods to access the field... Which practice is best?
there are always protected fields
Best practice is to use getters and setters, possibly protected or public.
If using getters and setters seems like over kill because all your implementations will be developed with the abstract class itself in the same package or module, you can use protected fields. I don't think its best practice but a pragmatic choice.
In your case a protected member is propably the better choice as it will allow access to the member from within the class or any derived class.
As seen in this article on Member function visibility in Java programs.
Article, includes a nice table for different Java accessors and when/why to use them.
This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 6 years ago.
I saw a code where getters and setters methods are declared private. I am trying to figure out the logic behind it, and I am really having hard time to understand why would you declare them as private? That's exactly opposite of what we are trying to achieve through getters and setters.
I can think of several reasons:
you want to prevent future public access.
If a different programmer sees your code and wants access to a variable, but there are no setters and getters, he might think you just forgot about them, and add them themselves. However, if you declare them as private, it's a statement of intent, saying I don't want these variables to be changed or accessed from the outside.
you want to associate setting and getting with other actions
Say you don't want public accessors. But maybe you want a count of how many times a private variable is changed. It's easier to use a setter rather than incrementing the count every time you access that variable.
you want a central access point
Again, you don't want public access, but during debugging, you might want to put a breakpoint in every place a private member is changed. So instead of setting breakpoints everywhere in the class, you just set one in the accessor.
That's exactly opposite of what we are trying to achieve through getters and setters.
Actually, it is not. The reason for declaring public getters and setters is to hide the fields. This is done to avoid unwanted coupling; i.e. clients of an API depending on the implementation details of the API. (That coupling can be problematic for a number of reasons. For example, dependencies on the types of the fields, the possibility of unexpected changes to the fields.)
The reason for declaring the getters and setters private is to make the corresponding part of the object's abstract state (i.e. the values) private. That's largely independent of the decision to use getters and setters or not to hide the implementation types, prevent direct access, etc.
While the case for using getters and setters is not as strong for private state, there are still tangible benefits in using private getters and/or setters. For instance:
The private getter/setter methods provide a place for adding extra behavior or error checking code.
They can provide a place for logging state changes or access to the fields.
They can provide a place for adding your debug code while testing. (Probably not the best way of debugging.)