r/javahelp • • 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

21 comments sorted by

•

u/AutoModerator Mar 22 '23

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions

  • You include any and all error messages in full

  • You ask clear questions

  • 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:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

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.

4

u/JDVene Mar 22 '23

I was confused about that too, which is why I asked. Unless they're final, methods can also be overridden, which makes them less secure than directly setting the variable.

5

u/aehooo Mar 22 '23

I was hoping he gave an explanation, because I was intrigued lol.

I always had this confusion, where “secure” meant “cyber security”, but after some studying, I don’t think that’s the case. Secure just means you or other developer are less likely to do something wrong, you are protecting your code and fields that shouldn’t be accessed externally (i.e. outside of that class). Having setters for all of the fields kinda defeats that purpose, that’s why the builder pattern exists.

Be in mind that with reflection you can mostly do that if you really want or need it, but you have to go out of your way to do it and I think that’s the point!

I am not saying you should always use the builder pattern (I rarely do), but if you really need to avoid changing the value of fields, I think that’s the way to go without having a gigantic constructor.

I highly advise reading Effective Java, if you would like to learn more :)

2

u/JDVene Mar 22 '23

Thanks for the resource

3

u/ITCoder Mar 22 '23

Do not go through this book if you are a beginner. This book discuss lots of points in comparatively short paragraphs. I think one need to have mid level experience with Java, to grasp the concepts discussed in this book.

3

u/desrtfx Out of Coffee error - System halted Mar 22 '23

A setter doesn't necessarily have a side effect as in the conventional meaning, but, properly done (which excludes all the this.xyz = xyz; setters) it performs input validation and can therefore prevent improper values.

Yet, I would not rate input validation as side effect.

The general gist is that setters are also a means to hide implementation details which makes it easier to change the underlying implementation without affecting the front facing interface (here not the Java meaning of interface is meant).

2

u/manuelpimen Mar 22 '23

Welp, first time ever that I see the second approach, is that a common way to do it?

2

u/JDVene Mar 22 '23

I think people use the second method as a way to control input validation without having a giant constructor. Most of the times that I used it was when the attributes of an object were determined by the user.

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 :

class Wibble {
    private int rotation;

    public Wibble() {
        rotation = -1;   // Rotation has not been set yet
    }

    public void setRotation( int degrees ) {
        if( (degrees < 0 ) || (degrees > 359) ) { 
            throw new IllegalArgumentException( "Illegal rotation value !!" );
        }
        if ( rotation == -1 ) {   // Only set if not set already
            rotation = degrees;
        }
    }

    ...
}

3

u/[deleted] Mar 22 '23

[removed] — view removed comment

-3

u/[deleted] Mar 22 '23

It's a trivial example buddy, not deployed code :)

Lazy Initialisation and Lazy loading both have plenty of more meaningful use cases.

2

u/[deleted] Mar 22 '23

[removed] — view removed comment

1

u/[deleted] Mar 22 '23

From Wikipedia...

In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.

This is typically accomplished by augmenting an accessor method (or property getter) to check whether a private member, acting as a cache, has already been initialized. If it has, it is returned straight away. If not, a new instance is created, placed into the member variable, and returned to the caller just-in-time for its first use.

If objects have properties that are rarely used, this can improve startup speed. Mean average program performance may be slightly worse in terms of memory (for the condition variables) and execution cycles (to check them), but the impact of object instantiation is spread in time ("amortized") rather than concentrated in the startup phase of a system, and thus median response times can be greatly improved.

In multithreaded code, access to lazy-initialized objects/state must be synchronized to guard against race conditions.

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....

class MyClass {
    private String item;
    private int prefixLength;
    
    public MyClass(String item, int prefixLength) {
        setItem(item);
        setPrefixLength(prefixLength);
    }
    
    public void setItem(String item) {
        this.item = item;
    }
    
    public void setPrefixLength(int prefixLength) {
        if(prefixLength > -1 && prefixLength < item.length()) {
            this.prefixLength = prefixLength;
        }
    }
}
class SubClass extends MyClass {
    private String specialItem;
    public SubClass(String specialItem, int prefixLength) {
        super(specialItem, prefixLength);
    }
    @Override
    public void setItem(String item) {
        this.specialItem = item;
    }
}

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 item instance 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