Method naming best practices


Method naming best practices

This post is a continuation of our Clean Code series. You can find the previous post here

Giving your method a meaningful and readable name is essential to writing clean code. Why would put so much effort into writing a great code, and then ruin it by avoiding the method naming best practices and giving a bad name? A bad name can cause confusion to your fellow colleagues, since they will have to analyze it to understand if they should or shouldn’t use it. It can even mislead them into using them accidentally, possibly causing some hard to find bugs.

One might argue that you can always explain the method’s behavior in the comments. That’s not entirely wrong, but let’s be honest: nobody really likes to read documentation, and it’s not unusual for them to end up outdated. In my opinion, you should only need to use the comments if your code is really complex. I mean, crazy business logic, university-level math expressions, regexes (those can get messy really easily), and so on.

But that said, let’s enumerate some method naming best practices:

  • It should state the method’s purpose – This is the most important one. A method called “VerifyProperties” should not change properties
  • It should be a verb – It’s an action, right?
  • Avoid acronyms – You don’t wanna keep guessing if a method called “PayJanBills” is paying January or Jan’s bills
  • Be pronounceable – Imagine being unable to refer to your code during a conversation
  • Don’t try to save on words – Sometimes you do have to write a sentence, that’s life. But remember: they should always do ONE thing

If you can manage to keep those best practices in mind, you are one step further into becoming a great developer. And definitely adored by your colleagues, they will appreciate your effort in developing readable code.