I have multiple constructors in the same class and they have many assert functions which is the same for all constructors. For example a class Foo have 2 constructors:
Foo({...some params}):assert(conditionA),assert(conditionB),assert(conditionC);
Foo.fromForm({...some params}):assert(conditionA),assert(conditionB),assert(conditionC);
Is there any ways that i can group the assert and share to the two constructors?
CodePudding user response:
You can share the assertions by making your named constructor call the unnamed one.
Let's say I have defined my class Foo
like this:
class Foo {
final int? paramA;
final bool? paramB;
Foo({
this.paramA,
this.paramB,
}) : assert(
(paramA == null && paramB != null) ||
(paramA != null && paramB == null),
'You cannot use both paramA and paramB',
),
assert(
paramA == null || paramA > 0,
'When specified paramA must be superior to 0',
);
}
I can have an assertion error when doing the following:
Foo(paramA: -1); // Assertion failed: "When specified paramA must be superior to 0"
Foo(paramA: 1, paramB: false); // Assertion failed: "You cannot use both paramA and paramB"
Now if I declare my secondary constructor as follow:
class Foo {
// ...
Foo.fromForm(int param) : this(paramA: param);
}
When using this()
I define that my Foo.fromForm
constructor will call my base unnamed Foo
constructor and will beneficiate from its assert
.
This could also work by using an abstract class:
abstract class BaseFoo {
BaseFoo({
required int? paramA,
required bool? paramB,
}) : assert(
(paramA == null && paramB != null) ||
(paramA != null && paramB == null),
'You cannot use both paramA and paramB',
),
assert(
paramA == null || paramA > 0,
'When specified paramA must be superior to 0',
);
}
class Foo extends BaseFoo {
final int? paramA;
final bool? paramB;
Foo({
this.paramA,
this.paramB,
}) : super(paramA: paramA, paramB: paramB);
// You can also call this()
Foo.fromForm(int param)
: paramA = param,
paramB = null,
super(paramA: param, paramB: null);
}