Setting Java Variable

Is there a difference between case1, case2 and case3? Are there any advantages or disadvantages 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; } } 
+6
source share
4 answers

I assume that in case 2 we push one additional method onto the stack, i.e. setName.But in terms of performance, the gain is almost negligible. Therefore, in this example, we should think, and the point of view on readability than performance.

+3
source

Use debugging and breakpoints on Eclipse to find out how many steps each case takes. Less is better.

Case 1 took 1 step

Case 2 completed 2 steps.

Case 3 = same as Case 1

Case 1 same as Case 3 this simply refers to the current class.

+3
source

case 1 and 3 will return an identical code (unless these are different "names"). The second will have an extra function call that can be optimized or not available for JIT. However, this is not a disadvantage that you should pay attention to.

0
source

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

In case 3, although the scope is clearer, the fact that setters are not used means that sometime in the future you will change the way you set the name field (for example: you want to trim spaces), you must change all the code that changed the variable name, whereas if you used case 2 throughout, you only need to update the setter method.

In my opinion, healthy corporate software development should constantly reorganize the code, as errors are found, and business requirements continue to change, so case 2 will give you an advantage here. But if this is just college homework, then you will leave with affairs 1 and 3.

Potential cases 1 and 3 seem to consume fewer function calls, but won't you get a significant improvement. I dont know.

Also keep in mind that most popular IDEs, such as Eclipse, have the ability to automatically generate getters and setters for you in just a few clicks of the mouse buttons - this should answer "getters and setters - such a problem in Java."

0
source

All Articles