views:

241

answers:

12

What's a good rule of thumb for naming methods that return properties/attributes/members of an object? If an object has some immutable quality "blarg", should a method that returns that quality be called "blarg()" or "getBlarg()"? The Java API, for example, is inconsistent: most properties are accessed through "get" methods (even those that don't have corresponding "set" methods), but yet we also have things like Object.hashCode() instead of Object.getHashCode().

Update: Should whether or not it's the property is a field (in the implementation) be the determiner here? What about a class to represent immutable points in 2-d space? Regardless of whether the point is stored as (x,y) or (r,theta), I would still want accessors for all four properties. Should they be getX(), getY(), etc, or just x(), y(), etc? From the point of view of the user, shouldn't all four have the same naming convention since we don't want our user to know/care about our implementation?

+2  A: 

I believe the most often used conventions are:

GetBlarg() or getBlarg()

It could be argued that the name GetHashCode() is incorrect, since the object doesn't have a field called hashcode and that it's calculated.

These are of course all conventions, not rules, and most of them have evolved over a long time and as such are not 100% consistent.

Regards
K

Khb
I think you're right. I'm reasonably certain that hashCode predates the accessor naming convention. However, it is common to cache hash codes in immutable objects, so in some cases they *can* be read from a field.
Bill the Lizard
You shouldn't care if the field is calculated or retrieved. That's one of the points of OO - to separate interface from implementation.
Peter Crabtree
+1  A: 

If the method doesn't do anything other than access a property, then stick with the getProperty convention. The common exception to this rule is if you're accessing a boolean, then the convention is to use isProperty.

Bill the Lizard
A: 

If it's boolean, the convention is "isBlarg()".

Brian Knoblauch
+1  A: 

To disagree with the other posters here, I generally prefer the intuitive APIs that result from just using the name ("blarg") as the property. When you learn about object oriented programming, that's usually what you are taught - for example, in the classic example of a "car" class and an "engine" class, you're taught that the car has an engine, and that looks like:

car.engine

That's what they use because it's easier to understand than

car.getEngine

to which most normal people would say, "what's a getEngine?". A car doesn't have a getEngine, it has an engine. In my experience, the cases where momentary confusion might result from this are far outweighed by the overall improvement in plain old human readability. This is just my opinion, and goes against the grain for Java programming in general, but honestly, that's part of what I don't like about Java programming in general. ;)

Ian Varley
Oh so wrong... an Object is about the **service** it offers, not about its internal component. getEngine() is the service allowing you to access to the engine of the car. -1
VonC
I didn't say anything about internal (private) components; if the service that a property offers is to construct and return something that is conceptually a "blarg", I see it as natural to name the method that. Just because the Java convention to add a "get" in front of it doesn't make it right.
Ian Varley
Ian, I have to agree with what your perspective on things. "Is a" doesn't like the getProperty convention.
marc
Ian my point exactly: get is much more natural to name the service of accessing a property. a Car does not have a getEngine (as you say), it does have the service of getting the Engine. 'Is a' characterizes the Object, not the get() service.
VonC
A: 

The IsFoo convention sucks in my opinion. You're adding in Hungarian notation. If you change it to a class that uses 3-value logic from 2-value logic you'll need to rename your method. Keep your typing in the compiler and out of the naming.

jcollum
I guess that hasn't been a major concern because if you're changing the return value, changing the name at the same time is trivial.
Brian Knoblauch
+3  A: 

Depends on the language.

In Smalltalk, the convention is blarg for getter and blarg: for setter.

In Java, the JavaBeans convention is getBlarg() and setBlarg(). Plus isBlarg() for boolean properties.

You mention cases where you don't have both getter and setter. That makes sense, since some properties are read-only.

When you follow conventions, you get code that others can read more easily. Sometimes tool support. For example, many tools recognize the JavaBeans conventions.

The JavaBeans convention wasn't whipped up until Java 1.1. All of the Object methods (e.g., hashCode()) predate that. And can't be changed for backwards compatibility.

John M
A: 

I believe you shoud stick to the getBlarg() (or isBlarg()) convention, as long as you realize this is not just for getting an property.

The reason they are named get...() is to represent the process of accessing to a characteristic of an object, whether it is a simple property or a calculated attribute.

So, IMO, it should have been getHashCode() ;), but for backwards compatibility reason, as John points out, it will remain hashCode().

VonC
+1  A: 

For languages that have a native concept of properties (which Java does not), you should use a property when the accessor (get or set) does not have side effects, is relative performant (not long-running), returns the same value for each call, or does not depend on other properties (contextual dependencies). If any of those are true, you should use a method named GetXxx or SetXxxx where "Xxx" is what would otherwise have been the property name.

Scott Dorman
A: 

In Objective-C, there are "strict" conventions for naming accessor methods that will enable a class to be Key-Value Coding compliant.

A setter for foo is always called setFoo:

[obj setFoo:newFoo];

A getter can be one of three alternatives:

[obj foo];
[obj getFoo:otherFoo];
[obj isFoo];

The first is the instance where the accessor returns either the attribute or a copy of the attribute. The second is where the accessor takes an argument, and places the attribute into this variable (pointer reference, usually), and the third is where the attribute foo is a boolean type.

The advantage in Objective-C of using this, is that you can access an attribute using a Key Path, and it will use the accessor - and will search through the different forms of accessor until it finds one.

temp = obj.foo;

This will use the accessor, as long as it follows the naming scheme above.


In python, I use a different scheme. For properties that I will access via property notation:

class Class:

    def get_x(self):
        return self._x

    def set_x(self,x):
        self._x = x

    x = property(get_x, set_x)

In the instances where I want to use a method call, then I use:

get_thing()
Matthew Schinckel
A: 

I'm against omitting the "get" or "is" prefix for a getter since using just the field name can result in it being misconstrued as a function that actually performs a real action.

Let's say you have a proofreader class and you have a bool field named _checkSpelling that indicates whether or not spelling will be checked: checkSpelling()

no-op
A: 

Conventions are usually language specific, and the best way is to follow whatever language you are using. Java uses getters and setters (or accessors and mutators) wheras in C# you might be making Properties for your classes. Learn the various conventions for your language so you can communicate with other coders.

Chet
A: 

To sum up:

Please note that all the following is language specific. It goes for Java and probably more languages, but not for all. Second: It's only a convention. When you follow conventions, you get code that others can read more easily. Sometimes tool support (For example, many tools recognize the JavaBeans conventions) This still doesn't mean that you can't choose to stick to another convention.

  • A good rule of thumb for naming methods that return or set a certain attribute an object has, for example a 'hashCode' is as follows: getHashCode() for getting it, setHashCode(...) for setting it.
  • For getHashCode() this is also true when the object wouldn't have the hashCode standing by when the function is called, but instead computes it right at the moment, because the service the object offers by this method stays the same in both cases: it gets you a hashCode.
  • The fact that Java method names are inconstant regarding this can be explained by the fact that in earlier versions of Java this naming conventions were not yet followed, and they cannot be changed for backwards compatibility reasons.
  • The fact that some getters don't have a corresponding setter is normal, since you might not want every attribute to be both accessed and changed.