Avoid mixing inputs and outputs

From CSSEMediaWiki
Jump to: navigation, search

Mixing inputs and outputs refers to passing a parameter into a method so it can be assigned a new value, rather than using a return statement. It should be noted this problem cannot even occur in java.

An example of this is given below

   void pretendMethod (int pretendInt) {
       pretendInt = 6;
   }

This is bad because it means we don't know what will happen to our variables when we pass them into methods and it can make the method interface extra complex and confusing.

This problem is normally easily solved by simply using a return statement.

Here is the fixed version of the example given above

   int pretendMethod () {
       return 6;
   }

You can still pass Integers as a reference type, like so.

   void pretendMethod (Integer pretendInt) {
       pretendInt = 6;
   }

However the solution is not so simple if the method already has a return value, several ways to deal with this issue are discussed in this quote from http://www.yoda.arachsys.com/java/passing.html:

"This is the real reason why pass by reference is used in many cases - it allows a method to effectively have many return values. Java doesn't allow multiple "real" return values, and it doesn't allow pass by reference semantics which would be used in other single-return-value languages. However, here are some techniques to work around this:

  • If any of your return values are status codes that indicate success or failure of the method, eliminate them immediately. Replace them with exception handling that throws an exception if the method does not complete successfully. The exception is a more standard way of handling error conditions, can be more expressive, and eliminates one of your return values.
  • Find related groups of return values, and encapsulate them into objects that contain each piece of information as fields. The classes for these objects can be expanded to encapsulate their behavior later, to further improve the design of the code. Each set of related return values that you encapsulate into an object removes return values from the method by increasing the level of abstraction of the method's interface. For instance, instead of passing co-ordinates X and Y by reference to allow them to be returned, create a mutable Point class, pass an object reference by value, and update the object's values within the method.
  • If you find yourself passing in an object and then returning a new version of that object, and the object is mutable, then consider moving the method to be a member of the class of the object that you were passing. This can improve the encapsulation of the design and simplify the interface.
  • If, after all steps above, you are still left with multiple returns to a method, split the method into several different methods that each return a part of the answer. Using this set of methods from client code will be much clearer than one mega-method."
Personal tools