Manmohan
Manmohan

Reputation: 146

Java Variable setting

Is there any difference among case1, case2 and case3 ? Is there any advantage or disadvantage related to performance?

public class Test {

private String name;

    public void action (){

        name = doSome(); // case 1
        setName(doSome()); // case2
        this.name =doSome(); // case3

    }


    public String doSome(){
            return "Hello";
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }


    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }
}

Upvotes: 6

Views: 126

Answers (4)

gerrytan
gerrytan

Reputation: 41123

I prefer case 2 because on case 1 if sometime in the future a local variable name is introduced, it will cause confusion to the person reading your code as to which variable it refers.

On case 3, although the scope is clearer, the fact that setters is not used means if sometime in the future you changed the way the name field is set (eg: you want to trim whitespaces), you have to change all code that modified name variable, whereas if you used case 2 everywhere, you only need to update the setter method.

In my opinion a healthy enterprise software development should constantly refactor the code as bugs are discovered and business requirements keep changing, hence case 2 will give you advantage here. But if this is just a college homework then you'll get away with case 1 & 3.

Performance-wise case 1 & 3 seem to consume less function calls, but whether it will give you significant improvement I don't know.

Also keep in mind most popular IDE such as Eclipse has a facility to auto-generate getters and setters for you with just few clicks of mouse buttons -- this should answer "getters & setters are such a hassle in Java.."

Upvotes: 0

Joban
Joban

Reputation: 1337

Use the debug and breakpoints on Eclipse to see how many steps each case takes. The less the better.

Case 1 took 1 step

Case 2 took 2 steps

Case 3 = same as Case 1

Case 1 is the same as Case 3 the this keyword just refers to the current class.

Upvotes: 3

user297171
user297171

Reputation:

case 1 and 3 will produce identical code (unless these are different "name"s). The second one will have an extra function call, which may or may not be optimized away by JIT. However, this is not a drawback you should pay attention to.

Upvotes: 0

Jaydeep Rajput
Jaydeep Rajput

Reputation: 3673

I guess, in case 2, we are putting one extra method on the stack i.e setName.But from performance point of view, the gain is almost negligible.So According to me, in this example, we should think from code maintaince and readablity point of view than performance.

Upvotes: 3

Related Questions