Java Programming Practices – Should Function Names Describe Parameter Types?

clean codecoding-stylejavanamingprogramming practices

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?

Best Answer

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.

Related Topic