What is the best way to set a default instance for a trailing private field with an optional parameter?
For a class with a trailing 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();
}
}
Trying to set it in the parameter list will result in an error
//error: default values of an object must be constant
Foo({Bar bar: new Bar()}) : _bar = bar ..
I would like to keep an optional parameter so that I can inject mocks during unit tests. What's the best approach to do this?
+3
ZeroDivide
source
to share
2 answers
class Foo {
final Bar _bar;
Foo({Bar bar}) : _bar = bar != null ? bar : new Bar();
}
+3
Alexandre ardhuin
source
to share
I recommend using static methods when the logic is complex.
class Foo {
final Object _field1;
Foo({Object value1}) : this._field1 = _setUpField1(value1);
static Object _setUpField1(Object value) {
// Some complex logic
return value;
}
}
+1
mezoni
source
to share