Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always avoid in-out parameters in Java?

There's no doubt that in-out parameters leads to confused code since they may increase unexpected/unpredictabled side-effects.

So, many good programmers say :

Avoid in-out parameters for changing mutable method parameters. Prefer to keep parameters unchanged.

For a perfectionist programmer who expects his code to be the most clean and understandable, does this "rule" must be applied in all case ?

For instance, suppose a basic method for adding elements to a simple list, there's two ways :

First way (with in-out parameter):

private void addElementsToExistingList(List<String> myList){
  myList.add("Foo");
  myList.add("Bar");
}

and the caller being :

List<String> myList = new ArrayList<String>();
//.......Several Instructions (or not) .....
addElementsToExistingList(myList);

Second way without out parameter :

private List<String> addElementsToExistingList(List<String> originalList){
      List<String> filledList = new ArrayList<String>(originalList); //add existing elements
      filledList.add("Foo");
      filledList.add("Bar");
      return filledList; 
    }

and the caller being :

List<String> myList = new ArrayList<String>();
//.......Several Instructions (or not) .....
myList.addAll(addElementsToExistingList(myList));

Pros of second way :

Parameter are not modified => no risk of unexpected side-effects for a new code reader.

Cons of second way :

Very verbose and very less readable ...

Of course, you would tell me that for a code as simple as this one, first way is really more convenient.

But, if we don't consider the difficulty of any concept/code, I juge the second way more logical and obvious for any readers (beginners or not).

However, it violates the CQS principle that consider "command" methods having void return with potential (but allowed since it's the convention) side-effects and "query" methods having a return type and without side-effects.

So, what should a motivate programmer adopt ? Mix of two accorging to the code case ? Or keep the "law" expecting to always avoid in-out parameters...

(Of course, method for adding Element is named for expliciting the example, and would be a bad name choice in real code).

like image 704
Mik378 Avatar asked Dec 17 '22 02:12

Mik378


1 Answers

I think the law should be:

Use what is more straight-forward, but always, always document the behavior of your methods extensively.

Your second example is a very nice case where without documentation you would have a guaranteed bug: the name of the method is addElementsToExistingList, but the method does not add elements to the existing list - it creates a new one. A counter-intuitive and misleading name, to say the least...

like image 150
thkala Avatar answered Jan 01 '23 21:01

thkala