0

Consider the following example (common if you use the provider Flutter package): You have a class with a private variable that can be accessed via a setter and a getter. What is the convention / recommended way to document this?

class Foo extends ChangeNotifier {

  int _bar = 0;

  int get bar => bar;

  set bar(int bar){
    _bar = bar;
    notifyListeners();
  }
}

Should you add doc comments to both the setter and getter and explain the purpose of the variable in both comments, or should you just add a doc comment to the private variable?

For example:

class Foo extends ChangeNotifier {

  /// The number of bars in the foo.
  int _bar = 0;

  /// Get the number of bars in the foo.
  int get bar => bar;

  /// Set the number of bars in the foo.
  set bar(int bar){
    _bar = bar;
    notifyListeners();
  }
}

vs.

class Foo extends ChangeNotifier {

  /// The number of bars in the foo.
  int _bar = 0;

  int get bar => _bar;

  set bar(int bar){
    _bar = bar;
    notifyListeners();
  }
}

The first example is the most clear one, but it can possibly mean a lot of duplicate comments. The second example reduces the amount of comments, but it isn't as easy to see what the getter / setter does (for example by hovering over it in vs code). Is there a recomendatin by the Dart team or a convention for how documentation should be written in cases like this?

Hannes Hultergård
  • 1,157
  • 1
  • 11
  • 33
  • 1
    I would do the first example based on the fact that DartDoc seems to combine the documentation for both `set` and `get` for a given property. An example is the `length` on `List`: https://api.dart.dev/stable/2.13.0/dart-core/List/length.html – julemand101 May 15 '21 at 15:51
  • So, it seems like dartdoc doesn't generate documentation for private variables (reasonable when you think about it). So, like you said, the best way to do this is probably to document the getter and setter but not the private variable. Maybe just comment that with a regular `//` comment? – Hannes Hultergård May 15 '21 at 20:47
  • If it is not obvious what the private variables does, yes you should document it. But else, I would say it is enough to document the public part of your interface. – julemand101 May 15 '21 at 20:51

1 Answers1

3

Document either, traditionally the getter. Document it as you would a field, using a noun phrase. The DartDoc tool will then show it as a field. https://dart.dev/guides/language/effective-dart/documentation#prefer-starting-variable-getter-or-setter-comments-with-noun-phrases

lrn
  • 64,680
  • 7
  • 105
  • 121