28

Recently I started releasing an open source project, while I was the only user of the library I did not care about the names, but know I want to assign clever names to each methods to make it easier to learn, but I also need to use concise names so they are easy to write as well.

I was thinking about some guidelines about the naming, I am aware of lots of guidelines that only care about letters casing or some simple notes. Here, I am looking after guidelines for meaningful but yet concise naming.

For example, this could be part of the guidelines I am looking after:

  • Use Add when an existing item is going to be added to a target, Use Create when a new item is being created and added to a target.
  • Use Remove when an existing item is going to be removed from a target, Use delete when an item is going to be removed permanently.
  • Pair AddXXX methods with RemoveXXX and Pair CreateXXX methods with DeleteXXX methods, but do not mix them.

As the above samples show,I would like to find some online material helping me with naming methods and other item complying with English grammar and word meanings.

The above guidance may be intuitive for native English speakers, but for me that English is my second language I need to be told about things like this.

gnat
  • 21,442
  • 29
  • 112
  • 288
000
  • 4,525
  • 4
  • 16
  • 16
  • Welcome to the site! You may find this related question helpful: http://programmers.stackexchange.com/questions/14169/what-naming-guidelines-do-you-follow – Adam Lear Nov 12 '11 at 03:31
  • 1
    I think the concise part is more important than the meaningful part, since your scheme is already meaningful. If you are going to go the extra mile, do it for consistency. – yannis Nov 12 '11 at 03:32
  • 8
    Descriptive is more important than concise. Most IDE's offer completion, so length shouldn't be an obstacle, and descriptive names are easier to understand and remember. – Caleb Nov 12 '11 at 03:57
  • @AnnaLear I am asking something different, My question is related to things like suggested terminology for naming or the grammar notes that can help others understand the purpose of the method better. – 000 Nov 12 '11 at 07:24
  • 4
    Readable is more important than concise. All modern IDEs have code completion facilities, so making it easier to discover what a method does is more valuable than making it easier to type. –  Jan 14 '12 at 16:46
  • Couldn't agree more with you, @GrahamLee. Sam, your assumption that finding the right names is intuitive for English speakers is most often wrong, many people have problems finding the right name for things ;-) – Amos M. Carpenter Jan 21 '12 at 08:05
  • Question - can an item be created independtly of a target? I would tend to have `create()` **just create**, and then in a separate step they have to call `add()`. Same for remove / delete. – user949300 Dec 09 '16 at 05:58

8 Answers8

40

Naming. One of the hardest things about software development :)

When I name something, here is my set of priorities:

  • Follow the idioms of the language. Ruby likes underscores. JavaScript likes camel case. Whatever language you're in is the convention to follow.
  • Reveal the intent of the API. It's not "send_http_data" it's "post_twitter_status".
  • Avoid leaking implementation details. Say, prefixing a variable with a type.
  • Do not use more characters than necessary without breaking the previous guidelines.

Obviously this is a rather simplistic approach. Naming is nuanced.

For further research, I would recommend reading The Art of Readable Code, as it provides some excellent, succinct advise on method naming. For even more research I cannot more highly recommend Bob Martin's Clean Code.

Glorfindel
  • 3,137
  • 6
  • 25
  • 33
Zee
  • 785
  • 5
  • 7
  • 2
    +1 for good answer and recommending Clean Code. I highly recommend this book as well. One more thing I would add, and this is from Martin's book: "I want code easy to write as well" is much lower priority compared to being able to read code. Obviously, there's such a thing as a name that's too long, but I would always lean towards more readable long names, than those which are easy to write. Plus most modern IDE's have auto-complete anyway. – DXM Jan 15 '12 at 21:54
  • 3
    One more important idea from Robert Martin's book: For methods - long scope short name, short scope long name. For variables the reverse - short scope short name, long scope long name. – Patkos Csaba Jan 16 '12 at 18:49
  • "Clean Code" was the greatest book that helped me **understand the impact** of code readability and listed the best practices I follow on regular basis – Paul Jan 19 '12 at 18:43
  • One question, revealing the intent in method name, doesn't it affect the method reusability? post_twitter_status makes it too specific. – EresDev Mar 20 '19 at 20:23
  • Yes and no. That particular _method_ may be less re-usable, but you can always extract a method with the core behavior, move it to a more generic class and leave the old method as a "seam." This way if you need to avoid duplication you _can_ without changing the interface. – Zee Mar 28 '19 at 15:08
7

The temptation to codify a style or convention for naming can in some cases lead to habits that are considered poor practice nowadays, such as using Hungarian Notation for example. The simple answer is to forget about naming convention and style as if it were some separate thing to be determined separately, and instead to focus on naming everything in your system based on what it actually represents. Method names will be naturally tend to be concise if you limit the functionality of each method so that it does only one thing notionally, and if your method name actually describes the one thing that the method is supposed to do.

Variables, fields, class and file names are something else. I'd suggest that if the variable names are getting too long, then you are trying to either describe these items in too great a detail, or they represent something complex that should either be broken into smaller parts, or perhaps described in a more abstract manner.

At the end of the day, you want to avoid ugly code with names that take up an entire row, or that are so glib as to rob them of their value.

S.Robins
  • 11,385
  • 2
  • 36
  • 52
6

For me, finding a good name for something always comes back to thinking of it as an object that has to justify its existence. Ask yourself:

  • What does the class/method/variable do, i.e. what is its wider purpose and what is it for?
  • What specifically about its purpose does it need to communicate, i.e. what is the essential part that the name needs to have in it?

Most developers would agree that readability is always of paramount importance when it comes to naming. Don't just write code so that you know what you mean while you're writing it, write it so that someone looking at the code for the first time at some point in the future knows what you meant without having to think too much. You'll write the code just once, but during its lifetime it will most likely have to be edited many times and read even more times.

Code should be self-documenting, that is, your naming should make it obvious what something does. If you need to explain what a line of code does in a comment, and renaming things doesn't improve it enough, you should seriously consider refactoring that line into a new method with an appropriately descriptive name, so that reading the original method, the new method call describes what's happening. Don't be afraid to have long names; of course you shouldn't write novels in class/method/variable names, but I'd rather have a name be too long and descriptive than too short and I need to figure out what it does by looking under the hood. Except for some obvious exceptions like x/y coordinates and commonly used acronyms, avoid single-character names and abbreviations. Calling something "bkBtn" instead of "backButton" may have had a purpose back when names were limited to 8 characters and dinosaurs roamed the earth, but in these days with code-completion there's really no excuse for abbreviating.

As much as your language allows, make your code read like an English sentence. Objects use nouns, methods use verbs. Boolean methods typically start with "is", but there are many other options that convey the meaning even better, depending on the use case, such as "can", "should", or "does". Of course, not all languages can be as good as Smalltalk at this, but some symbols are generally understood to be parts of the sentence. Two Smalltalk conventions I personally like to take into other languages as much as possible are prefixing the name of loop parameters with "each", and prefixing method parameters with the article "a" (or "an", or "some" for collections). This may not be a common standard in Java, and anyone is welcome to ignore this bit, but I find that this greatly enhances the readability of code. For instance (example in Java):

public boolean shouldConsiderAbbreviating(List<String> someNames) {
  for (String eachName : someNames) {
    if (isTooLong(eachName)) {
      return true;
    }
  }
  return false;
}

This should be readable to people with just a bit of knowledge of Java as something like this:

To determine whether you should consider abbreviating a list of some names (which are strings), iterate over some names, and for each name, determine whether it is too long; if so, return true; if none is too long, return false.

Contrast the above code with just naming the argument strings and the loop variable string, especially in a more complex method. You'd have to look closely to see the difference instead of the usage being obvious from a glance at the name.

Amos M. Carpenter
  • 825
  • 1
  • 8
  • 12
3

Do not worry about the length of method names. Make sure the method names clearly reflect what they are doing. This is paramount to anything else. If you feel that the method name is too long, use a thesaurus to find a shorter word that means the same thing. For example use Find instead of Retrieve.

Also what is just as important is the names you choose for your classes. These provide lots of context when looking at method names. A method signature like so:

public User Find(int userId);

is easier to understand than:

public Person Find(int personId);

because the context obtained from the class name User tells the programmer that Find() is for locating a specific type of person, the user of your system. The version that uses the Person class doesn't give you any context about why you would even need to use the method in the first place.

Charles Lambert
  • 2,019
  • 17
  • 18
3

Finding a good naming is always a compromise between more factors. You will never be fully satisfied.

That said, even if your native language is not that way, consider that English is the language whose programming languages tokens are formed. Using English-like syntax makes code reading more "fluent" since there are no "broken reading rules" every time a keyword is found.

In general, consider things like object.method(parameters) to match a scheme like subject.verb(complements).

The key point, if you have to support generic programming, is choose a good and consistent set of "verbs" (especially the ones that need to be used in generic algorithms).

About nouns, classes should be named for what they are (in term of concept), while objects for what they are for.

That said, between list.add(component) and component.add_to(list) prefer the first. In general "active transitive" verbs better represent actions respect to their passive or reflexive counterparts. Unless design constrains foce you.

Emilio Garavaglia
  • 4,289
  • 1
  • 22
  • 23
1
  1. Assume English, unless every developer that ever works on this code will speak the same non-English language.

  2. Study commonly accepted naming conventions and styles. Your guiding principle should be clarity. Styles differ by programming language.

  3. There isn't anything you can do with the naming that will make it easier to understand the relationships between the various objects in your code. For that, you still need well-written comments and documentation.

Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
  • 1
    Even if every developer that ever works on the code will speak non-English, still use English...! – Mvision Nov 21 '16 at 14:43
1

Look at how others on your platform do it - some of the bigger players might even have code style and naming guidelines.

Some platforms prefer short names (for instance, in the Win32 C API _tcsstr is the function to find a string within a string - isn't it obvious?), others go for readability in favor of brevity (in Apple's Cocoa framework for Objective-C, the method to replace a substring in a string with another string and return the result as a copy is called stringByReplacingOccurrencesOfString: withString:). I find the latter vastly easier to understand, and only moderately harder to write (especially with code completion).

Since you read code more often than you write it (doubly true for open source libraries), and reading is harder than writing, optimize for reading. Optimize for brevity only last, and take only as much away as is possible without diluting clarity.

fzwo
  • 631
  • 3
  • 7
  • 12
0
  1. Use prefix. If a bunch of methods are used to do something similar or can be in some way grouped together, put a common prefix before their names to show what these methods have in common.
  2. Do not use unclear abbreviation if you want others to understand the names instantly (important in API naming)
neuron
  • 109
  • 2