Simple Getter/Setter comments

77,103

Solution 1

I usually just fill the param part for setters, and the @return part for getters:

/**
 * 
 * @param salary salary to set (in cents)
 */
public void setSalary(float salary);

/**
 * @return current salary (in cents, may be imaginary for weird employees)
 */
public float getSalary();

That way javadoc checking tools (such as Eclipse's warnings) will come out clean, and there's no duplication.

Solution 2

Absolutely pointless - you're better off without this kind of crap cluttering your code:

/**
 * Sets the foo.
 * 
 * @param foo the foo to set
 */
public void setFoo(float foo);

Very useful, if warranted:

/**
 * Foo is the adjustment factor used in the Bar-calculation. It has a default
 * value depending on the Baz type, but can be adjusted on a per-case base.
 * 
 * @param foo must be greater than 0 and not greater than MAX_FOO.
 */
public void setFoo(float foo);

Especially the explanation of what the property actually means can be crucial in domain models. Whenever I see a bean full of properties with obscure names that only investment bankers, biochemists or quantum physicists understand, and the comments explain that the setGobbledygook() method "sets the gobbledygook.", I want to strangle someone.

Solution 3

Generally nothing, if I can help it. Getters and setters ought to be self-explanatory.

I know that sounds like a non-answer, but I try to use my time for commenting things that need explanation.

Solution 4

I'd say only worry about commenting getters and setters if they have some sort of side effect, or require some sort of precondition outside of initialization (i.e.: getting will remove an item from a data structure, or in order to set something you need to have x and y in place first). Otherwise the comments here are pretty redundant.

Edit: In addition, if you do find a lot of side effects are involved in your getter/setter, you might want to change the getter/setter to have a different method name (ie: push and pop for a stack) [Thanks for the comments below]

Solution 5

Ask yourself what do you want people to see when the comments are viewed as JavaDocs (from a browser). Many people say that documentation is not necessary since it's obvious. This won't hold if the field is private (unless you explicitly turn on JavaDocs for private fields).

In your case:

public void setSalary(float s)
public float getSalary()

It's not clear what salary is expressed in. It is cents, dollars, pounds, RMB?

When documenting setters/getters, I like to separate the what from the encoding. Example:

/**
 * Returns the height.
 * @return height in meters
 */
public double getHeight()

The first line says it returns the height. The return parameter documents that height is in meters.

Share:
77,103
theblackips
Author by

theblackips

Founder - http://crowdscriber.com , Editor of The Basement Coders Podcast (http://basementcoders.com ), Java, Scala & ObjC dev. All around nice guy :).

Updated on December 13, 2021

Comments

  • theblackips
    theblackips over 2 years

    What convention do you use to comment getters and setters? This is something I've wondered for quite some time, for instance:

    /**
     * (1a) what do you put here?
     * @param salary (1b) what do you put here?
     */
    public void setSalary(float salary);
    
    /*
     * (2a) what do you put here?
     * @return (2b)
     */
    public float getSalary();
    

    I always find I'm pretty much writing the exact same thing for 1a/b and 2a/b, something like 1a) Sets the salary of the employee, 1b) the salary of the employee. It just seems so redundant. Now I could see for something more complex you might write more in the (a) parts, to give context, but for a majority of the getters/setters out there the wording is almost exactly the same.

    I'm just curious if, for the simple getters/setters its ok to only fill in either the (a) part OR the (b) part.

    What do you think?

  • oxbow_lakes
    oxbow_lakes almost 15 years
    They're only self-explanatory if you say "this is a property setter". Otherwise a client of the API has no idea whatsoever what is actually happening inside the methods
  • plankalkul
    plankalkul almost 15 years
    Who said anything about self-explanatory?
  • Jonik
    Jonik almost 15 years
    Can you fix the typo? "@return part for setters"
  • oxbow_lakes
    oxbow_lakes almost 15 years
    That's fine - but that requires users of your API to know that, had there been any side effects, they would have been documented !
  • mqp
    mqp almost 15 years
    Without documentation, any caller would assume that a method called setX sets X. It follows that if setX actually sets X, without doing anything else important, then you don't need documentation.
  • Steve Kuo
    Steve Kuo almost 15 years
    What if getFirstName() returns null? Where would that be documented?
  • Michael Borgwardt
    Michael Borgwardt almost 15 years
    How about security.getFinalMaturity()? Not all property names have an immediately understandable meaning. Would you want to be fired for not knowing what that means?
  • oxbow_lakes
    oxbow_lakes almost 15 years
    What if the method is implemented by swizzling? How are you supposed to know that unless it's been clearly documented? How are you supposed to know it is a standard setter unless the doc says it is?
  • oxbow_lakes
    oxbow_lakes almost 15 years
    That's great! Now does this company CrudTech, whose API I am coding against, follow your convention, or does it follow someone else's on this thread? Hmmmm
  • David Berneda
    David Berneda almost 15 years
    akf, I was thinking exactly that after posting :) I guess I'll add it to my response.
  • theblackips
    theblackips almost 15 years
    I think I like this answer best as there is no redundancy and things like cobertura won't make it look like the coder is slacking with his/her commenting
  • Brett
    Brett almost 15 years
    There's a difference between commenting and documenting.
  • Fostah
    Fostah almost 15 years
    There's also a typo in salary()'s comment. It's not JavaDoc comment.
  • Fostah
    Fostah almost 15 years
    I agree that it is the best approach to commenting accessors.
  • João Marcus
    João Marcus almost 15 years
    There is no point in writing "sets the price" in the setPrice doc if the method just sets the value for the price property, but if it also e.g. updates the totalPrice property and recalculates the tax, such behaviour should obviously be documented.
  • oxbow_lakes
    oxbow_lakes almost 15 years
    No; but "JavaBean property setter" is perfectly descriptive
  • matbrgz
    matbrgz almost 15 years
    Very true. Exactly therefore is why I do not comment getters and setters. They should be self explanatory, and adding a comment indicates that the code isn't self explanatory.
  • matbrgz
    matbrgz almost 15 years
    get/set should in my opinion be reserved for getters and setters. Database lookups should be named like "lookupPerson" or so.
  • theblackips
    theblackips almost 15 years
    My sentiments exactly, the worst are the domain specific models where only a domain expert knows what the heck the property means.
  • littlebroccoli
    littlebroccoli about 14 years
    You seem to be asking for the documentation to state "This does what you expect." Which is a bit like writing "Caution: HOT" on a cup of coffee. In a perfect world, there would be no need to ever say such things.
  • oxbow_lakes
    oxbow_lakes about 14 years
    Yes - having used APIs where methods called things like setX had side-effects other than the expected, I can indeed state with confidence that this is not a perfect world.
  • Gad
    Gad over 13 years
    while I agree with you, I think that one must make sure that the function comments are not making out for a bad chosen, non-explicit function name.
  • Hakanai
    Hakanai over 13 years
    I think the 's' in 'salary' should be in lowercase here, taking into account how these render in the Javadoc output (they are not at the start of a sentence. This Javadoc glitch is a pet peeve of mine.)
  • Hakanai
    Hakanai over 13 years
    Another valid answer along these lines might be "designs with getters and setters do not properly understand the notion of encapsulation" :)
  • Hakanai
    Hakanai over 13 years
    No good - people don't read the field comments. Javadoc doesn't even generate the private documentation by default, and IDEs don't show you the field documentation when you use quick help on a method call.
  • akf
    akf over 13 years
    people don't read the field comments unless they need to. Once there is a need, the more information the better.
  • Lyle
    Lyle about 13 years
    Adding noise to your code for the sake of silencing overly pedantic warning from our tools feels wrong to me. If it doesn't add value to a programmer, then the right solution would be to turn down/fix the verbosity of the tools and/or ease up on how much we care about jumping through hoops so that the tools reward us. Analysis tools are supposed to help us and save effort, not create more senseless tasks for us.
  • Laurent Pireyn
    Laurent Pireyn about 13 years
    @Trejkaz: Not true, because accessor methods allow for read-only or write-only properties, and for polymorphism (and so wrapping, proxying, and so on).
  • Hakanai
    Hakanai about 13 years
    They may allow for those things, but often a builder pattern can replace setters (less mutable) or a visitor pattern can replace getters (more flexible.)
  • Vinoth Kumar C M
    Vinoth Kumar C M over 12 years
    Even if it is useful what would you do for getFoo(). Will you copy the same comment for the getFoo() as well ?
  • Michael Borgwardt
    Michael Borgwardt over 12 years
    @cmv: Obviously the "param" part would not be copied. I'm undecided whether the value of having the information attached to both accessors directly justifies duplicating the information. Probably yes. Even better would be a way to attach one comment to both; I believe this is available in Project Lombok.
  • Paŭlo Ebermann
    Paŭlo Ebermann over 12 years
    An effect of this is that now the alphabetic method summary contains no text at all for these methods. This might be good or bad depending on point of view.
  • Zordid
    Zordid almost 12 years
    but if you don't document "stupid" getters and setters (it's what I prefer, too!) - how do you get rid of Eclipse warnings on missing javadoc? I don't want to clutter my workspace with warnings like that, but I also don't want that warning to be disabled for all other methods...
  • Jarek Przygódzki
    Jarek Przygódzki over 11 years
    The problem with this approach is that Javadoc doesn't generate the private documentation by default! In that case reference tag {@see #salary} is invalid in generated documentation.
  • Sathya Babu Ram k
    Sathya Babu Ram k about 11 years
    @VinothKumar: maybe it would be nicer to simply explain the property in the getter (as in "Foo is the adjustment factor used in the Bar-calculation.") and the effects of changing the value in the setter (or whether it is necessary or not to initialize that value -- in the answer's example it is not necessary to initialize Foo since "it has a default value depending on the Baz type").
  • Michael Scheper
    Michael Scheper about 11 years
    I certainly like and use the builder pattern, but there's so much support for POJOs (e.g. in Hibernate) that getters and setters still have their very prominent place, for better or for worse. It's the daggiest thing about Java, IMHO, and after writing repetitive JavaDocs for well over a decade, I'm about ready to subscribe to @sleske's advice.
  • Michael Scheper
    Michael Scheper about 11 years
    I'm a big supporter of JavaDocs, but also a big supporter of self-documenting code. So for the setter at least, I'd do something like public void setSalary(float aud) (or more realistically, public void setSalary(BigDecimal aud)). Better yet, the property ought to be of type abstract class CurrencyAmount, which in turn has the properties java.util.Currency currency and java.math.BigDecimal amount. Most developers I've worked with are terribly lazy with JavaDoc, but enforcing API like this makes this less of a problem.
  • AlexWien
    AlexWien almost 11 years
    If the unit is a SI unit like meters / seconds, there is less need to document, if it is not an Si unit then it must be documented or better named to include the non standard unit, e.g heightFeet
  • Michael Scheper
    Michael Scheper over 10 years
    I agree. And then I realised, why write all this boilerplate anyhow? See my answer about Project Lombok.
  • Jackson
    Jackson almost 10 years
    +1 for "obscure names that only investment bankers, biochemists or quantum physicists understand"
  • Matt Vukas
    Matt Vukas over 9 years
    @Lyle That may be true, but I feel like there's almost always something useful that a programmer can say which describes a getter/setter better than just the method signature alone. Yes, there are cases where a programmer is lazy and just repeats the method signature in the comment, but I think that generally speaking, it is a helpful behavior to force.