Maybe I made a mistake with the choice of site.
Sorry for my English
Until recently, I thought that there was no point in writing setters
and getters
for a class which fields are set only once. Instead of the setters\getters
I used public constant
fields (or final
in Java) and set fields via a constructor.
But I recently ran into a situation when this method proved to be very uncomfortable. Classes have many fields (5-7 fields either).
And I first realized the benefits of getters
.
Instead of doing this:
class Human {
public final int id;
public final String firstName;
public final String lastName;
public final int age;
public final double money;
public final Gender gender;
public final List<Human> children;
Human(int id, String firstName, String lastName, int age, double money, Gender gender, List<Human> children) {
// set fields here
}
}
class HumanReader {
Human read(Input input) {
int id = readId(input);
String firstName = readFirstName(input);
// ...
List<Human> children = readChildren(input);
return new Human(id, firstName, lastName, age, money, gender, children);
}
}
I began using the next solution:
interface Human {
int getId();
String firstName;
// ...
List<Human> getChildren();
}
class HumanImpl implements Human {
public int id;
public String firstName;
// ...
public List<Human> children;
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
// ...
public List<Human> getChildren() {
return children;
}
}
class HumanReader {
Human read(Input input) {
HumanImpl human = new HumanImpl();
human.id = readId(input);
human.firstName = readFirstName(input);
// ...
human.children = readChildren(input);
return human;
}
}
I think that the second solution is better. It has not the complicated constructor with confusing order of parameters.
But what use are setters
? I still can not understand. Or they need for uniformity?