So I've been coding in Java for a decent amount of time, but recently, I've started a class that cares about my coding design. In the past, if I had two methods inside a class that needed to edit the same variable, I would make the variable a class variable. However, I know that some people prefer creating their methods to take in the explicit parameters, and then return the edited version. This results in pretty much the same effect as what I usually do, but I was wondering if there is an advantage one way or the other.
Example 1:
public class foo{
private static String toBeEdited;
private static void main(String args[]){
toBeEdited = "Original string";
editingMethod();
... Code that uses the toBeEdited variable with its new value...
}
private static void editingMethod(){
toBeEdited = "Edited String";
}
}
Example 2:
public class foo{
private static void main(String args[]){
String toBeEdited;
toBeEdited = "Original string";
toBeEdited = editingMethod(toBeEdited);
... Code that uses the toBeEdited variable with its new value...
}
private static String editingMethod(String tBE){
tBE = "Edited String";
return tBE;
}
}
Thanks!
Best Answer
The advantage of 1 is lower Arity, it has fewer arguments. The fewer there are the easier they are to remember.
The advantage of 2 is that it's effect and dependency are explicit. Where it's used it's obvious that it will use a string and that it will change a string.
Both impact readability but 2 is a huge improvement where 1 is only a small improvement.