Java – What is an Output Argument in Martin’s Clean Code?

clean codejava

On page 45 of Robert C. Martin's Clean Code: A Handbook of Agile Software Craftsmanship, Martin writes that output arguments should be avoided. I'm having trouble understanding the meaning of "output argument" and why they should be avoided.

Martin's example for an output argument appendFooter(s); calls the function public void appendFooter(StringBuffer report). His improvement of the code is report.appendFooter();

Maybe it is due to the lack of code context, but I don't see how using output arguments is considered poor coding. Could someone explain the concept or give addition example of code to understand this?

Would the following function also be considered an example of unclean code by the above principle?

int[] numberArray = {3, 5, 7, 1};
sortArray(numberArray);

If the above is a violation of Martin's principle of not using output arguments, would it be better to have an object that has an array as a field and a function that can be called to sort the array?

ObjectWithArrayField numberArray = new ObjectWithArrayField(3, 5, 7, 1);
numberArray.sort();

Best Answer

Bob Martin is simply talking about readability.

The problem with the appendFooter example is, if you find the code line appendFooter(s) somewhere in a program, it is not immediately obvious if that call takes s as an input and appends it somewhere, or if s is used as an output argument, only passed into the method to take the output of that function. To be sure, you need to check the function's documentation. A call like report.appendFooter(), however, avoids that problem: it is much more obvious now what happens.

Note, however, Bob Martin does not say "never ever use output arguments", he says "in general, you should avoid it, because it will help you to keep your code a bit more cleaner". So this is not a braindead cargo-cult rule one should follow blindly.

Sort methods for standard arrays and collections are a little bit different. Having the sort method a member function of each standard array datatype would have a few drawbacks from the language designer's point of view, for example, having a method like Array.sort allows to keep this in the standard library, outside of the Java runtime. But if you would create an individual collection type which has to be sorted sometimes, adding sort as a member function might be indeed a better idea than putting that into a separate class.

Related Topic