Best practices for naming functions

Asked

Viewed 6,194 times

26

I would like to know which tenses are most used to name the functions.

For example, there is a more suitable in this hypothetical case?

Calculadora calculadora;
calculadora.soma(3, 4);
calculadora.somar(3, 4);

or

int obtemValor();
int obterValor();

What is the best verbal time to use when naming functions?

  • 1
  • It is a broader and specific question for C# but it may help to see how to name things in general in the code: http://answall.com/q/31646/101

  • @bigown Actually the question had tags of C# and Java, and I removed it. I thought it would work better if it was generic, I don’t know if I did well or not.

  • 3

    From the answers, I think the question is broad. Although it has been closed as based on opinions, I think the problem is amplitude, especially given to responses of utluiz and bigown, which are objective, but at different angles of the same problem. The answer of utluiz seems to me very clear if focus on OOP, the bigown seems to me very comprehensive in more varied development contexts, but the important thing is that both answers show that you can have very objective answers. Only the question doesn’t help much in the way it is, so I agree with leaving it pending.

4 answers

29


TL;DR

This is a topic whose personal opinion influences a lot, but there are some general good practices that can be extracted for nomenclature and standardization of methods.

Standard

Each language suggests or even limits the nomenclature of methods and functions.

Usually when dealing with objects the preference is to use the pattern Camel Case, that is, the initials of the words are capitalized:

comerCoxinha();

When we talk about functions in languages such as Python, PHP or Javascript, it is not uncommon to find the use of underline or underlined:

comer_kibe();

In this aspect, the important thing is to maintain pattern and consistency both in how the words that make up the name are linked as in relation to the verb, language and word order.

Grammar class and tense

Different grammatical classes such as verbs, nouns, prepositions and adjectives can be used to name functions and methods if used within the correct context.

Nouns and Adjectives

Nouns and adjectives are usually used to name variables, classes, and attributes, since these elements usually refer to something or someone.

Example:

class Carro {
}
class CarroColorido extends Carro {
    String cor;
}
carrinhoVermelho = new CarroColorido("vermelho");

Note how CarroColorido and carrinhoVermelho are compositions of noun and adjective that help to understand what these elements refer to.

Verbs

There is no general consensus, but many books and implementations suggest the use of verbs in methods, since they denote stocks of an object.

However, in practice many end up using different tenses. For example, some understand that they should use infinitive tenses. In this case, the correct for the Calculadora would be the method somar.

Others prefer to use the imperative, as ordering the object to do something. In this case, the order for the Calculadora would be some.

When naming the method soma:

  • Or you are using the imperative incorrectly, which is not uncommon in Brazil;
  • Or are you using the noun to refer to the action of somar, as saying to the object "make the sum".

A lot of confusion arises because methods named in English can have both the connotation of imperative and infinitive. For example, execute() can be understood as much as to execute (perform, in infinitive) how much execute (perform, in the imperative).

Methods getters and setters

Attribute access methods are usually an exception and are named according to their attributes.

Most of the time you’ll find something like setNome(String) and getNome() to change and recover the value of an attribute, respectively nome.

It is also not uncommon to find such methods without prefixes get and set, such as nome() to recover and nome(String) to change. Particularly I prefix this pattern.

Fluent interfaces

Several grammatical classes end up being welcome when we use the standard Fluent Interfaces.

The goal here is to make the code more readable and easy to use and not simply follow a pattern blindly.

An example of a possible database access API:

query = Consulta.select("nome").from("cliente")
            .where(Criterio.maiorOuIgual("credito", 1000))
            .and(Criterio.igual("cidade", "Foz do Iguaçu"));

Although I have mixed languages, nouns, prepositions, the above code can be easily understood. The parts in English are SQL language and the rest can be understood without reference to the documentation.

Putting it all together

As I said, there is no rule, but it is recommended to follow a standard. Even so, there are different patterns for different contexts that, coupled with different techniques, allow a coherent class model.

I believe that the question to be asked of each method created is:

From the point of view of client code (which calls the method), this name makes sense and makes clear the purpose of the method, including its side effects?

  • 4

    The fourth point says enough from my point of view. + 1.

  • 1

    I understand that some people don’t like getNome() it is even find interesting to change the get for trazer, retornar, obter, etc. to stay more consistent, but since I read somewhere a long time ago (I think in the Javabeans specification) that if it is not used get some tools may not map the attribute to the respective method getter, I was afraid I wouldn’t use it.

  • @Piovezan great observation. Actually many tools will not work without following the Java Beans standard. But overall, newer tools and frameworks make use of annotations and other alternative mechanisms to map attributes. I myself when writing some reflection routine do not make more use of getters or setters because it gives more headache than it helps. It is easier to directly access the attributes and add meta information with annotations, in addition to being faster. In all my years, I’ve never seen a case where a getter method justifies its existence.

  • Whenever I found some logic within a getter method this was usually a sign of trouble. This is true mainly because it means that the object is not immutable. I think the only exception are delegate objects.

  • 1

    @You seem to be talking about Project Lombok. Interestingly, I didn’t. : ) Using this plugin on Ides really loses the sense to discuss the nomenclature of getters, since they become implicit (invisible). Now, on the unchanging objects, although immutability is desirable I think there is no rule that all objects must be immutable, although some people think so.

  • @Piovezan I hadn’t exactly thought about Ombok, but it’s an example. But what I meant with respect to getters and setters is that it is not worth using the pattern when it will be useful only in 10% or less of the code. I only use get and set when strictly necessary or in legacy systems that adopt this standard. In my opinion, the code gets cleaner and easier to understand. With Lombok is even better, because Beans are practically only the definition of attributes.

  • 1

    When you spoke of avoiding getters I had understood that it was only about hiding them. But you’re talking about avoiding getters and setters as in Why getters and setters are evil or How do you avoid getters and setters, Right? I get it now. In fact, it is such an interesting point that I think it could be added to the answer: "Avoid them when possible and you will not fall into the problem of naming them"

  • @Piovezan In my answer, what I meant was that I prefix do not use the prefixes get and set. In this case, an attribute nome could be accessed by the method nome() instead of getNome(). On the other hand, I am referring to Beans and not to other objects. On objects that do some kind of processing or logic I almost never create a getter or Setter.

Show 3 more comments

15

Each team has its own standard, there is nothing universal. I studied the subject and concluded that each group of people chooses what they think best, but I found a pattern in better written codes, usually by recognized professionals. Also I found some style guides that indicate certain patterns, some of them that can be considered "official". They varied according to language. So I’ll talk about what I found most common. Your mileage may vary.

Some "little rules"

The most common is to use verbs to designate methods and functions, but there are cases that another form of expression may be useful.

The most commonly used time is the imperative, after all you are ordering an action. Expressions whose main component are verbs are also used. A classic example is the getField() (much used in getters and setters). This is easily seen in English.

When methods have a specific function they can use other tenses or even be omitted giving rise to the noun it will produce. For example:

  • in events when it indicates something that is yet to happen it is common to use the infinitive. When the event has already happened it is more common to use the past participle. When the event is occurring the gerund is used.

  • if the method or function will return a boolean it is common to have a specific construction indicating a capacity. Ex.: is, can, has, isThere (some prefer to use only the has), allow (which may be the same as can). Or in English é or eh, está or estah (usually followed by a verb in the participle or adjective), pode (usually followed by a verb in the infinitive), tem (probably followed by a noun), existe (followed by a noun), contém. The plural can be used, or another conjugation, e.g..: foiTentado or tentou. Note the use of the 3rd person. In some cases the verb may be omitted, but you should avoid doing this. There are cases where the prefix Try indicates this situation, the name says you should try and inform whether it worked or not, it is a convention. It is written thinking it will be used in a question (a condition/predicate).

  • when the method actually returns a property, a feature, an obvious object, in short, when it is obvious that what it is trying to get is simple information, it is possible to use a noun, but you cannot abuse it. We can say that it is a form of abbreviation of what the method actually does. Libraries do this in methods such as IndexOf that deep down you’re saying GetIndexOf, or HashCode, that would be CalculateHashCode, or Size, replacing a property (GetSize), Sin (CalculateSin). Note that there is a difference between a pure property that in general must be a noun or adjective and a method that is replacing a property.

    When a property needs more than trivial processing to obtain the result, it is better to use a method than a property, to make it clear that there is a cost in calling that. Some people think that you should still maintain the verb pattern and put at least one Get at the front. Others think this would cause an unnecessary proliferation of Get or Calculate or other obvious verbs. I have seen some people separate into verbs what changes the object and nouns which produces an independent result, when there is purity. Something to consider when eliminating the obvious prefix verb.

  • in fluent interface or places where the use has a specific purpose, the expressions can be used a little differently. It is more important to be fluent in reading, although this most often works much better in English than Portuguese.

Em português parece que há mais confusão. Alguns entender que o get is obter, others think it’s obtenha. I see people mixing English with Portuguese in cases like this, but when one decides to translate everything I see it is very common to use the obter. But if we look strictly for the tongue, this is a mistake. toGet would be obter. If this analysis were not enough, some guides are quite clear in saying that the time to be used is the imperative, then the translation would be obtenhaSee comments below for translation variations.

So the ideal in these examples would be to call calculadora.some(3, 4); and obtenhaValor();. No one considered will say it’s wrong to use calculadora.soma(3, 4); and obterValor();. Some should even require it to be this way, after all it must be the reason the answer has negative.

The idea is to give the reading fluent: "with the calculator add 3 and 4", or "with the variable name separate by comma" (nome.split(',')) or simply "get the value". Hence some even think that the article should not be omitted to give more fluency. It is rare to see codes that do not omit. I can’t say which one is right, I know which one I’m used to. That’s where pure opinion comes in.

Try reading in the infinitive, it looks like a talking machine. Is that how you prefer it? Have you gotten used to it? Okay, I have nothing against, it’s your taste. Do you want to make a mental translation of what is actually written for what you really think, that is, write in the infinitive but read in the imperative? OK for me too. I do it myself in fast codes where I’m not thinking much about how it will be used.

I see they use the infinitive pattern in Portuguese frequently. I believe it is because they follow the pattern of others without making a question of which is correct.

Within this principle the name should not describe what the function does, it should indicate the command. The name should indicate the behavior and not the implementation. It is subtle and even subjective, but it seems to me that the imperative pulls by the behavior and the infinitive pulls by the implementation.

A common error is trying to use a method to change a property. Then the name will already be wrong. It is better to name an action that happens to change a property. Nomenclature is another and it becomes clearer what the behavior is. Eventually having the property changed can even be considered an abstraction leak.

Completion

But what happens if you don’t follow this pattern? Nothing! It’s still understandable. Ideally, always be consistent. The most important thing is the name define the goal well, what it is telling you to do. The problem gets bigger when name indicates one thing and does another. Remembering that pro compiler obviously doesn’t make the slightest difference.

I’m not here trying to change the way people do. If someone has done it one way her whole life she won’t want to change because she read what I wrote here, even though she realizes it makes sense.

Maintain consistency. The important thing is to know what you’re doing. Always! And more importantly, rules were made to be broken when necessary.

The question focuses on functions. For variables, classes and other forms, the pattern should be different, including about the Casing, I have a answer that talks about this in C#, it would make no sense to repeat here.

The subject yields and it fits more specific questions. In fact I agree with the closing of the question because it is broad, not based on opinions.

Just to quote some references I found quickly, beyond the question linked above where I quote the source of the general recommendations I posted:

Many books and articles do not speak clearly about using the imperative, but all examples are like this. The book Clean Code is one of the classics to learn about it. Although I don’t agree with everything in it. Another is the Code Complete.

  • As I said in the other answer, I think the main reason people use English is that the meaning may vary depending on the context in which it is found. Now the endings for gerunds are a little perplexed, and too centralised, and the terms become too objective, which is usually intended, but on the other hand what you want to avoid in a function. In the case of get for example, I would say that is another reason to write names incognito to the context, both can mean pega, as busca or something else. And yes, I do agree with the case of bools.

  • Yes, I gave a simplified, the translation can be made for other things, but the time would be this same, then it would be pegue, busque, traga. Although the specific names I think need to be well thought out too, because it may all seem synonymous, but small differences can pass a wrong idea. In the related question that I Linkei above (in question comment) I speak of several names that are similar. You need to choose right. It may not seem like but start and begin are very different things.

  • As a matter of fact, I think get in English even is abused, because he is a joker in the language, but in programming, we need more precision than it is.

  • It is widespread, perhaps this is the reason why people willingly accept it, can be used in various programs, with different functions and yet will fulfill the role assigned to it without any complications. In part I think most English terms act the same.

  • 1

    Someone didn’t like the answer. At least there are several others who found it good.

  • 2

    Perhaps because it is normative in the use of the imperative. It can be disagreement on this point. I myself disagree with this, although I have not negatively. I think it is infinitive and present of the indicative (calculaResultado) are equally valid.

  • 2

    It is likely. You know that the vote should not express disagreement, others no longer understand this. In the end I say that each one can do as he wants. I put the way I see the use in the best existing codes and recommendations in some guides. Of course, everyone can do as they please, but my answer is not only my opinion, I have done a lot of research to reach this conclusion. Although it is not definitive and universal.

  • 2

    I improved, I hope the negatives review your vote.

Show 3 more comments

1

Between the two forms you quoted, I prefer that the verb is in the infinitive, how to get() and add().

Try to name your variables in the same language as the programming language, in this case in English.

Each language has a standard and its best practices. Python, for example, has a PEP 8, a style guide for the developer community. Java should have its, C++ too and so on.

Besides, everything can vary according to the project you are working on. If people are using a specific pattern, the ideal would be to continue the way it was started in order to maintain a pattern.

The link to the slides is also a hint How to name things: the biggest problem of programming.

0

I always use the name summarizing with the minimum of words what the function will do, example:

class Calculadora {
    public static int somar(int a, int b) {
         return a + b;
    }
}

Java has a different language design than . NET Framework, its functions and classes often use lowercase and uppercase letters to "improve code vision".

somarNumeros java special

SomarNumeros special. NET Framework

somar_numeros I don’t know what it is, but in my opinion it’s the worst way to name something.

Names in Portuguese?

In my opinion, I prefer to use even English for any language I will use, it is much more beautiful to use English to name a function than Portuguese.

int obterValor(); 
int getValue();   //Tudo em inglês, melhor ainda

Defining function names or types depends on the writer of the code, it is not good to mix English with Portuguese in your code, can cause a confusion at the time of understand the code. You should name the method with what it will do, a function with what it will do and what it will return, example:

int getAlunoFromIndex(int i, string[] alunos) {
     return alunos[i];
}

And not like this:

int ObterAlunoPeloIndice(int i, string[] alunos) {}

Always you will perform a function ~~ future

You will get a value ~~ future

That function will use this method here ~~ future

Anyway, this question depends a lot on who will write the code. I recommend using the function name on future of the indicative, and also adapt to the syntax of the language. If there are languages that use all the methods IN UPPER CASE, would you like to see one method in upper case and another in lower case in your code? I was gonna give a stump, is not?

private int OBTER_VALOR = 0;
private int getIdade = 15;
private int ObterPropriedade = "Foo Bar";

Causes a mess, so you choose the way you’re going to use your code.

  • 2

    I usually use everything in English, but it gets weird when you need to use a "Cpfdigit()", "Boletoverify()", etc gets kkk.

  • 1

    @Bacco think that in these specific cases we should use the name in Portuguese because it has more meaning due to the context.

  • 1

    I think that most of the time people write in English because it makes their writing easier, that is, relatively short names, still with the same meaning that they would have in Portuguese, and even have more logic, by adapting to the context, as well as being a viable option for internationalization of the script, being that it is a dominant language.

  • @Bacchus : BoletoVerify() It’s pretty weird even because it’s wrong even in English. Even if one chooses not to translate "Boleto" into English, the verb must come in front of the noun: VerifyBoleto() is not (so) strange and is more correct.

  • 2

    @Mestrelion if you think from the point of view of language yes, but usually I use words to group functions: BoletoIsso BoletoAquilo BoletoAquiloOutro (for you to group the functions by "Boleto") - It is not a question of phrase composition, but of code organization - That being said, I agree with you that it gets stranger, but it is a "conscious disorder". I have a certain preference for treating it as a prefix in the same collection. Note that the digit case comes CPF before too, as would Cpfverify or Cpfformat, etc.(which despite reversed order, put the subject first)

  • 2

    Let’s call it "poor namespace" ;)

  • 1

    @Mestrelion and boleto.Verify() is it suitable? Because it’s what everyone loves to wear.

  • 1

    Bool VerificaBoleto(Boleto boleto) { }

  • @Bacco: ah, ok, while "poor namespace" is valid yes. In that case I might use _ as a separator to make clear the intention of grouping/namespace. But we are talking about "pure" functions right? If we are in classes, see all these methods with prefix BoletoXxx()/boleto_xxx() are strong evidence that a class Boleto() is begging to be raised :-)

  • @Maniero: boleto.Verify() as a class method Boleto() I think super valid yes (but would leave it in lowercase). I prefer to program in English not to fall into the eternal infinitive/imperative/indicative dilemma (calculate, calculate or calculate?), but would leave boleto without translating pq has no direct equivalent (slip? ticket?). So, yeah, boleto.verify() it is :-)

  • 1

    @Bacco, complementing his great comment: when changing order for grouping purposes have to have much care (and be much consistent in use) due to ambuiguities in some verbs: in natural language, CpfFormat and FormatCpf are distinct things, the first can be read as a noun, "the format of the CPF", like the mask to be used when formatting the CPF for display or typing.

  • 1

    @Cypherpotato: We’re already going a little outside the scope of the question, but I think a function that receives an object to verify it is a weak OO modeling. verification should be an object class method, not an external function/method of another class that receives the object.

  • More than three years after publication and we will make the answer as Out of scope.

  • 1

    @Mestrelion agreed, note that I do not like this mixture, really it was just to exemplify even. In Harbour, for example I use _ as you commented: namespacedepobre_NomeDaFuncao() (for lack of fact namespaces)

Show 9 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.