Chiseled
Chiseled

Reputation: 2300

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 ?

Upvotes: 5

Views: 15363

Answers (3)

Brandon Ling
Brandon Ling

Reputation: 3919

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");
}

Upvotes: 1

amza
amza

Reputation: 810

If the two are exactly identical (and the result_of_a_guess is needed but just not returned) then I would say that you are fine. Many times built-in functions have return values that people ignore because they just don't need them (but they are nice to have for extra processing, like you seem to be doing).

If you really don't like the return value then you can place result_of_a_guess in a member variable to be only set when the checkUserGuess is flagged as complex like so:

public void checkUserGuess(String aGuess, Boolean isComplex)
{
   // Some processing

   if (isComplex)
      setResult(result_of_a_guess)
}

I've seen a lot of both. In my opinion it comes down to a stylistic choice/ preference. You need to know and understand the scope of your project and what works best for you and your future code!

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

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.

Upvotes: 4

Related Questions