Argument’s names may improve the method’s signature expressivity

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?

Enjoyed reading this post?
Subscribe to the RSS feed and have all new posts delivered straight to you.
  • kikers25

    Good blog! What do you do If there are more than one way to find a user? Do you code a findBy method per possibility?

  • http://developerscookbook.blogspot.com/ Yeray Darias Camacho

    Nice blog Carlos.

    Actually, in more than 90% of cases I prefer findBy(argument). That is because in my experience there are a few situations where you do something like findBy(“bob”) But anyway I like very much your explanation on the level of abstraction.

  • http://www.carlosble.com/ Carlos Ble

    Thank you Yeray, the fact that you use these kind of names and find then useful make me feel more confident about the idea 😉

  • http://www.carlosble.com/ Carlos Ble

    Maybe in that case you have to add redundancy in the names :-). Thank you Enrique

  • Pingback: Injección de dependencias en Java para dummies – Enrique Martín Martín()