Is it necessary to have getters and setters in POJO's [duplicate]
I have been going through clean code book which states that the class should not expose the internal state of its data and only should be exposing the behavior. In case of a very simpl and dumb java bean exposing the internal state which getter's and setters, is it not worth just removing them and make the private members public? Or just treat the class as a data structure?
I don't think so. It depends of the lifetime of your Object and its "exposure" (external modification).
If you're only using it as a data structure, exposing fields in secure way (final) sounds enough:
public class Person {
public final String firstName;
public final String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
The term POJO was intended to distinguish classes from JavaBeans or any other convention. As such a POJO is by definition NOT required to do anything.
I have been going through clean code book which states that the class should not expose the internal state of its data and only should be exposing the behavior.
This is called encapsulation and a good principle.
In case of a very simpl and dumb java bean exposing the internal state which getter's and setters, is it not worth just removing them and make the private members public?
That is an alternative approach. Some projects may forbid this approach while others may encourage it. Personally, I would favour this approach for classes which are encapsulated in some way already e.g. they are package local.
There is a view that some day in some way your class might have additional requirements and changing the "API" will be impossible. This goes against the YAGNI principle and very rarely proves to be the case and when it does has a much lower cost than adding lots of methods which don't do anything.
However, this is not always the case and if you don't use accessor methods you should consider what the impact will be on the project if you have to change it later. Using accessor methods every where means you never need to worry about this.
In summary, if you are pretty sure accessor methods are pointless and it won't be a problem to add them later, I would say you should use your judgement. However if you are not sure if it could be a problem in the future or you don't want to have to worry about it, use accessor methods.
The definition of POJO doesn't mandate getter/setter.
Experimentally, I am not using getter and setter in my current project.
The approach I am taking is this one:
unless necessary, don't provide getter/setter.
So far, I didn't find a case where I really needed get/set.
Some friend told me: "having get/set is helpful if in the future you need xyz"; my reply has been: when -in the future- I need to do so, I will provide the getter and setter; I don't want to anticipate anything.
The objection about incapsulation, that some may raise, is not really a valid one: providing getter and setter breaks incapsulation in the same manner, plus you have additional lines of (useless) code. Bugs may also lay in getter and setters.
This is an example of one of a non-trivial domain class:
public class SSHKey implements IsSerializable {
public Long id;
public Long userId;
public String type;
public String bits;
public String fingerprint;
public String comment;
@SuppressWarnings("unused")
private SSHKey() { // required by gwt-rpc
}
public SSHKey(String text) throws InvalidSSHKeyException {
Ensure.that(text != null, new InvalidSSHKeyException("Invalid Key"));
text = text.trim();
String[] parts = text.split(" ", 3);
Ensure.that(parts.length >= 2,
new InvalidSSHKeyException("Invalid Key"));
type = getType(parts);
Ensure.that(type.equals("ssh-rsa") || type.equals("ssh-dss"),
new InvalidSSHKeyException(
"Key must start with 'ssh-rsa' or 'ssh-dss'"));
bits = getBits(parts);
comment = getComment(parts);
}
private String getBits(String[] parts) {
return parts[1];
}
private String getComment(String[] parts) {
if (parts.length == 3)
return parts[2];
return type + " " + bits.substring(0, min(15, bits.length())) + "...";
}
private String getType(String[] parts) {
return parts[0];
}
}
The constructor takes the responsibility to validate and prepare the data to be manageable. Thus this logic doesn't need to be in a setter/getter.
If I was shown object with public members some years ago, I would probably not like them; maybe I am doing something wrong now, but I am experimenting and so far it is ok.
Also, you need to consider if your class is designed to be extended or not (so, foresee the future is part of the requirements), and if you want your object to be immutable. Those things you can only do with get/set.
If your object must be immutable, and you can avoid the empty constructor, you can just add 'final' to the member instances, btw. Unfortunately I had to add IsSerializable (similar to java.io.Serializable) and an empty constructor since this is required by gwt. So, you could tell me then "you see? you need the getter an setter"; well not so sure.
There are some jdbc frameworks which promote the use of public fields btw, like http://iciql.com This doesn't imply that this project is correct, but that some people are thinking about it.
I suppose that the need of getter/setter is mostly cultural.
Only if you expose a class in a library that's used beyond your control.
If you do release such a library, the Uniform Access Principle dictates that you should use getters and setters in order to be able to change the underlying implementation later without requiring clients to change their code. Java doesn't give you other mechanisms to do this.
If you use this class in your own system, there's no need: your IDE can easily encapsulate a public field and update all its usages in one safe step. In this case, brevity wins, and you lose nothing for the time where you need encapsulation.
The issue with making the members accessible is that you no longer control them from inside the class.
Let's say that you make Car.speed accessible. Now, everywhere in you program there can be some reference to it. Now, if you want to make sure that speed is never set a negative value (or to make the change synchronized because you need to make it thread safe), you have to either:
in all the points where speed is accessible, rewrite the program to add the control. And hope that everybody that changes the program in the future remembers to do so.
make the member private again, create the getter and setter methods, and rewrite the program to use them.
Better get used to write getter and setter from the beginning. Nowadays, most IDEs do it automatically for you, anyway.
The canonical answer to this is: You don't know whether your simple data structure will stay so simple in the future. It might evolve more than you expect now. It might be also possible, that anytime soon you want some "value changed" observer in that bean. With getter and setter methods you can do this very simply later without changing you existing codebase.
Another pro point for getter/setter is: If in Rome, do like the Romans... Which means in this case: Many generic frameworks expect getter/setter. If you don't want to rule all these usefulls frameworks out right from the start then do you and your colleagues a favour and simply implement standard getter/and setters.
I think it's a good idea to use getters and setters, unless you have very specific speed/memory/efficiency requirements or very simple objects.
A good example is a Point
, where it is probably both nicer and more efficient to expose it's .x
and .y
variables.
That said, it will actually not be a big effort to change the visibility of a few member variables and introduce getters and setters even for a large codebase, if you suddenly require some logic in a setter.
JavaBeans require getters and setters. POJOs do not, anyway this has its benefits
The objetive of the getters and setters is to achieve encapsulation, which manages the internal state of object. This allows you to add or change business rules in your application after the application has been implemented only change the getter or setter code, example, if you have a text field that only allows for more than 3 characters can check before assigning it to an attribute and throw an exception, other reason for not doing this is if it's possible you'll want to change the implementation or change variable names or something like. This cannot be enforced if the field is publicly accessible and modifyable anyway you can use your IDE to generate setters and getters.
If you are developing a simple application can be recommended, if your application is complex and must give maintenance is not recommend.
for the data-type objects, like POJO / PODS / JavaBean, at python you have only public members
you can set those and get those easily, without generating boilerplate setter and getter code(in java these boilerplate code usually(98%) exposes the inner private tag as noted in the question)
and at python in the case you would need to interact with a getter, then you just define extra code only for that purpose
clean and effective at the language level
at java they chose the IDE development instead of changing base java, see JavaBean e.g. how old that is and java 1.0.2 is how old...
JDK 1.0 (January 23, 1996)
The EJB specification was originally developed in 1997 by IBM and later adopted by Sun Microsystems (EJB 1.0 and 1.1) in 1999
so just live with it, use the setter getter because those are enforced by java surroundings
That's the true what @Peter Lawrey explains about encapsulation.
Only one note: it's more important, when you are working with complex objects (for example in the domain model in a ORM project), when you have attributes that aren't simple Java types. For example:
public class Father {
private List childs = new ArrayList();
public Father() {
// ...
}
private List getChilds() {
return this.childs;
}
public void setChilds(List newChilds) {
this.childs = newChilds;
}
}
public class Child {
private String name;
// ...
private String getName() {
return this.name;
}
public void setName(String newName) {
this.name = newName;
}
}
If you expose one attribute (like the childs
attribute in the Father
class) as a public, you won't be able to identify what part of your code are setting or changing one property of your exposed attribute (in the case, for example, adding new Child
to a Father
or even changing the name
of a existing Child
). In the example, only a Father
object can retrieve the childs
content and all the rest of the classes can change it, using its setter.
精彩评论