Landon
Landon

Reputation: 538

Is it redundant to make final variables private in dart?

The following class has multiple parameters but only some need to be final; my q is, should I also make these final variables private, or would doing so be redundant?

class Car {
    final double _galInFullTank;
    get galInFullTank => _galInFullTank;
    double _miDrivenToEmpty;
    get miDrivenToEmpty => _miDrivenToEmpty;
    double _mpg;
    get mpg => _mpg;

    void update(double newMiDrivenToEmpty) {
        _miDrivenToEmpty = newMiDrivenToEmpty;
        _mpg = _miDrivenToEmpty/_galInFullTank;
    }

    Car({galInFullTank = 12, miDrivenToEmpty = 300}) :
        _galInFullTank = galInFullTank,
        _miDrivenToEmpty = miDrivenToEmpty,
        _mpg = miDrivenToEmpty/galInFullTank;
    }
}

Upvotes: 1

Views: 975

Answers (2)

jamesdlin
jamesdlin

Reputation: 90005

Making a private member final is not redundant. In general, being private and being final are orthogonal. For example, consider something like:

class Foo {
  final List<int> someList;
}

Just because Foo.someList is final does not prevent external code from modifying it (e.g. someFoo.someList.clear()).

You should make things that you don't want to be part of your API private.

Upvotes: 2

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277077

It has some use-cases. It can be used to down-cast variables.

For example, using RxDart we could have:

final BehaviorSubject<Foo> _foo;
Stream<Foo> get foo => foo;

This hides the implementation details.

It could also be used to do extra things inside the getter. For example, Mobx uses that to know what values are used.

But just straight up exposing the variable without modification or extra computation is pointless.

Upvotes: 1

Related Questions