0

Having a method like this:

public double calculateCost();

I could do the next:

if(!personIsPartner) {
  double cost = calculateCost();
}

or

public double calculateCost(){
  if(!personIsPartner) {
    //calculateCost
  }else{
     return 0;     
  }
}

What I mean is if whenever you call a method you have to evaluate the same condition/s previously,

  • those conditions should be part of the method itself like in the last case? I think it should because if you have to call that method from many places and you extract that condition from the method, you would be repeating code, right?
  • Is some pattern that talks about it?

Thanks

1 Answer 1

1

At the end of the day this really comes down the judgement of the developer. It is generally a good thing for your method to be permissive of what's passed into it and to handle errors, special cases, ect accordingly.

Here there's really a couple things to consider; how often you're going to use this method, and if that check will always be made before calling. If you're using it often and the check is always made then I would put in the method, if you have one or more cases where you want the result of calculateCost(), it would be non-zero and personIsPartner == true then you can't reasonably move the condition into the method (or at least it would require further changes to accommodate those special cases).

Based on the details you've included I would recommend moving the conditional inside the method. If those circumstances change you may have to adjust accordingly and deciding which way is going to lead to cleaner/simpler code in the long run can be hard to judge. To certain extent you need to go off feel here, you should be considering how this will used in the future and if excluding the conditional from the method is going to lead to you having that check occur 50 times in your project then it should be in the method, if this isn't going to be used much then perhaps it's not worth doing that refactor and it would be simpler to not call the method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.