4

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?

0
13

Identifiers should not repeate 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 best choice.

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

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, privacy policy and cookie policy

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