The Importance Of Naming Things

When you think about it, as programmers, we mostly deal with sequences of characters.
I mean, for the compiler (or interpreter), it doesn’t matter if you write sadad = 3 or some_meaningful_name = 3, the end result is the same.
Same goes for method names, classes and so on. Many engines were invented in order to take advantage of this fact to reduce code size where it matters. Most of you know these engines as javascript minifiers and uglifiers.
I bet that no one can recognize or understand the meaning of an uglified code, even if it was him who written it.

I am telling you this because I more and more come to the realization of how much responsibility is put on the shoulders of the programmer which thrives to make his code as clear and self-documenting as possible. Writing a clear and easy to understand code is not an easy task at all. It doesn’t even matter on what programming language you’re developing with, since in every programming language the code mainly consists not of saved keywords, but your own code.
One sentence that is always stuck on the back of my mind when I’m programming is: “Clean code reads like well-written prose” by Grady Booch. When you put this high target in front of you when developing, you start to see things differently. You want your code to be plain english as much as possible, and bury the dirty implementation details, which you can’t evade from, far down.
My feeling is that almost every programmer has the basic sense of what is readable and what is not, but there are still some myths that hold us from making our code even more clean and understandable.
I wanted to break a few of these myths here. I will be using Ruby to give concrete examples but all of these apply to every other language.

Shorter code is better

Generally, writing shorter code is a good idea. Shorter is less to read and thus less time to understand.
Having said that, some cases justify making your code longer. Let’s have a look at the following code:


def get_data_from_internet
request = Request.new
request.url = "http://some.url.com"
request.type = "GET"
request.send
response = request.response_body
if ! response.nil?
json_response = JSON.parse(response)
data = json_response["data"]
else
data = nil
end
return data
end

view raw

gistfile1.rb

hosted with ❤ by GitHub

And let’s refactor out to a longer code:


def get_data_from_internet
request = build_request
response = request.response_body
data = handle_response(response)
return data
end
def build_request
request = Request.new
request.url = "http://some.url.com"
request.type = "GET"
request.send
return request
end
def handle_response(response)
if ! response.nil?
json_response = JSON.parse(response)
data = json_response["data"]
else
data = nil
end
end

view raw

gistfile1.rb

hosted with ❤ by GitHub

Now even though the second form is longer by 9 whole lines, we earn two important advantages from it:
1. The code is much clearer and readable.
2. The code is reusable, for example if we want to handle another response of the same form.

To conclude, we achieved better code by aggregating, grouping and naming of code into meaningful titles, by extracting methods from the original code.

Logic that is used only once should not be extracted

Let’s refer to the shorter form of the code from the previous example, and assume that this is the only code currently written in our system.
Some people will consider extracting it to methods redundant since it is only used in this specific case and hence cannot be reused in other places.
In my opinion we should not try to find the advantage of extracting the code in present time. A few changing factors in our code and development process must be taken into consideration:
1. The code will get a lot longer and a lot more complicated. By extracting it into methods we make the foundation for a more organized and clear code.
2. Other people might start working on our code base. These methods we now create may be used in the future by other programmers to complete their tasks.
3. When we extract code into methods we actually give names to these groups of lines. By doing this, we increase the readability of the code and hence other programmers might identify logic they need which has already been written by you. In the context of the previous code examples, let’s assume I want to to handle another response we get from the web. In the first form of the code it would be harder for me to identify that a handle_response logic already exists since the lines are not extracted into methods, but instead are just part of one big flow of get_data_from_internet.
We can never know when, or even if, our efforts will be worth the while, but if we don’t make these efforts now we lose the chance that something good can come up from it in the future.

One liners are not to be extracted

This is my favorite one, so I saved it for the last 😉
One liners are a big misconception when it comes to code readability since we tend to think that every one line of code we write is digestible by other programmers.
I want to give some of the more obvious cases in which one liners should definitely be extracted and named properly:
1. Regular Expression produce one of the most least readable code. For example:


if str =~ /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/
# Do something
end

view raw

gistfile1.rb

hosted with ❤ by GitHub

Even though it is written in only one line, there is no chance someone else will understand what this regular expression is trying to test (by the way, this is a regexp for a valid number).
It should definitely be extracted out and name properly:


if is_valid_number?(str)
#Do something
end
def is_valid_number?(str)
str =~ /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/
end

view raw

gistfile1.rb

hosted with ❤ by GitHub

This code worths at least two non-white hair on the head of whoever is debugging your code. It is just impossible to understand it otherwise.

2. If conditions that consist of many small conditionals and form a complicated logical expression should be extracted out. For example:


if (logged_in? && (admin? || post.user == current_user)) || post.is_public?
show_post_edit_button
end

view raw

gistfile1.rb

hosted with ❤ by GitHub

This complicated logical expression will hurt our code twice: Once because it is not readable and understandable as a code should be, and twice because as time goes own other programmers will just append more and more conditions to it and will make it look even more horrible than it is.
No doubt it should be refactored out and given a proper name:


if post_is_editable?
show_post_edit_button
end
def post_is_editable?
(logged_in? && current_user.can_edit_post?(post)) || post.is_public?
end
class User
def can_edit_post?(post)
self.admin? || post.user == self
end
end

view raw

gistfile1.rb

hosted with ❤ by GitHub

It is so much fun to read this second form, don’t you agree?

3. Complicated one line computations should be extracted out and named. Let’s look at the following code:


hash = hash.to_a.inject({}) { |h, (f,l)| h[l] = f; h}.select {|k,v| k % 1 == 0}

view raw

gistfile1.rb

hosted with ❤ by GitHub

Most of us will take a few good minutes to understand what this snippet does to a hash.
Refactoring it to small methods makes the whole code look a lot better:


hash = select_odd_keys(inverse_keys_and_values(h))
def inverse_keys_and_values(h)
h.to_a.inject({}) { |h, (f,l)| h[l] = f; h}
end
def select_odd_keys(h)
h.select {|k,v| k % 1 == 0}
end

view raw

gistfile1.rb

hosted with ❤ by GitHub

4. Inline language specific data structures include many non-natural characters which makes them hard to read and figure out. Let’s take a Ruby hash as an example:


if user.is_admin?
{success: true, message: "Welcome Admin", error: ""}
else
{success: false, message: "Permission denied", error: "Not and admin"}
end

view raw

gistfile1.rb

hosted with ❤ by GitHub

While these hashes do convey the message of success and failure they do not fit the description of “reads like well-written prose”. They include strange characters (like { and : ) which prevents the programmer from reading them fluently.
After a small refactoring:


if user.is_admin?
return success_message
else
return failure_message
end
def success_message
{success: true, message: "Welcome Admin", error: ""}
end
def failure_message
{success: false, message: "Permission denied", error: "Not and admin"}
end

view raw

gistfile1.rb

hosted with ❤ by GitHub

We made our code more readable and hidden dirty implementation details from the main flow of the program.
Great success indeed!

One thought on “The Importance Of Naming Things

  1. great success 🙂
    Very nice writing, some very good points.
    just wanted to sharpen two points –
    1. All you ruby programmers got spoiled! “reads like well-written prose” is nice in theory, and should be strived to, but not always realistic. Ruby does a good job at taking you there, but in other languages, unfortunately, this is far from reality, which leads to my next point :
    2. One liners are not to be extracted – most of your examples hit the spot, and extracting them into their own methods is probably the right way, BUT!
    where do you draw the line?
    in your first example, why not take out these two lines into their own method ? –
    json_response = JSON.parse(response)
    data = json_response[“data”]

    I’ll tell you why – because its redundant!
    i dont think that a simple code, which is not repeated in other places, should be extracted because then you might “pay for it” in other cases, like when trying to debug, you might end up tracing back-and-forth down the rabbit hole of unneeded method calls.

    Obviously, discretion should always be taken. all that said here are rules of thumb, best practices, and recommendations.

    Also, each programmer has its own style and preferences, and like in each form of art, there is not always a right or wrong way. Or things are not always Black or White… (or any other artistic cliché you may think of :-))

Leave a reply to שי Cancel reply