Rob
Rob

Reputation: 59

Altering fields via return values vs. altering fields by referencing them within methods?

Let's say I have a private integer x as a field in class Example, and I want to set this integer to 1. There are two ways I am going about doing this at the moment:

//Choice 1
public class Example{

    private int x;

    // Class Constructor
    public Example(){

        x = setX();

    }

    private int setX(){

        return 1;

    }

}

//Choice 2
public class Example{

    private int x;

    // Class Constructor
    public Example(){

        setX();

    }

    private void setX(){

        x = 1;

    }

}

I was wondering which way is optimal in terms of space and time, or if it matters at all. If the difference is negligible, which way is best practice?

In the same sense, when I want a method to utilize a class field, is it better to pass that field as a parameter or just reference it within the method?

Upvotes: 0

Views: 43

Answers (1)

JB Nizet
JB Nizet

Reputation: 691715

Regarding the last part of your question: methods of an object have access to the state of the object. Passing it as argument is unnecessary.

Regarding the first part: the biggest problem with the alternatives you show is not really which one to choose. The biggest problem is the naming.

A method called setX() is expected to set the value of x. And a Java developer would expect such a setter to take a parameter. A method called setX() that doesn't set anything but returns a computed value should rather be called getSomeValue() or computeSomeValue().

Upvotes: 2

Related Questions