DEV Community

Michele Volpato
Michele Volpato

Posted on • Updated on • Originally published at ishouldgotosleep.com

When to use a getter vs a method in Dart

Dart provides the possibility to use getters and setters, special methods that give read and write access to an object's properties.

You can use a getter to hide write access to a property:

enum ProductType { normal, offer }

class Product {
  // The product id.
  final String id = "ABC1234";

  // This property cannot be modified directly from outside the object.
  ProductType _type;

  Product(this._type);

  // _type can be accessed read-only using this getter.
  ProductType get type => _type;
}
Enter fullscreen mode Exit fullscreen mode

You can also use them to calculate a certain value that is notdirectlystored in your object:

...

  // Get whether the type of the product is an offer.
  bool get isOffer => _type == ProductType.offer;
 }
Enter fullscreen mode Exit fullscreen mode

You could also use a method, instead of a getter:

...

  // Get whether the type of the product is an offer.
  bool isOffer() => _type == ProductType.offer;
 }
Enter fullscreen mode Exit fullscreen mode

So, how do you know where to use a getter and where to use a method?

Personally, I avoid using a getter when the value cannot be calculated in O(1). The reason is that a getter and a property look the same from the outside, from the point of view of the user of your object.

final product = Product(ProductType.offer);

// Is this a getter or a property?
product.id;

// Is this a getter or a property?
product.isOffer;
Enter fullscreen mode Exit fullscreen mode

So the fact that there is a calculation behind the getter might be lost for the final user of the object who might think that the getter is a property and will use it as a O(1) "function".

Top comments (0)