5

We're having a discussion at work, because of my tendency to name functions based on what they do.

For instance:

function notifyUserOfSomeThingThatHappened(){
    // notification code
}

My coworker believes (and I kind of agree) that this function should be named based on why it's being called, rather than what it does, since what it does could change.

Something like this:

function someThingHappened(){
    // notification code
    // possible new code in the future
}

I agree with this, but with a catch: I think we should name functions that will only ever do one thing by their actual contents, but other functions by their reason for being called, like this:

function someThingHappened(){
    notifyUserThatSomeThingHappened();
    // possible new code in the future
}

function notifyUserThatSomeThingHappened(){
    // original code
}

What are the best practices for naming functions? Why are these practices used? What are the advantages of one over the other?

KthProg
  • 2,050
  • 1
  • 24
  • 32
  • I would have to go with `function someThingHappened(){ notifyUserThatSomeThingHappened(); // possible new code in the future }` because it will let you reuse the `somethinghappened()` function for more than one situation without needing to add much more code. – www139 Dec 04 '15 at 16:45
  • I found duplicates and this should probably be closed to be honest. – KthProg Dec 04 '15 at 17:13
  • i wouldn't say opinion-based, since I'm asking for explanations and comparisons. Without a reason, it shouldn't be here. – KthProg Dec 04 '15 at 17:15

1 Answers1

9

A simple rule is:
Function names should be verbs if the function changes the state of the program, and nouns if they're used to return a certain value.

Another thing to keep in mind is consistency.

If you use the name getName be consistent and don't write somewhere else retrieveName as this might confuse your co-workers.

Also keep in mind that different languages do indeed have different name conventions so you should always check what is the best way to name functions and variables in the language you're working with.

Felipe Alarcon
  • 948
  • 11
  • 19