DEV Community

Michele Volpato
Michele Volpato

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

1

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".

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post