emanuelsn
emanuelsn

Reputation: 121

Generate setters only in the class constructor or generate outside builder

In classes in Java, it is common (at least in college only see so) create private attributes and generate getters and setters for these attributes.

But, I read that you can do something a little different: only generate the getters and leave setters in the constructor. In my head, leaving the setters in the constructor, I think the code will be easier to understand and easier to give maintenance ..

Do according to this second option, leave the setters in the constructor, it is good practice (or even is the best practice) to be applied in the construction of classes? Or create gets and sets for all attributes is most recommended?

Upvotes: 0

Views: 49

Answers (3)

Ray
Ray

Reputation: 3201

Public setters are hints of bad design. We all use them, but actually they are wrong. Directly setting a value inside another object isn't really object-oriented. Members should change because of something the object does, not because of something another object does.

Do a search for "anemic domain model", and you'll understand what I mean.

Upvotes: 1

user1907906
user1907906

Reputation:

You don't 'leave the setters in the cosntructor'. You either have a setter

public void setFoo(String foo) {
  this.foo = foo;
}

or you don't. You can have a constructor that accepts arguments:

public Foo(String foo) {
  this.foo = foo;
}

But this is not a setter, it is a constructor.

To answer your question: Yes, it makes sense to not have a public setter. Some members are not to be set by the user.

Upvotes: 1

Michał Szydłowski
Michał Szydłowski

Reputation: 3409

That depends what you're trying to achieve. If you have fields that you do not plan to modify, sure, why not, you can initalize them in the constructor. But only using setters you can modify them later outside of this class. Neither approach is better or worse, just depends on what you want.

Upvotes: 1

Related Questions