Search code examples
dartdesign-patternsgetterfinal

Dart: When to use a getter vs a final field


I have a simple question to ask.

Consider the two code examples,

// 1
class A {
  final a = 23;
}

// 2
class A {
  get a => 23;
}

in [2], the final field is converted into a getter.

question: Under which circumstances should either type of codes be used? Which one is the dart's preferred way?


Solution

  • I don't think there is a preferred way. You can use either. There is also not necessarily any difference in what they mean. A smart compiler can convert on to the other, depending on which is more efficient the way the class is used.

    Assuming the compiler doesn't change the representation.

    • The final field introduces a memory slot on each instance of the class which holds the value, and then a generic getter reading that slot.
    • A getter introduces a getter method on the class, which does nothing except return the value.

    Which is better depends on how the class is used. If you only have very few instances, then the memory overhead of the extra memory slot on each instance is negligible.

    If the compiler is smart, it might skip the implicit getter for the field and read the slot directly. If the compiler is smart, it might inline the explicit getter too.

    All in all, I wouldn't worry about there being a difference. I personally tend towards the getter, because I prefer to reason about the state of the object by looking at its fields, and the final constant-valued field doesn't really contribute to the state.