Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to set the default instance for a final private field with optional parameter?

Tags:

dart

Given a class with final private field _bar:

class Foo() {

final Bar _bar;

    Foo({Bar bar}) : _bar = bar {

        //error: list cannot be used as setter, it is final
       _bar = new Bar();
    }

}

Attempting to set it in the parameter list results in this error

//error: default values of an object must be constant
Foo({Bar bar: new Bar()}) : _bar = bar ..

I'd like to keep the optional parameter so that I can inject mocks during unit tests. What is the best approach for this?

like image 925
Stephen__T Avatar asked May 11 '15 12:05

Stephen__T


2 Answers

class Foo {
  final Bar _bar;
  Foo({Bar bar}) : _bar = bar != null ? bar : new Bar();
}
like image 113
Alexandre Ardhuin Avatar answered Nov 18 '22 11:11

Alexandre Ardhuin


I recommend to use static methods when a logic is complex thing.

class Foo {
  final Object _field1;

  Foo({Object value1}) : this._field1 = _setUpField1(value1);

  static Object _setUpField1(Object value) {
    // Some complex logic
    return value;
  }
}
like image 20
mezoni Avatar answered Nov 18 '22 12:11

mezoni