methodsgetternames

What is the best practice for using "get" in method names?


I've noticed in many places in Java (C# included), that many "getter" methods are prefixed with "get" while many other aren't. I never noticed any kind of pattern Sun seems to be following. What are some guidelines or rules for using "get" in getter method names?


Solution

  • It comes down to semantics. Yes, C# has "properties" which give you a get/set 'method' stub... but functions (..."methods"...) in the .NET Framework that start with "Get" is supposed to clue the developer into the fact that some operation is happening for the sole purpose of getting some results.

    You may think that's odd and say "why not just use the return type to clue people in?", and the answer is simple. Think of the following methods:

    public Person CreatePerson(string firstName, string lastName) {...}
    

    Just by that method's name, you can probably figure that there will be database activity involved, and then a newly created "person" will be returned.

    but, what about this:

    public Person GetPerson(string firstName, string lastName) {...}
    

    Just by that method's name, you can probably assume that a 100% "Safe" retrieval of a person from a database is being done.

    You would never call the "CreatePerson" multiple times... but you should feel safe to call "GetPerson" all the time. (it should not affect the 'state' of the application).