Search code examples
classflutterdartfinalprivate-members

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;
    }
}

Solution

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