ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်
ဒီ lesson က Intermediate/Advanced chapter မှာ သင်ခဲ့တဲ့ null safety, OOP (classes, constructors, inheritance, mixins) နဲ့ Future/async/await တို့ကို ပေါင်းစပ်ပြီး ဖြေရှင်းရမယ့် ခက်တဲ့ practice tasks တွေပါ။ Real app development မှာ ဒီ concept တွေအားလုံးကို သီးခြားစီ မသုံးဘဲ တစ်ခါတည်း ရောသုံးရတာများပါတယ်။ ဒါကြောင့် ဒီ exercises တွေက class hierarchy ထဲမှာ nullable field ကို ဘယ်လိုကိုင်တွယ်မလဲ၊ async function ကနေ object ကို ဘယ်လို return ခေါ်မလဲဆိုတာ practice ဖြစ်စေပါတယ်။ Solution ရေးပြီးရင် null safety error တွေ (`!`, `?`, `??`) ဘယ်နေရာမှာ ဖြစ်နိုင်လဲ စစ်ဆေးကြည့်ပါ။
လေ့ကျင့်ခန်းများ
Task 1: `Animal` base class ဆောက်ပြီး name (String) နဲ့ nullable `sound` (String?) field ထားပါ။ `makeSound()` method ကို sound null ဆို "..." print ဖြစ်အောင်၊ null မဟုတ်ရင် sound ကို print ဖြစ်အောင် null-aware operator (`??`) သုံးပါ။ Task 2: `Dog` class ကို `Animal` ကနေ inherit လုပ်ပြီး constructor မှာ `super` ခေါ်ပြီး sound ကို "Woof" default ထားပါ။ Task 3: `Flyable` mixin တစ်ခု ဆောက်ပြီး `fly()` method ထည့်ပြီး `Bird` class မှာ `Animal` ကို extend + `Flyable` ကို with သုံးပါ။ Task 4: `Future<Animal> fetchRandomAnimal()` async function ရေးပြီး `Future.delayed` 1 second စောင့်ပြီးမှ `Dog` object တစ်ခု return ပြန်ပါ၊ `main()` ထဲမှာ `await` သုံးပြီး ခေါ်ပြီး `makeSound()` ခေါ်ပါ။
Code နမူနာ
class Animal {
String name;
String? sound;
Animal(this.name, [this.sound]);
void makeSound() {
// TODO: use ?? to handle null sound
print('$name says ${sound ?? "..."}');
}
}
class Dog extends Animal {
Dog(String name) : super(name, 'Woof');
}
mixin Flyable {
void fly() => print('Flying...');
}
class Bird extends Animal with Flyable {
Bird(String name) : super(name, 'Tweet');
}
Future<Animal> fetchRandomAnimal() async {
await Future.delayed(Duration(seconds: 1));
return Dog('Rex');
}
void main() async {
final cat = Animal('Cat');
cat.makeSound();
final dog = Dog('Buddy');
dog.makeSound();
final bird = Bird('Sky');
bird.makeSound();
bird.fly();
print('Fetching...');
final randomAnimal = await fetchRandomAnimal();
randomAnimal.makeSound();
}Console မှာ Cat ('...'), Buddy ('Woof'), Sky ('Tweet' + 'Flying...'), ပြီးတော့ 1 second စောင့်ပြီးနောက် Rex ('Woof') တို့ အဆင့်လိုက် print ထွက်လာရမှာပါ။၅ မိနစ် စမ်းကြည့်
Timer 5 မိနစ်ထားပြီး `Cat` class အသစ်တစ်ခုကို `Animal` ကနေ inherit လုပ်ပြီး `Flyable` mixin မထည့်ဘဲ sound ကို null default ထားကာ `makeSound()` ခေါ်ကြည့်ပါ။
သတိလေးတစ်ချက်
Nullable field ရှိတဲ့ class ကို inherit လုပ်တဲ့အခါ subclass ထဲမှာ null check ကို ထပ်ကာကွယ်ထားဖို့ မမေ့ပါနဲ့၊ base class ကနေ null မကျန်ရင်တောင် defensive coding ကောင်းပါတယ်။