when I used the typedef in the code it didn't do anything extra except increase my line of code. I need to know when to use typedef and when to avoid it?
Code snippet using typedef
typedef SaySomething = void Function(String name);
void sayHello(String name){
print('Hello to $name');
}
void sayGoodbye(String name){
print('Goodbye to $name');
}
void main() {
// Using alias
SaySomething myFunction;
myFunction = sayHello;
myFunction('[email protected]');
myFunction = sayGoodbye;
myFunction('[email protected]');
}
Code snippet without using typedef
void sayHello(String name){print('Hello to $name');}
void sayGoodbye(String name){ print('Goodbye to $name');}
void main() {
sayHello('[email protected]');
sayGoodbye('[email protected]');
}
CodePudding user response:
So, it is my belief that there are very few situations in which you need typedef
, but it can help to avoid long code repetition, take a look at this example class:
class MyClass {
MyClass(this.value, {
this.onChange,
this.onSubmit,
this.onCancel,
this.onDelete,
this.onReset,
});
Map<String, Map<int, List<double>>> value;
void Function(Map<String, Map<int, List<double>>>)? onChange;
void Function(Map<String, Map<int, List<double>>>)? onSubmit;
void Function(Map<String, Map<int, List<double>>>)? onCancel;
void Function(Map<String, Map<int, List<double>>>)? onDelete;
void Function(Map<String, Map<int, List<double>>>)? onReset;
}
The above code is ugly to say the least, I think it is obvious how to use typedef here, but I will show it nonetheless.
typedef MyCallback = void Function(Map<String, Map<int, List<double>>>);
class MyClass {
MyClass(this.value, {
this.onChange,
this.onSubmit,
this.onCancel,
this.onDelete,
this.onReset,
});
Map<String, Map<int, List<double>>> value;
MyCallback? onChange;
MyCallback? onSubmit;
MyCallback? onCancel;
MyCallback? onDelete;
MyCallback? onReset;
}
or even
typedef MyClassValue = Map<String, Map<int, List<double>>>;
class MyClass {
MyClass(this.value, {
this.onChange,
this.onSubmit,
this.onCancel,
this.onDelete,
this.onReset,
});
MyClassValue value;
void Function(MyClassValue)? onChange;
void Function(MyClassValue)? onSubmit;
void Function(MyClassValue)? onCancel;
void Function(MyClassValue)? onDelete;
void Function(MyClassValue)? onReset;
}
Yes, it is more code, but the code is better looking.
In general, typedef
is suited for functional programming patterns where you find yourself passing functions as arguments and returning functions from functions.