views:

508

answers:

11

So, I often have trouble describing a function in a succinct name. It's usually not a problem in functions that are made for reuse, but often a large process needs to be broken into sub-functions. Often these get strange names, such as connectionsToAccessLines or handleWallVisionSplit or something like that. And while these functions only do one thing, it's very tough to come up with a good name for them because they really are just one part of a larger algorithm.

What do you do in this situation? It's very frustrating.

+9  A: 

I would rather ridiculously long method names in the context of a larger algorithm because it reduces the need to look at the implementation of the function.

A name like ReadPropertiesFromFileThenWriteToSession is better than ReadProps.

Adam Sills
Yes, longer names are definitely preferable to short, ambigious names like Doaction(int id);But don't go overboard either. If you can't describe in one word or short phrase what the method is doing, break it out into more methods :)
Jack Marchetti
I'd say a problem with that is when you want one method to eventually call more methods. Method1 calls DoXAndYIfZ (which encapsulates some variable/state checking), which calls X and Y separately.In cases like this, when you don't want the branching logic in the higher-level method, you can't just "add more methods" to it. So your name gets longer.
Adam Sills
...though in general I'd agree with you with only "when having trouble coming up with a short name, just make a long name" as a caveat! :)
Adam Sills
I agree, don't think too hard, use the long name until a better name pops into your head. Don't waste time thinking of function names, just describe what they do as succinctly as possible and move on. Go with what you have and with refactoring tools, it is super easy to rename a function.
Kekoa
If you're exposing an API that will stay the same for a long time, then it would be worth it to take the extra time to think of a good name for people down the road.
Kekoa
I find that it's best to coin a new word to make your method memorable, so rather than "ReadProps" I would use "Propertize."
mquander
Steve McConnell in Code Complete talks about how really long names are nearly as bad as really short ones. (Your particular name sounds like a method that ought to be split in two, anyway.)
Jim Ferrans
Steve Jessop
Actually, I'm cheating a bit there, since reading from a file object is not necessarily a const operation (it might move a position pointer or whatever). But once you've established the order of the operands, the point is you don't need "fromXtoY" in the function name, you just overload. Or, in C++, use templates even.
Steve Jessop
A: 

Your functions should really state what it is they do! But not in an overly verbose manner. This is something that you will master over time, it takes a bit of practice getting a function right.

Have a quick read of this to see some stuff I wrote about this kind of thing a while back :) Make sure you follow through to the other article that inspired me to write it and check out the comments.

OJ
A: 

One suggestion from Refactoring books is to look at the long algorithm and at every place you feel that there is a block in the code you can describe with a one line comment refactor this block into a private function and use what is in the single line as a name for the function. That could be really long but if it helps you reading the algorithm in a quick way it is perfectly well. Code complete mentions a good range to between 9 and 15 charackters.

And don't worry if it is a private helper function refactoring the name later is no problem

Janusz
+2  A: 

Whenever I hit a brick wall trying to name a function or procedure, I go back and think very hard about what I think it is for. Often if a name doesn't easily suggest itself, it's a hint that I haven't thought through what the function or procedure is really supposed to do.

You've got a process that needs to do A, B, C, ..., X, Y and Z; you can't name the procedure doABCDEFGHIJKLMNOPQRSTUVWXYZ. You have to find some logical medium-level grouping (perhaps several layers of groupings) that divide the process up.

Sometimes finding the right name requires moving the code around so that it is in more logical chunks.

Another help is to encapsulate the functions/procedures (depending on the features of the language you're using) so that the name can be shorter (since its name can be interpreted within the context of its container). For example, the "openFile" procedure should normally just open a file for reading; but in the context of a "UserPrefsFile" class, it might have a more specific meaning.

Jeffrey Kemp
+5  A: 

The late, great Phil Karlton quipped famously: There are only two hard problems in computer science - naming things and cache invalidation. My experience leads me to believe there is much truth in that.

Naming things well is an art as much as it is a science, and as such there are not any hard and fast rules. That said, I sometimes read Ottinger's rules for Variable and Class Naming, which has some good heuristics to keep in mind. One of my favorites is to use noun phrases, such as - person.getName(), or bitTorrentClient.findPeersFromTracker(). In both of these cases, the intent of the line of code reads similar to a phrase in English.

Cameron Pope
+1 -- the Ottinger link is good.
Jim Ferrans
"get name" and "find peers from tracker" are verb phrases :)
Jeffrey Kemp
http://agileinaflash.blogspot.com/2009/02/meaningful-names.html is the short form of my naming rules. The long form is chapter 2 of Clean Code.
tottinge
+5  A: 

Sometimes you can reduce a function's name length by simply re-wording the name. Instead of:

void RetrievePropertiesFromRemoteStore()

You could use:

void RetrieveRemoteProperties()

Instead of:

bool CheckToSeeIfUserIsAuthorized()

Use:

bool IsUserAuthorized()

Another way to reduce it is to rethink what the function does. Instead of one function like this:

void GetUserProfileAndSetUpSession()

You could have:

void GetUserProfile()
void SetupSession()
jasonh
in the case of IsUserAuthorized, if it's a method in a class, then user.IsAuthorized() or service.IsAuthorized(user) is even better.
plinth
+12  A: 

Sometimes if you can't come up with a good function name it's an indication that the function doesn't have a nice, crisp focus and needs to be refactored. If it's a class method, perhaps the class needs refactoring too.

But it's well worth the trouble finding the best possible names, since it makes your code so much more understandable and usable.

Update: Many software engineering authors have talked about the importance of naming. Henry F. Ledgard's Programming Proverbs (1975) and Brian Kernighan and P.J. Plaugher's Elements of Programming Style (1978) were early ones and are still worth reading. Steve McConnell's wonderful Code Complete (2nd Edition, 2005) is a more recent example, devoting an entire chapter to the topic.

Elements of Programming Style was in part patterned on Strunk and White's Elements of Style, which actually has a surprising relevance. Their stress on making prose clear and extremely concise applies to our technical writing and comments (and naming), but I've always seen it as analogous to what we do when we refactor and improve our code.

Jim Ferrans
Yes. Agree strongly.
PeterAllenWebb
Except sometimes you can't split a function into parts due to efficiency. For example, iterating through a set and simultaneously looking for those values in another, and when found delete them both, but first put them in a third container which is returned, aka MoveSetUnionToNewSet. It would hugely increase the algorithmic complexity to split this function up.
rlbond
Very true, and Strunk and White would not have suggested removing words necessary for meaning. "MoveSetUnionToNewSet" certainly isn't too long in my book, though perhaps clearer would be "Set ExtractSetUnion(Set a, Set b)".
Jim Ferrans
A: 

Heh. It struck me upon reading the question title that the act of programming could be described as "trouble coming up with good names for functions".

PeterAllenWebb
A: 

You can use numbering and postfixes "_*" to avoid too many names in your code:

void DoX()
void DoX_Decode1()           <-- this name shows that this function is only used by DoX()
void DoX_Decode2()
void DoX_Decode3()
void DoX_Find1()
void DoX_Find2()
void DoX_Find3()

You can also group similar functionality with prefixes:

void tcpip_ShowConnectDialog()
void tcpip_AcceptConnections()
void logging_WriteToFile()
void logging_UpdateLogWindow()

This way you get unique function names (helps with searching and search-and-replacing) and still keep them relatively short. You also avoid the hassle of extracting them to separate class and separate code-file. Just keep the prefixes short so that you can easily ignore and see past them.

AareP
DoX_Decode2 means absolutely nothing to me. And, maybe you are using a no-OO language, but DoX.find() and DoX.Decode() is way better IMO. I say that because you were talking about separating class.. so I guess it's OO. Lastly, one shouldn't avoid refactoring because of the "hassle of extracting them".. with a good IDE (cough* cough* eclipse cough*), renaming and extracting method is really an enjoyable thing to do. :)
Yeah, I'm really old-fashioned in that way. Hate having a separate class and file for every little thing. For me it's practically impossible to make you code shorter (by refactoring) when all you see is high-level abstractions, that all make "sence", and "fight" for their existence (sorry for so far-fetched analogies). Also I believe more in lists, than in hierarchies or trees. For example I would much rather use multiple excel documents with 2-dimensional tables, that one xml-document with hierarchical tree-structure (if that makes any sense to you). That's why I hate OO class hierarchies.
AareP
A: 

When you run out of sensible names, just use letters of the alphabet. Once you run out of those, pick random words from the dictionary. This way, they can never fire you, because you're the only one who understands the code.

Breton
Hah! See http://stackoverflow.com/questions/961942/what-is-the-worst-programming-language-you-ever-worked-with for examples of several languages where you almost only had single letters of the alphabet. A BASIC I saw once only allowed names like A and B1 for integers, and $D and $R2 for strings. Hideous.
Jim Ferrans
A: 

By using an object oriented approach, it helps to reduce this problem.. connectionsToAccessLines -> connexion.connect(System.getAccessLines());

handleWallVisionSplit -> this one, I'm not really sure what it does :D But, I'd say something like: wall.handleVision(Wall.split); or whatever, I think you understand what I mean.

Also, sometimes, when it's really hard to name a too specific function, it can be because the code isn't enough high level. For instance: readSecondWordOfLine(a_line) -> line.split()[1].

Or, sort(sortWithSecondWordOfLine()) could become, sort(line=>split(line)[1]).. I know it's not always doable as clean as that in all languages, but you get my point. With C++, for example, you can use bind and stl composites to build one liner expression instead of creating a new method.

So, I could summarize that by saying, if you have a too technical method - which is usually really short because otherwise the name would be easy to find by abstracting the functionalities- it's good to create a new function/class more generalized with an abstract name and use it directly in the first function.