Monday, April 19, 2010

On naming functions sanely

When naming your functions, there are certain function prefix/postfixes that should only return specific types. They help the programmers who follow in your footsteps to grasp what it is you were trying to do. It also reduces the number of comments you need because the naming conventions are self explanatory. Here is a short list of some of those function modifiers and the expected return values.

The following should only return boolean values, they should not set anything in the class. They are idempotent. If they are not, you have probably done something wrong or your function is misnamed. Rename it quick before anyone else mistakes it for something that it is not and causes a long bug search.

is_something();
something_exists();

The following should probably not return a value (but if they do it should be true or false based on their success).

set_something();
unset_something();
import_something();
read_something();
calculate_something();
something_calculation();
//this one obviously shouldn't return a value... it could throw an exception though
$something->var = $something_else;

The following should only return values not set them or change anything prior to returning them.

get_something();
retrieve_something();
$something_else = $something->var;
something_value();

The following should only return an integer (long, double…).

count_something();
something_count();

The following are similar, they should also return a number of some sort (could be a float, an int, a double).

total_something();
something_total();
sum_something();

Another thing, don’t use this naming scheme:

get_something();
get_somethings();

There is not enough difference when you are glancing at them quickly or trying to debug something, or you are scrolling through them in an auto-complete pop-up, or documentation. Rather use this one, it is easier to differentiate.

get_something();
get_all_somethings();

Remember:

Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live

No comments:

Post a Comment