In a previous post I wrote some examples of method names that use their arguments’ names to form an expressive expression:
- Users findBy(String name){…}
It reads well when looking at the method definition but it may not read well when used:
- users = findBy(someReallyBadVariableName);
- users = findBy(“bob”);
In this case I can prevent consumers from writing unexpressive code with some redundancy:
- Users findByName(String name){…}
But the redundancy may be annoying in some cases, so when may I avoid the redundancy?
I believe it depends on:
- If the method has more than one argument, I can’t count on the argument’s names – still they have to be good names.
- The level of abstraction of the method:
If the method or function is a low level one, like in a general purpose library, then I prefer to have some redundancy because it’s hard to tell how is it going to be invoked. On the other hand if it’s closer to the domain then the usage gets narrower and I feel better counting on the argument’s name. - The type of the argument – are they primitives or objects?
If the argument is a primitive like a string, someone may pass a literal into the function thus making the readability bad. However if it’s a domain object, literals are not possible and variable names use to be more precise:
generateOrderFor(shoppingCart);
What others heuristics do you usually consider?