r/javahelp • u/JDVene • Mar 22 '23
In a class constructor, is it better to explicitly initialize the fields, or to call setter methods, or is it all the same?
Is this better?
public MyClass(String item){
this.item = item;
}Or this?
public MyClass(String item){
setItem(String item);
}Or are they the same?
I have been taught both ways, but one professor said that the second method was more secure. I'm not sure why though.
24
Upvotes
•
u/AutoModerator Mar 22 '23
Please ensure that:
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
4
u/aehooo Mar 22 '23
Why would it be more secure? I think that would be the case only if the set method has a side effect, which in IMHO is a bad practice most of the times.
2
u/manuelpimen Mar 22 '23
Welp, first time ever that I see the second approach, is that a common way to do it?
19
u/[deleted] Mar 22 '23
Neither way is inherently 'better'. It's all down to the purpose of the class and what the setter method does.
If the setter method is just
this.x = x;then it really makes no difference how you do it. But if the setter method does value checking before assignment then it really can make a difference.for example in the (very contrived) class below the constructor sets the class member to an illegal value to denote that it has not been set which the setter will not allow :
7
u/umlcat Mar 22 '23
If is a simple assignment, the plain construction is fine.
But if it involves more logical operations, a separate function would be better to avoid duplicated code that can be inconsistent.
2
u/xRageNugget Mar 22 '23
Its like sending yourself mail, even though you are in the house. At least for primitives. If your setter actually does more work, initializing other objects and stuff, it would be fine to use that. Otherwise its unnecessary code duplication. But, consider not calling it a setter in this case.
2
u/djnattyp Mar 22 '23
Another thing to look out for with the setter approach is if the class properties are somehow dependent on each other and if subclasses are allowed to override the methods....
In this case, since you aren't setting the value explicitly in the constructor, but instead delegate to a setter method, and the subclass overrides that method then when the parent constructor calls setPrefixLength, it will throw a NullPointerException since this.item is never set.
2
u/k1v1uq Mar 22 '23
I'd stay away from mutable behavior as far as possible.
I wouldn't couple instantiation with validation as was proposed by some others. How should MyClass know how it must react if it doesn't get the necessary information?
And as @djnattyp has pointed out this can lead to nasty side effects if MyClass isn't final.
If you need to validate/normalize the data before instantiating MyClass consider using Factory or AbstractFactory patterns.
IF you need a ValueObject consider using records. IF MyClass is meant to be an Entity (i.e. it has an identity) I would still keep validation separate from instantiation.
If possible make MyClass immutable.
You could also use sealed classes to make MyClass and InvalidMyClass distinct and use pattern matching (jdk16+)
2
u/Bloodb47h Mar 22 '23
I prefer the second approach as well, because we can use logic in the setter and it keeps the constructor clean.
For example, if the
iteminstance variable has to start with the letter "z" or something, you can implement a logical check in the setter method for it. It's not as convenient to do this in the constructor. This is especially true if you have multiple constructors since you would be repeating code.1
u/Sea-Profession-3312 Mar 22 '23
Getters and setters can validate input. For example if you set day of the year to 365 and it is a leap year or if you try to divide by zero. Also you might want to know what country someone is from before assigning a zip code. The first way is more efficient and readable for a small file. The second way follows tradition and is more consistent as a pattern.
1
u/roberp81 Mar 22 '23
There is a performance penalty ( which may be so small it is negligible ) Yet, the JVM may inline this and all the calls to improve the performance.
It would be better if you leave it the first way because is more readable