mcjabberz
mcjabberz

Reputation: 9998

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?

Upvotes: 12

Views: 10127

Answers (10)

Michal M
Michal M

Reputation: 1568

13 years later, I believe this question deserves a revisit. Surely, over the time there were a lot of stackoverflow Q&A-s (even some good answers here), articles and blog posts that amounted to the same conclusion, but finally, I think, we get a rather straightforward answer from Brian Goetz himself:

“The JavaBeans naming convention* is a little bit of an unfortunate story,” he continues. “It’s a terrible convention for general-purpose development. It was a fairly well-targeted convention for naming visual components in a visual editor, where you were dragging and dropping buttons and labels and things like that onto a canvas, and you had property sheets that you could edit about foreground color and fonts and what have you, which could be discovered reflectively.”

Goetz explains that the naming convention was great way building those UI components—which turns out to not have been a key Java use-case. “And yet, somehow, we continued with that naming convention, even though it’s such a poor match for most business domain objects.”

https://blogs.oracle.com/javamagazine/java-architects-loom-panama-valhalla#anchor_4

* – basically, the getX/setX convention in question

Upvotes: 4

mikera
mikera

Reputation: 106351

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

Upvotes: 10

Yang Meyer
Yang Meyer

Reputation: 5699

Just a short addendum: Another convention is for getters of Boolean fields to be prefixed with "is" instead of "get", e.g. bool isEnabled() { return enabled; }

Upvotes: 1

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 248029

It depends. It is often redundant information, even in languages without properties.

In C++, instead of a getAttr()/setAttr() pair, it is common to provide two overloads of an Attr() function: void Attr(Foo f); // The setter Foo Attr(); // The getter

In Java, it is common practice to prefix get/set. I'll have to say the best practice is to go with what's standard in your language. In Java, people expect to see get/set prefixes, so omitting them might confuse people, even though they're not strictly necessary.

Upvotes: 2

Serxipc
Serxipc

Reputation: 6699

The best practice in Java is to use the get and set prefixes for properties.

Frameworks, tag libraries, etc will look for methods with those prefixes and use them as properties.

So, if you have a java class like this...

public class User{
    private String name;
    public String getName(){ return name;}
    public void setName(String name){ this.name = name; }
}

.. with struts-tags (or any other ognl based tag library) you will access the name property with user.name.

The Spring framework also uses this convention in the xml configuration files.

Upvotes: 4

Timothy Khouri
Timothy Khouri

Reputation: 31845

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

Upvotes: 9

Matthew Schinckel
Matthew Schinckel

Reputation: 35629

Objective C 2.0 also uses properties, using the same dot syntax.

Prior to that, it used a slightly different naming scheme for getters and setters (which, naturally, can still be used with properties, or for plain old attributes).

value = [obj attr];

[obj setAttr:value];

[obj getAttr:&value];

That is, get is used in a different way. It doesn't return a value, but stores the result in the passed in variable.

The typical getter has the same name as the attribute, the setter is the attribute prefixed by set (as per Java's convention). These conventions are used by the KVO (Key-Value Observation) system, so should be adhered to.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500893

It certainly used to be the case that APIs often exposed read-only properties without the get prefix: String.length() and even the newer Buffer.capacity() being reasonable examples.

The upside of this is that there's less fluff involved. The downside is that anything which tries to determine properties automatically based on the conventions won't discover them. Personally I tend to err on the side of including the prefix.

Of course, in C# it's mostly irrelevant as there are "real" properties anyway :)

Upvotes: 2

David Arno
David Arno

Reputation: 43254

Java doesn't (yet) support properties. Getters and setters are a bodge to get around this. Other languages - including C# - support properties and you should use these instead. This isn't just a "best practice" thing either: serialization in C# will rely on properties, not getters & setters, so not using properties could lead to all sorts of problems in the future if you need to serialize your classes.

The advantage to properties is that they make the code more readable. Something like

obj.setX(10);

in Java, becomes

obj.X = 10;

Yet behind the scenes, X is a method, rather than being a variable and so can perform dirty input checking etc.

Upvotes: 2

Marko
Marko

Reputation: 31403

"get" and "set" prefix pair in Java is used originally as a convention to denote java bean. Later, it become just an encapsulation convention, since Java, unlike C# doesn't have proper properties.

Upvotes: 6

Related Questions