Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 491
mcjabberz Avatar asked Nov 04 '08 09:11

mcjabberz


2 Answers

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).

like image 126
Timothy Khouri Avatar answered Oct 11 '22 23:10

Timothy Khouri


I personally like the following rule:

  • Use the get prefix whenever the value is directly modifiable with a corresponding set method
  • Drop the get prefix in situations where the value is something you can't set directly as a property (i.e. there is no equivalent setXXX method)

The rationale for the second case is that if the value isn't really a user-settable "property" as such, then it shouldn't need a get/set pair of methods. An implication is that if this convention is followed and you see a getXXX method, you can assume the existence of a setXXX method as well.

Examples:

  • String.length() - since strings are immutable, length is a read-only value
  • ArrayList.size() - size changes when elements are added or removed, but you can't set it directly
like image 32
mikera Avatar answered Oct 11 '22 23:10

mikera