Anyone else find naming classes and methods one of the most difficult parts in programming?

Naming Conventions

Naming Conventions Problem Overview


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?

Naming Conventions Solutions


Solution 1 - Naming Conventions

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.

Solution 2 - Naming Conventions

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

Solution 3 - Naming Conventions

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."

Solution 4 - Naming Conventions

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?

Solution 5 - Naming Conventions

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.

Solution 6 - Naming Conventions

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.

Solution 7 - Naming Conventions

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

Solution 8 - Naming Conventions

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.

Solution 9 - Naming Conventions

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

Solution 10 - Naming Conventions

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.

Solution 11 - Naming Conventions

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.

Solution 12 - Naming Conventions

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?

Solution 13 - Naming Conventions

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.

Solution 14 - Naming Conventions

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.

Solution 15 - Naming Conventions

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.

Solution 16 - Naming Conventions

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.

Solution 17 - Naming Conventions

There is only one sensible name for that class:

HelpRequest

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

Solution 18 - Naming Conventions

Invest in a good refactoring tool!

Solution 19 - Naming Conventions

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.

Solution 20 - Naming Conventions

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!

Solution 21 - Naming Conventions

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).

Solution 22 - Naming Conventions

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

Solution 23 - Naming Conventions

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

Solution 24 - Naming Conventions

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.

Solution 25 - Naming Conventions

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.

Solution 26 - Naming Conventions

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.

Solution 27 - Naming Conventions

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 ?

Solution 28 - Naming Conventions

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.

Solution 29 - Naming Conventions

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.

Solution 30 - Naming Conventions

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

Solution 31 - Naming Conventions

I don't find it difficult. If you can't name it then maybe you don't need it. The better your design the easier it will to name the things that your design does.

Now temp variables, that's a different story. :)

Solution 32 - Naming Conventions

Well I see it from another perspective, its one of the most important things if you want your code to be readable by others.

Try to make it descriptive and if its from a third party, why not include the name [of the third party] on the class or method name.

If it takes to long, just use any name, afterwords you can change it.

Solution 33 - Naming Conventions

I feel your pain. :/

I wish there were a tool for reviewing source code in conjunction with a data dictionary (a file describing the various variable / method names, I guess sort of like javadoc), so you could write code like this:

class Battery 
{
   double I; // current
   double T; // temperature
   double V; // voltage
   double Q; // charge

   void update(double Inew, double dt) { I = Inew; Q += I*dt; }
   // ... etc ...
};

and the code-reviewing tool could do a number of different things to make it easier to view code in context, including display reminders that I = current (e.g. in a pane on the right-hand-side of the window it would display variable definitions/semantics/comments for the place in the code you are clicking on), or even allow you to do "virtual refactoring" where as a code reviewer you could rename something to your liking for readability/display reasons without actually changing the code stored on disk.

As much as I like self-describing names, I hate reading things like BatteryFilteredCurrentInMilliamps. Often in embedded systems we are modeling objects based on algebraic equations and names like that in equations get very cumbersome. (on the other hand, an "I" with a hat on top and a subscript "d" and a superscript "*" is rather confusing.)

I'm an EE / systems engineer first with minor software responsibilities and in the end I really don't care what a variable is named as long as I have a convenient way of telling what it is, and mapping it into my own internal model of the system being controlled.

Solution 34 - Naming Conventions

It usually feels very natural to me. I always make very short methods, never more than 6 lines of Smalltalk code (automatically formatted), so I really don't have any trouble saying what this method is about.

Sometimes class names are difficult, because the word I want to choose is in use somewhere in the system, because sometimes the same word has different meanings in separate contexts. I wish that in those cases, some Wikipedia-like syntax would be allowed, so i could name my class "Task (To do list item)". Until that is legal, I make a large German-style word out of it: ToDoListItemTask. You might have guessed it: My method names can be very long, too. But I think they are readable.

So, in your case, your class is a "getter", or retriever, or whatever. Are you sure that this should be modelled in class? Shouldn't rather the vendor doc be able to request itself? Something like vendorDoc.requestFrom(source); would be easier to name, wouldn't it?

cheers,

niko

Solution 35 - Naming Conventions

When every sensible name seems too long or ambigious, you can try using something a little less sensible, e.g.:

  • class GoForHelpLassie
  • class DunnoAskTechSupport
  • class RTFVM [where V is for Vendor]

Make sure the name is really unique and there is a descriptive comment at the top of the class, because anyone who sees it in the code is going to need to look it up to find out what it does (but when they do, they'll probably find it easier to remember).

Solution 36 - Naming Conventions

Another reason why every software developer should have writing and communication skills.

PD: I believe a vast vocabulary is also important.

Solution 37 - Naming Conventions

What I do is check if it's to long if I can't remember it to long

Solution 38 - Naming Conventions

If 8 out of 10 people understand it, then you can safely assume that it is understandable and readable and clear. There will always be those 1 or 2 nit pickers that will try and fault you for no reason other than that they are petty.

Solution 39 - Naming Conventions

I find its easier to choose a name once something is finished. Refactor->Rename ftw.

Solution 40 - Naming Conventions

If you are a .NET developer I strongly recommend reading the BradA, Cwalina book - Framework Design guidelines. Its all explained there.

Solution 41 - Naming Conventions

Just summarize the method/class in 'One Word', answering what it mean for? And there should be no equivalent for that word.

Solution 42 - Naming Conventions

Not really. Considering all the difficult things you have to understand in coding, saying that naming classes and methods is one of the most difficult things in programming is preposterous. Don't get me wrong, it's sometimes hard to think of a good name but let's be real here. I'll go as far to say that it's one of the easiest parts of programming.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHaoestView Question on Stackoverflow
Solution 1 - Naming ConventionsTravisOView Answer on Stackoverflow
Solution 2 - Naming ConventionsToon KrijtheView Answer on Stackoverflow
Solution 3 - Naming ConventionsJoel SpolskyView Answer on Stackoverflow
Solution 4 - Naming ConventionsBrad BarkerView Answer on Stackoverflow
Solution 5 - Naming ConventionskrosenvoldView Answer on Stackoverflow
Solution 6 - Naming ConventionswillcodejavaforfoodView Answer on Stackoverflow
Solution 7 - Naming ConventionsEmile VrijdagsView Answer on Stackoverflow
Solution 8 - Naming ConventionsNosrednaView Answer on Stackoverflow
Solution 9 - Naming ConventionsJonathan SchusterView Answer on Stackoverflow
Solution 10 - Naming ConventionsJW.View Answer on Stackoverflow
Solution 11 - Naming ConventionsDaniel SchafferView Answer on Stackoverflow
Solution 12 - Naming ConventionsCaseySoftwareView Answer on Stackoverflow
Solution 13 - Naming ConventionsMike GriffithView Answer on Stackoverflow
Solution 14 - Naming ConventionsRob WilliamsView Answer on Stackoverflow
Solution 15 - Naming ConventionsLena SchimmelView Answer on Stackoverflow
Solution 16 - Naming ConventionsJoshBerkeView Answer on Stackoverflow
Solution 17 - Naming ConventionsAngus GlashierView Answer on Stackoverflow
Solution 18 - Naming ConventionsTGnatView Answer on Stackoverflow
Solution 19 - Naming ConventionsLJ.View Answer on Stackoverflow
Solution 20 - Naming ConventionsSteveView Answer on Stackoverflow
Solution 21 - Naming ConventionsOtávio DécioView Answer on Stackoverflow
Solution 22 - Naming ConventionsRob WellsView Answer on Stackoverflow
Solution 23 - Naming ConventionsStew SView Answer on Stackoverflow
Solution 24 - Naming ConventionsDarius BaconView Answer on Stackoverflow
Solution 25 - Naming ConventionsPaul W HomerView Answer on Stackoverflow
Solution 26 - Naming ConventionsJason BakerView Answer on Stackoverflow
Solution 27 - Naming ConventionsHerrmannView Answer on Stackoverflow
Solution 28 - Naming ConventionsSvanteView Answer on Stackoverflow
Solution 29 - Naming ConventionsJohn GallagherView Answer on Stackoverflow
Solution 30 - Naming ConventionsdreamlaxView Answer on Stackoverflow
Solution 31 - Naming ConventionsbruceatkView Answer on Stackoverflow
Solution 32 - Naming ConventionsGeries HandalView Answer on Stackoverflow
Solution 33 - Naming ConventionsJason SView Answer on Stackoverflow
Solution 34 - Naming Conventionsnes1983View Answer on Stackoverflow
Solution 35 - Naming Conventionstoo much phpView Answer on Stackoverflow
Solution 36 - Naming ConventionsDemian GarciaView Answer on Stackoverflow
Solution 37 - Naming ConventionsEnderView Answer on Stackoverflow
Solution 38 - Naming ConventionsJoboView Answer on Stackoverflow
Solution 39 - Naming ConventionsFrank SchwietermanView Answer on Stackoverflow
Solution 40 - Naming ConventionsView Answer on Stackoverflow
Solution 41 - Naming ConventionsDhanapalView Answer on Stackoverflow
Solution 42 - Naming ConventionsRayneView Answer on Stackoverflow