Clean Code–Tips to Become a Better WordPress Developer (II)

WordPress

One of the things I like the most about WordPress is its plugin system–there's a lot you can do! For instance, you can download and install our new plugin, Nelio Content.

A few months ago, I shared my opinion with you about “The pragmatic programmer: from journeyman to master”, a book that, as I said, includes good advice and best programming practices. If you haven’t read the book yet, go ahead and do it right away–it’s very enjoyable and instructive. Anyway, in my previous post I also told you I had a second book on the shelf waiting for me: Clean Code, remember? Well, I’m happy to say I’ve already read it and I like it even more than “The pragmatic programmer”! Let’s take a look at the book and what I think its best parts are, shall we?

Book Overview

Clean Code is based on a very interesting premise: “even bad code works”. That is, even if the code isn’t clean and tidy, if it’s chaotic and difficult to understand, if it’s poorly written… none of these things have to have a negative impact on its functioning–the code can work as it’s supposed to. Now, you’ll agree with me and the author of the book, Robert C.”Uncle Bob” Martin, that dealing with such code would be a big problem for any programmer, right? 😱

Software components play an extremely important role in any company. If your source code isn’t clean and tidy 😵, the amount of time and brutal resources you will have to invest in it every time you have to change, adapt or correct it will be brutal and might even wreck the company’s finances. That’s why this book teaches you how to write clean code and how to detect code that can be improved.

The book is divided into three parts. First, it describes the principles, standards, and good practices that make a source code clean. In the second part, you have a lot of case studies (increasingly complex) where you start from poorly written code and polish it little by little until you reach an elegant and efficient solution. The last part is a list of heuristics and “smells” gathered while creating the case studies, which help you to detect when and how a fragment can be improved. In other words, it’s a knowledge base that describes how to write, read, and clean code.

If you read the book carefully and you try to learn all the lessons it includes, in the end, you’ll come away from it understanding:

  • How to tell the difference between good and bad code
  • How to write good code and how to transform bad code into good code
  • How to create good names, good functions, good objects, and good classes
  • How to format code for maximum readability
  • How to implement complete error handling without obscuring code logic
  • How to unit test and practice test-driven development

Pretty cool, huh?

The book is organized into the following chapters:

  1. Clean Code. An introduction to the difference between unintelligible code and clean code. I think the image that opens the chapter is pretty funny and clearly depicts what to expect from the book:

    What the Fucks" per Minute
    The only valid measurement of code quality: WTFs/minute. Source.
  2. Meaningful Names. How to make sure that our functions, variables, classes… in short, all the components of our code are intelligible and self-explanatory.
  3. Functions. Tips to write better functions: short, atomic, simple, few parameters, no side effects…
  4. Comments. A chapter that basically tells you why you shouldn’t use comments. Why? Read the book! 🤓
  5. Formatting. More tips to format code (spacing, indentation, and so on). If you’re reading this book to become a better WordPress developer, you can skip this chapter—WordPress already has some great style guides that address this.
  6. Objects and Data Structures. Several tips and principles on data abstraction to reduce (or even eliminate) coupling.
  7. Error Handling. A great chapter (one of my favorite, actually) with some useful tips on how to efficiently add error handling into our code. In essence, it covers a sad reality: error handling is accessory—we need it, but it’s probably unrelated to our software’s main functionality. As a result, adding it into our code makes the code look “dirty” and unnecessarily complex. Well, this chapter teaches how to do it cleanly.
  8. Boundaries. One of the toughest problems that programmers face (and this is especially true in WordPress) is our dependence on external libraries or services—if they change, things can stop working. This chapter identifies different scenarios in which we may have compatibility problems when relying on third-party solutions and shows you how to eliminate or minimize their impact.
  9. Unit Tests. There’s little I can say about this chapter—we’ve already discussed its content thoroughly in previous posts.
  10. Classes. During the first chapters, the book covers the building blocks of coding: functions, data structures, variables, and so on. Since clean code requires good organization, the book also devotes a couple of chapters to discuss this topic. In this chapter it focuses on object-oriented programming and its concept of classes, giving some basic advice on “size” and “responsibilities”.
  11. Systems. This chapter is more abstract than the previous one because it explains the concept of “a system”, the interactions between different components, the challenges it entails… Even if it’s more complicated than the rest, it’s worth it (especially if you work with larger software components like, you know, WordPress Core).
  12. Emergence. In this chapter, the author gives four guidelines. Follow them and your code will be cleaner. Essentially, a design is “simple” if it follows these rules:
    • Runs all the tests
    • Contains no duplication
    • Expresses the intent of the programmer
    • Minimizes the number of classes and methods
  13. Concurrency. A chapter devoted to the problems found in concurrent systems and their solutions.
  14. Successive Refinement. A case study in which the author presents a bad code and refines it step by step until it becomes clean code.
  15. JUnit Internals. Another practical example. In this particular case, the author dives into JUnit source code and presents some possible improvements.
  16. Refactorizing SerialDate. Finally, yet another case study. In this case, we start with a code that Martin defines as “good code”. But this doesn’t stop him from proposing several improvements.
  17. Smells and Heuristics. A fantastic compilation of heuristics and smells that’ll help you to identify the components in your code that should be improved. You shouldn’t just read this chapter—you should keep it close to you and use it as a reference. I think these smells and heuristics are priceless!

The 3 Best Tips

This book is fantastic—it’s very well written and has a lot of tricks that I wish we all knew and applied when writing code… but I guess that reading the book and being willing to apply its lessons are the first step towards becoming a better programmer!

Now, as promised, here you have the 3 best parts of the book:

🥉 Bronze. “Comments Do Not Make Up for Bad Code”.

As Martin says, “one of the more common motivations for writing comments is bad code“. Think about it: you’ve just written a new module and, well, it does work, but it’s basically a mess. So you look at it and say to yourself: “Ooh, I’d better comment that!” No! You’d better clean it!

One should never need a comment to understand a piece of code—it should be self-explanatory. And that’s because a comment in your code creates more problems than it fixes. On the one hand, the comment may be out of date and not correspond to the code. But even if that’s not the case, changing the code means you’ll have to update the comment so that it’s “in sync” with the comment… and that’s extra work! On the other hand, comments can end up being a nuisance.

For instance, consider this tiny fragment:

// Check to see if the employee is eligible for full benefits
if ( ( employee.flags & HOURLY_FLAG ) && ( employee.age > 65 ) )

Isn’t the following way better?

if ( employee.isEligibleForFullBenefits() )

It only takes a few seconds to explain most of your intent in code. In many cases, it’s all about creating a function whose name says the same thing as your comment does. And that’s how you make your code cleaner and better.

Disclaimer. Sometimes, you’ll have to comment your code. For example, if you’re creating an API, it’s obvious that it has to be well-documented so that your users can effectively use it—after all, they may be oblivious of its internals. But, anyway, your function and parameter names should be as self-explanatory and clear as possible.

🥈 Silver. “Functions Should Have No Side Effects”.

“Side effects are lies. Your function promises to do one thing, but it also does other hidden things“. I couldn’t agree more with this statement. When a function depends on and manipulates global variables, it’s very difficult to analyze, understand, and fix an erratic behavior. And that’s something we see a lot in WordPress Core—there’s plenty of global variables and objects. That’s why I think this tip is so important for all WordPress developers—we should avoid side effects whenever possible.

Not only global variables can result in unexpected side effects—output parameters in a function can too! When this occurs, the value of one or more parameters changes after calling a function, which is clearly an unexpected behavior. In general, we all assume that the parameters of the functions are just input variables. The only way to know that a certain variable will change when used as the parameter of a function is through its documentation and, well, we’ve just seen that comments shouldn’t be necessary, right?

To get a clear idea of the issue, take a look at the following example:

public class UserValidator {
  ...
  public boolean checkPassword(String username, String password) {
    User user = UserGateway.findByName(username);
    if (user != User.NULL) {
      if (user.hasPassword(password)) {
        Session.initialize();
        return true;
      }
    }
    return false;
  }
  ...
}

Can you spot the side effect? Exactly! The side effect is the call to Session.initialize(). The user is calling a function that, apparently, is supposed to check the password, so the user expects the function to do what it just says it does. So, why does it initialize a session? 🤷 Nobody knows! If that’s the behavior we want, a different name would make it better:checkPasswordAndInitializeSession

🥇 Gold. “Meaningful Names”.

Names are everything in software. After all, programming is no more than describing a system in a formal language, which means concepts and names play an extremely important role. Think about it for a sec—names are everywhere! Variables, arguments, functions, classes, files, directories… they’re all named! So, how much time do you invest in deciding how to name something? Do you use the first name that comes to your mind?

I think the second chapter of the book is outstanding—it’s full of useful tips that I think all programmers should apply. The following are just a few examples of those tips:

  1. Use Intention-Revealing Names. How many times have you found a variable named d followed by a comment explaining what it is? Sometimes programmers are just lazy… and we shouldn’t be! Use a different name, such as elapsedTimeInDaysdaysSinceCreation, or fileAgeInDays. It doesn’t really matter the actual name, as long as it’s clear and meaningful.
  2. Avoid Disinformation. Names should give real information—they shouldn’t lie. For example, if we have a set of accounts, don’t name your variable accountList—such a name’s telling the programmer it’s implemented as a List, and it may not be. A better name would be accounts.
  3. Make Meaningful Distinctions. Sometimes, due to language constraints, we can’t name a thing using the word we want. For instance, if we want to name a variable, class, we can’t, because it’s a reserved keyword. To overcome this issue, we tend to misspell the word and name it klass or clazz instead. This is a bad idea. In these situations, we should use a synonym or similar. Another common example is the situation in which we have two variables with the same type, and we just name them equally and append a number at the end: string1 and string2. Wouldn’t it be better if we named them source and destination? Just look at how easy it is to guess what they’ll do, once the names are properly set!
  4. Use Pronounceable Names. The example included in the book is hilarious: a company had a variable named genymdhms (generation date, year, month, day, hour, minute, and second), so its employees walked around saying “gen why emm dee aich emm ess”. Programmers, designers, analysts… everyone was using that silly name, and one could hear things like “Hey, Mike, take a look! The gen-yah-mudda-hims is set to tomorrow’s date!”. What?! Sure, it’s funny, but it’s a poor naming choice. Why didn’t they use a better, pure English name such as generationTimestamp? “Hey, Mike, take a look! The generation timestamp is set to tomorrow’s date!”
  5. Method Names Should be Verbs or Verb Phrases. No surprise here: there’s plenty of examples of this rule in WordPress:have_posts, get_the_author, or is_single.
  6. Pick One Word per Concept. Sometimes, the same concept can be expressed using different synonyms: fetch, get, or retrieve; delete, remove, or trash. In these cases, you should try to use the same concept always. This way, your code will be easier to understand and you’ll reduce your mental workload.
  7. and many more!

My Opinion

In short, Clean Code is an entertaining and educational book. I recommend that you buy it now and add it to your personal bookshelf. The tips and tricks it contains are very valuable. And believe me when I tell you that the leap in quality between the code you write before and after reading this book is enormous.

Have you already read it? What did you think? Do you have any other recommendation for me?

Featured Image by Joel Filipe via Unsplash.

PoorMehGoodVery GoodAwesome! (No Ratings Yet)
Loading...

by

He obtained his PhD in Computer Science at UPC. David leads the analysis and design of our services and the user support area. He's interested in a variety of areas, including conceptual modeling, virtual reality, and 3D digital printing. He contributes to the WordPress community by participating in meetups, seminars, and the WCEU.

One thought on “Clean Code–Tips to Become a Better WordPress Developer (II)

  1. Wow!! Amazing article.

    I really like your articles, in this article you have shown it in a very easy and simple method. It would be a great help for beginners.

Leave a Reply

Your email address will not be published. Required fields are marked *

I have read and agree to the Nelio Software Privacy Policy

Your personal data will be located on SiteGround and will be treated by Nelio Software with the sole purpose of publishing this comment here. The legitimation is carried out through your express consent. Contact us to access, rectify, limit, or delete your data.