7

Is there a standard or best practice for writing javadocs for Java/JVM language methods which contain side effects?

I have a void method defined, which modifies one of the method parameters, but do not know how to document the actual return value (since there is no actual return).

/**
  * @param obj - reference object
  * @return obj - obj.name is changed to 'hello' //TODO figure out javadoc annotation
 */
void methodName(Object obj) {
   if (obj != null) {
       obj.name = "hello";
   }
}

It just seems that there is no good way to tag the side effects on the object, since the @param and @return annotations do not really dictate what is going on.

tmarthal
  • 1,498
  • 19
  • 28
  • that seems to me to be a leak of your abstraction – Daniel A. White Apr 05 '16 at 00:26
  • 3
    I don't want to talk about side effects or leaky abstractions - I just want to write some comments to document what legacy methods are doing. – tmarthal Apr 05 '16 at 00:40
  • 1
    There's no standard JavaDoc annotation such as @ SideEffectTowWatchFor or @ LeakyAbstraction (and I'll totally admit that I, and almost everyone else, has done the same) so just make sure you're crystal clear in the docs about what's happening, what's expected, etc. Essentially, your contract defines this method to affect objects this way. – Scott Sosna Apr 05 '16 at 00:59
  • 4
    The lack of javadoc's ability to annotate side effects has been bugging me since I started java programming years ago. If java doesn't allow side effects, then why have class variables? – SMBiggs Aug 24 '16 at 16:40

1 Answers1

3

There is no standard Javadoc annotation to describe side effects. Side effects are typically mentioned in the human-readable description of the method. In your case, the object which is passed as a parameter is modified, so you can consider briefly repeating the side effect after the @param tag.

In any case, the @return tag is not the correct place to document side effects: your method has void as return type, so it does not return anything.

In your case, your Javadoc could look like:

/**
 * Methods a name. This method sets the "name" attribute of obj to "hello".
 * @param obj reference object ("name" attribute is modified by this method)
 */
void methodName(Object obj) {
   if (obj != null) {
       obj.name = "hello";
   }
}
Hoopje
  • 12,677
  • 8
  • 34
  • 50