294

So I'm working on this class that's supposed to request help documentation from a vendor through a web service. I try to name it DocumentRetriever, VendorDocRequester, DocGetter, but they just don't sound right. I ended up browsing through dictionary.com for half an hour trying to come up with an adequate word.

Start programming with bad names is like having a very bad hair day in the morning, the rest of the day goes downhill from there. Feel me?

10
  • 2
    Why would you want a class, when you clearly only need a function? Make sure you check out steve-yegge.blogspot.com/2006/03/… for the verb as class name problem.
    – user51568
    Jan 7, 2009 at 22:11
  • Or, move forward & refactor when you finally know what it should be called. Jan 8, 2009 at 23:26
  • 16
    What are you naming?: methods: use verbs, like get, set, save, etc. classes and variables: use nouns, like document, user, context, etc. interfaces: use adjectives, like printable, clonable, iterable, etc. After reading this thread, I like Spolsky's suggestion for classes and variables (it uses nouns) and TravisO's suggestion for methods (it uses verbs). Also don't make objects that end with 'er'. Oct 13, 2012 at 22:47
  • 6
    "There are two hard problems in computer science: cache invalidation, naming conventions, and silent overflow."
    – Karakuri
    Nov 26, 2014 at 17:31
  • 8
    @karakuri The version I heard is "there are 2 hard problems in computer science: naming, and offset by 1 error."
    – Haoest
    Nov 26, 2014 at 17:34

42 Answers 42

125

What you are doing now is fine, and I highly recommend you stick with your current syntax, being:

context + verb + how

I use this method to name functions/methods, SQL stored procs, etc. By keeping with this syntax, it will keep your Intellisense/Code Panes much more neat. So you want EmployeeGetByID() EmployeeAdd(), EmployeeDeleteByID(). When you use a more grammatically correct syntax such as GetEmployee(), AddEmployee() you'll see that this gets really messy if you have multiple Gets in the same class as unrelated things will be grouped together.

I akin this to naming files with dates, you want to say 2009-01-07.log not 1-7-2009.log because after you have a bunch of them, the order becomes totally useless.

11
  • 31
    I prefer to have context inferred from type name when naming methods... class EmployeeRepository { void Add(Employee employee); void Get(int id); void GetAll(); void GetAll(Action<FilterCriteria> filter); } What do you think? Jan 7, 2009 at 23:40
  • 5
    Also helps if you have a standard list of "house" verbs. So it's always Get and not Load/Read/Retrieve/Select/Find .... etc. Jan 8, 2009 at 9:23
  • 2
    Richard you are correct in OOP scenarios, my answer pulled back a bit and was more of a general coding suggestion. I guess technically it applies more towards non OOP languages. Employee.Add() and Employee.GetByID() would be the best usage in OOP.
    – TravisO
    Jan 8, 2009 at 14:56
  • 6
    I like the Intellisense effect of your suggestion, but I prefer an approach that's slightly more literate. So I'd prefer Employee.SetSupervisor() over Employee.SupervisorSet() because it reads (more like natural English. Jan 14, 2009 at 0:20
  • 13
    But @TravisO, this doesn't sound good in English. You don't employee get, you get an employee. What if you have more complex actions involving adjectives, such as InvalidateObsoleteQueries? QueriesInvalidateObsolete is hard to read and does not make sense. Besides, in C#, especially with Resharper, the alphabetic order is irrelevant. If you start typing "emp", Resharper will give you GetEmployee, SetEmployee, and even PopulateInactiveEmployeesList.
    – Ilya Kogan
    Feb 17, 2011 at 15:00
64

One lesson I have learned, is that if you can't find a name for a class, there is almost always something wrong with that class:

  • you don't need it
  • it does too much
2
  • 18
    Or it does too little.
    – user51568
    Jan 8, 2009 at 14:23
  • 4
    Thank you, this was actually relevant to me.
    – Haoest
    Jan 8, 2009 at 17:37
54

A good naming convention should minimize the number of possible names you can use for any given variable, class, method, or function. If there is only one possible name, you'll never have trouble remembering it.

For functions and for singleton classes, I scrutinize the function to see if its basic function is to transform one kind of thing into another kind of thing. I'm using that term very loosely, but you'll discover that a HUGE number of functions that you write essentially take something in one form and produce something in another form.

In your case it sounds like your class transforms a Url into a Document. It's a little bit weird to think of it that way, but perfectly correct, and when you start looking for this pattern, you'll see it everywhere.

When I find this pattern, I always name the function xFromy.

Since your function transforms a Url into a Document, I would name it

DocumentFromUrl

This pattern is remarkably common. For example:

atoi -> IntFromString
GetWindowWidth -> WidthInPixelsFromHwnd // or DxFromWnd if you like Hungarian
CreateProcess -> ProcessFromCommandLine

You could also use UrlToDocument if you're more comfortable with that order. Whether you say xFromy or yTox is probably a matter of taste, but I prefer the From order because that way the beginning of the function name already tells you what type it returns.

Pick one convention and stick to it. If you are careful to use the same names as your class names in your xFromy functions, it'll be a lot easier to remember what names you used. Of course, this pattern doesn't work for everything, but it does work where you're writing code that can be thought of as "functional."

7
  • A nice reminder that in OOP languages, class names do not always need to be nouns but it is ok for them to be "verbish" on occasion. Hence why OOP practitioners often get tripped up (like the person asking the question) since too much emphasize that classes must be a "thing" in real world.
    – Ray
    Jan 8, 2009 at 8:35
  • 7
    The xFromY-Convetion basically repeats what's in the return type and parameter list: Foo fooFromBar (Bar bar). It's up to you if you call this consistency or redendancy. Jan 8, 2009 at 9:07
  • "In your case it sounds like your class transforms a Url into a Document". Since when are classes supposed to "do" things, instead of represent concepts?
    – user51568
    Jan 8, 2009 at 14:19
  • 7
    @Brian: it's only redundant in one place... at the declaration. Everywhere else you use it, it's nice to have a little reminder of the data types. Makes code more readable without having to go back to the declaration. Jan 8, 2009 at 16:31
  • 3
    @stefan- In some languages such C# and Java all code must be encapsulated in an a class unlike in C++. Functions are not quite first class citizens in those languages if you want modularize code. Therefore, you sometimes end up with class that might "do" things like a function.
    – Ray
    Jan 8, 2009 at 18:23
32

Sometimes there isn't a good name for a class or method, it happens to us all. Often times, however, the inability to come up with a name may be a hint to something wrong with your design. Does your method have too many responsibilities? Does your class encapsulate a coherent idea?

1
  • 4
    Very good point, really. May 5, 2010 at 22:10
29

Thread 1:

function programming_job(){
    while (i make classes){
         Give each class a name quickly; always fairly long and descriptive.
         Implement and test each class to see what they really are. 
         while (not satisfied){
            Re-visit each class and make small adjustments 
         }
    }
}

Thread 2:

while(true){
      if (any code smells bad){
           rework, rename until at least somewhat better
      }
}

There's no Thread.sleep(...) anywhere here.

0
24

I do spend a lot of time as well worrying about the names of anything that can be given a name when I am programming. I'd say it pays off very well though. Sometimes when I am stuck I leave it for a while and during a coffee break I ask around a bit if someone has a good suggestion.

For your class I'd suggest VendorHelpDocRequester.

3
  • 1
    > VendorHelpDocRequester Good one. I actually googled Requestor rather than Requester, both seems to be legit English words.
    – Haoest
    Jan 7, 2009 at 21:08
  • 1
    I've done that once or twice as well :) Jan 7, 2009 at 22:00
  • 1
    Having a verb in the class name always sounds wrong to me. Plus it always leads to some duplication in the usage (ie: VendorHelpDocRequester.request()). I'd prefer just the plural form like `VendorHelpDocs.request()' Jun 15, 2016 at 15:15
20

The book Code Complete by Steve Mcconnell has a nice chapter on naming variables/classes/functions/...

2
  • that is one of my favorite books, highly recommend it Jan 7, 2009 at 22:48
  • 2
    +1 for anyone who ever mentions Code Complete!
    – Richard Ev
    Jan 8, 2009 at 11:11
17

I think this is a side effect.

It's not the actual naming that's hard. What's hard is that the process of naming makes you face the horrible fact that you have no idea what the hell you're doing.

12

I actually just heard this quote yesterday, through the Signal vs. Noise blog at 37Signals, and I certainly agree with it:

"There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton

2
8

It's good that it's difficult. It's forcing you to think about the problem, and what the class is actually supposed to do. Good names can help lead to good design.

6

Agreed. I like to keep my type names and variables as descriptive as possible without being too horrendously long, but sometimes there's just a certain concept that you can't find a good word for.

In that case, it always helps me to ask a coworker for input - even if they don't ultimately help, it usually helps me to at least explain it out loud and get my wheels turning.

6

I was just writing on naming conventions last month: http://caseysoftware.com/blog/useful-naming-conventions

The gist of it:

verbAdjectiveNounStructure - with Structure and Adjective as optional parts

For verbs, I stick to action verbs: save, delete, notify, update, or generate. Once in a while, I use "process" but only to specifically refer to queues or work backlogs.

For nouns, I use the class or object being interacted with. In web2project, this is often Tasks or Projects. If it's Javascript interacting with the page, it might be body or table. The point is that the code clearly describes the object it's interacting with.

The structure is optional because it's unique to the situation. A listing screen might request a List or an Array. One of the core functions used in the Project List for web2project is simply getProjectList. It doesn't modify the underlying data, just the representation of the data.

The adjectives are something else entirely. They are used as modifiers to the noun. Something as simple as getOpenProjects might be easily implemented with a getProjects and a switch parameter, but this tends to generate methods which require quite a bit of understanding of the underlying data and/or structure of the object... not necessarily something you want to encourage. By having more explicit and specific functions, you can completely wrap and hide the implementation from the code using it. Isn't that one of the points of OO?

5

More so than just naming a class, creating an appropriate package structure can be a difficult but rewarding challenge. You need to consider separating the concerns of your modules and how they relate to the vision of the application.

Consider the layout of your app now:

  • App
    • VendorDocRequester (read from web service and provide data)
    • VendorDocViewer (use requester to provide vendor docs)

I would venture to guess that there's a lot going on inside a few classes. If you were to refactor this into a more MVC-ified approach, and allow small classes to handle individual duties, you might end up with something like:

  • App
    • VendorDocs
      • Model
        • Document (plain object that holds data)
        • WebServiceConsumer (deal with nitty gritty in web service)
      • Controller
        • DatabaseAdapter (handle persistance using ORM or other method)
        • WebServiceAdapter (utilize Consumer to grab a Document and stick it in database)
      • View
        • HelpViewer (use DBAdapter to spit out the documention)

Then your class names rely on the namespace to provide full context. The classes themselves can be inherently related to application without needing to explicitly say so. Class names are simpler and easier to define as a result!

One other very important suggestion: please do yourself a favor and pick up a copy of Head First Design Patterns. It's a fantastic, easy-reading book that will help you organize your application and write better code. Appreciating design patterns will help you to understanding that many of the problems you encounter have already been solved, and you'll be able to incorporate the solutions into your code.

4

Leo Brodie, in his book "Thinking Forth", wrote that the most difficult task for a programmer was naming things well, and he stated that the most important programming tool is a thesaurus.

Try using the thesaurus at http://thesaurus.reference.com/.

Beyond that, don't use Hungarian Notation EVER, avoid abbreviations, and be consistent.

Best wishes.

4
  • 1
    +1 with the note that you shouldn't use what is caled system hungarian; app hungarian can be helpful at times, especially in a programming language without a good typing system.
    – user51568
    Jan 8, 2009 at 14:22
  • I have never heard of system vs. application Hungarian notation, but neither is ever a good idea in any environment--you should always name based on WHAT, not HOW, and Hungarian is totally about how. Jan 8, 2009 at 15:59
  • @RobWilliams I think they were referring to Joel Spolsky's article Jun 3, 2015 at 17:03
  • 1
    @RobWilliams Also, are you sure about "I have never heard of X vs Y but neither is ever a good idea..." ...? :) Jun 3, 2015 at 17:05
4

In short:
I agree that good names are important, but I don't think you have to find them before implementing at all costs.

Of course its better to have a good name right from the start. But if you can't come up with one in 2 minutes, renaming later will cost less time and is the right choice from a productivity point of view.

Long:
Generally it's often not worth to think too long about a name before implementing. If you implement your class, naming it "Foo" or "Dsnfdkgx", while implementing you see what you should have named it.

Especially with Java+Eclipse, renaming things is no pain at all, as it carefully handles all references in all classes, warns you of name collisions, etc. And as long as the class is not yet in the version control repository, I don't think there's anything wrong with renaming it 5 times.

Basically, it's a question of how you think about refactoring. Personally, I like it, though it annoys my team mates sometimes, as they believe in never touch a running system. And from everything you can refactor, changing names is one of the most harmless things you can do.

3

Why not HelpDocumentServiceClient kind of a mouthful, or HelpDocumentClient...it doesn't matter it's a vendor the point is it's a client to a webservice that deals with Help documents.

And yes naming is hard.

3

There is only one sensible name for that class:

HelpRequest

Don't let the implementation details distract you from the meaning.

1
  • A year and a half later, I was about to suggest HelpLibrary for the class, but this is at least as good. It pays to read through answers first! Jul 1, 2010 at 20:35
2

Invest in a good refactoring tool!

1
  • lol. Sometimes refactoring isn't the best option (big C++ projects), but I've certainly resorted to it before. Sometimes I just have to get things done, and the names come to me later.
    – Steve S
    Jan 7, 2009 at 23:04
2

I stick to basics: VerbNoun(arguments). Examples: GetDoc(docID).

There's no need to get fancy. It will be easy to understand a year from now, whether it's you or someone else.

3
  • While this reads well, it organizes poorly because it's backwards. It's better to say DocGet() because when you also create DocAdd() DocRemove() etc they will all appear together in a list. Your method really shows how ugly it gets when you have dozens of Gets or whatnot.
    – TravisO
    Jan 7, 2009 at 20:53
  • Excellent suggestion, TravisO.
    – Jon Smock
    Jan 7, 2009 at 20:54
  • I wouldnt use a verb for a class normally. Jan 7, 2009 at 22:47
2

For me I don't care how long a method or class name is as long as its descriptive and in the correct library. Long gone are the days where you should remember where each part of the API resides.

Intelisense exists for all major languages. Therefore when using a 3rd party API I like to use its intelisense for the documentation as opposed to using the 'actual' documentation.

With that in mind I am fine to create a method name such as

StevesPostOnMethodNamesBeingLongOrShort

Long - but so what. Who doesnt use 24inch screens these days!

0
1

I have to agree that naming is an art. It gets a little easier if your class is following a certain "desigh pattern" (factory etc).

1

This is one of the reasons to have a coding standard. Having a standard tends to assist coming up with names when required. It helps free up your mind to use for other more interesting things! (-:

I'd recommend reading the relevant chapter of Steve McConnell's Code Complete (Amazon link) which goes into several rules to assist readability and even maintainability.

HTH

cheers,

Rob

1

Nope, debugging is the most difficult thing thing for me! :-)

1
  • debugging usually comes down to asking the right question. There's this number game where you have to guess a number from 1 to 1000. If your guess is too low or high, the console tell you so, and you have only 10 tries. What do you do?
    – Haoest
    Jan 7, 2009 at 22:19
1

DocumentFetcher? It's hard to say without context.

It can help to act like a mathematician and borrow/invent a lexicon for your domain as you go: settle on short plain words that suggest the concept without spelling it out every time. Too often I see long latinate phrases that get turned into acronyms, making you need a dictionary for the acronyms anyway.

1

The language you use to describe the problem, is the language you should use for the variables, methods, objects, classes, etc. Loosely, nouns match objects and verbs match methods. If you're missing words to describe the problem, you're also missing a full understanding (specification) of the problem.

If it's just choosing between a set of names, then it should be driven by the conventions you are using to build the system. If you've come to a new spot, uncovered by previous conventions, then it's always worth spending some effort on trying extend them (properly, consistently) to cover this new case.

If in doubt, sleep on it, and pick the first most obvious name, the next morning :-)

If you wake up one day and realize you were wrong, then change it right away.

Paul.

BTW: Document.fetch() is pretty obvious.

1

I find I have the most trouble in local variables. For example, I want to create an object of type DocGetter. So I know it's a DocGetter. Why do I need to give it another name? I usually end up giving it a name like dg (for DocGetter) or temp or something equally nondescriptive.

1

Don't forget design patterns (not just the GoF ones) are a good way of providing a common vocabulary and their names should be used whenever one fits the situation. That will even help newcomers that are familiar with the nomenclature to quickly understand the architecture. Is this class you're working on supposed to act like a Proxy, or even a Façade ?

1

Shouldn't the vendor documentation be the object? I mean, that one is tangible, and not just as some anthropomorphization of a part of your program. So, you might have a VendorDocumentation class with a constructor that fetches the information. I think that if a class name contains a verb, often something has gone wrong.

1

I definitely feel you. And I feel your pain. Every name I think of just seems rubbish to me. It all seems so generic and I want to eventually learn how to inject a bit of flair and creativity into my names, making them really reflect what they describe.

One suggestion I have is to consult a Thesaurus. Word has a good one, as does Mac OS X. That can really help me get my head out of the clouds and gives me a good starting place as well as some inspiration.

0

If the name would explain itself to a lay programmer then there's probably no need to change it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.