There exists a general OOP principle that methods should return local variables rather than set object fields.
For instance, say I have the following piece of code (example in Java):
public class Number {
public int myNum;
}
public class Horrible {
public static void areYouSerious(Number num){
num.myNum = 47;
}
}
public class Test {
public int num = new Number();
public void doHorribleThings(){
Horrible.areYouSerious(num);
}
public static void main(String[] args){
Test test = new Test();
test.doHorribleThings();
}
}
Obviously this style of programming can go sideways very quickly, and becomes a massive headache for anyone attempting to maintain it. A more correct way of doing this would be the following:
public class Number {
public int myNum;
}
public class NotAsBad {
public static int getDefaultVal(){
return 47;
}
}
public class Test {
public int num = new Number();
public void doHorribleThings(){
num.myNum = NotAsBad.getDefaultVal();
}
public static void main(String[] args){
Test test = new Test();
test.doHorribleThings();
}
}
The first example is modifying a passed in reference, whereas the second is generalizing the static setting function, making it return a value which can be used to set the object field.
Is there a name for the principle that the second method should be preferred over the first? A sort of "modularity" principle?
Just as encapsulation
is the term for restricting variable manipulation, I would like a term for limiting the scope of the effects of some piece of functionality.
If there is no existing term, I am going to call it consequence localization.
num
in the constructor? They didn't seem necessary for the example.