Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose function names? [duplicate]

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?

like image 342
KthProg Avatar asked Dec 04 '15 16:12

KthProg


People also ask

What makes a good function name?

A function name should clearly indicate what the function does. You don't have to scroll around, open the function source code to understand how it works. Also, the name should describe only one concept: one-to-one relation. In the end, you probably don't want to communicate like these guys!

Can two functions have the same name in C?

Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures.

Can function have same name?

It's just that an overloaded function has the same name as some other function. An overloaded function must have a parameter list that's different from all other functions with the same name so the compiler has some way to tell the functions apart.


1 Answers

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.

like image 195
Felipe Alarcon Avatar answered Oct 21 '22 09:10

Felipe Alarcon