Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not using a return value of a method , Is it bad design?

Following is an example code , checkUserGuess method that belongs to a Board class.

public String checkUserGuess(String aGuess)
{
   // Some processing

   return result_of_a_guess;
}

I have a SimpleGuessingGame class consumes this method and is satisfied with the processing that the method does. It does not use the returned value.

Another class ComplexGuessingGame consumes this method and also uses the value returned by the method for further processing.

So we have two cases , one where the return value is used and other where its ignored. Is this a common occurrence or does this point to bad design ?

like image 912
Chiseled Avatar asked Nov 01 '22 00:11

Chiseled


2 Answers

When you need to do something like this, chances are that the method does two things that are of value to a caller:

  1. Validates something, or produces another side effect, and
  2. Computes the result to be returned to the callers

Since some users need only #1, while other users need both #1 and #2, it may be a good idea to split the method in two parts, like this:

public void validatekUserGuess(String aGuess) {
   // Some processing
}
public String checkUserGuess(String aGuess) {
    validatekUserGuess(aGuess);
   // Some additional processing
   return result_of_a_guess;
}

Now the users that wish to ignore the return value would not be required to "pay" with CPU and memory for computing a value that they are going to discard anyway.

like image 167
Sergey Kalinichenko Avatar answered Nov 15 '22 06:11

Sergey Kalinichenko


There is nothing inherently wrong with using a return value in one call, and not using it in another.

Imagine in one case you want to attempt to turn a light on, and in another you want to make sure it was actually turned on.

public boolean turnOn(Light l);

case 1:

turnOn(new Light());
log.debug("Attempted to turn on light");

case 2:

boolean turnedOn = turnOn(new Light());
if (turnedOn) {
    log.debug("Light is turned on");
} else {
    log.debug("Not able to turn light on");
}
like image 31
Brandon Ling Avatar answered Nov 15 '22 06:11

Brandon Ling