Suppose i have a class with 3 variables
class User{
private int userId;
private String userFirstName;
private String userLastName;
}
now, i could create it's setter methods like this
public User setUserId(int userId){
this.userId = userId;
return this;
}
it would allow me to do chaining like this
User user = new User().setUserId(1).setFirstName("fName");
it has been advised to me not to create object this way because it's an anti-pattern. Basically, the reason that was given to me was that i'm using a setter to set the value of a variable and also, return the object itself(thereby violating Single Responsibility Principle), which i don't think is true. but nonetheless, another approach suggested to me is create a constructor with all the variables.
public User(int userId, String userFirstName, String userLastName){
this.userId = userId;
this.userFirstName = userFirstName;
this.userLastName = userLastName;
}
and call it like this
User user = new User(1, "fName" , null);
LastName would be null as it was in previous case, which i don't suppose is also right(passing null as parameter value).
This is just one example. if i have like 10 different variables and i don't want to use setter in normal way(i.e. call each setter in a single line of code, after creating user object), could someone shed some light over which of the two ways to go about. (my primary concern is code should be smaller yet readable)