9

If you wish to perform the same action using different parameters, you can either make differently named functions:

public Apple findAppleById(long id){
    return repo.findById(id);
}
public Apple findAppleByCultivar(String cultivar){
    return repo.findByCultivar(cultivar);
}

Or you can overload a function and make it less verbose and coupled to the parameter type

public Apple findApple(long id){
    return repo.findById(id);
}
public Apple findApple(String cultivar){
    return repo.findById(cultivar);
}

Which is considered better practice? I recall Clean Code detailing how including type in variable names (customerName > customerNameString) is considered to be bad practice, so why shouldn't that idea extend to function naming?

1
  • It would help to explain what language you're talking about, as different languages offer difference facilities.
    – Caleb
    Feb 22 at 21:30

2 Answers 2

16

Identifiers should not repeat information that is already indicated by the types. So findAppleByString() and findAppleByInteger() would be redundant. But in your case the function names add the information that the integer represents an ID and the string represents a cultivar name, which is not indicated by the type system.

You could also have multiple search methods using the same parameter type, e.g find by ID and find by weight, where the parameter in both cases was an integer. So you would need to distinguish the name.

So the first example seems to be more informative and more flexible, and therefore the better choice.

2
  • 6
    On the other hand, if you had strongly findAppleById(Id id) and findAppleByCultivar(Cultivar cultivar), you'd not want the repetition
    – Caleth
    Sep 20, 2021 at 8:28
  • 1
    @Caleth: Exactly, because now the same information is represented by the types.
    – JacquesB
    Sep 20, 2021 at 8:47
3

I would say, if overloading is available, you only include the argument in the name if you have to use different arguments of the same type (like first name and last name).

For other cases the argument immediately follows the method name anyway so it will read pretty fluently. Also IntelliSense (or whatever they call it in Java) will do a nice job providing a hierarchical view, showing just one entry with multiple options.

Your Answer

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

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