The Liskov Substitution Principle (LSP) states that objects of a superclass should be able to be replaced with objects of a subclass without affecting the correctness of the program. In other words, a subclass should be able to replace its superclass without breaking the code.
I’m trying to figure out how it could be a good implementation in a real world example, where we use the subclass everywhere in our code and only use the superclass on instantiation.
This is my approach:
class User {
const User({
required this.id,
required this.avatar,
});
final String id;
final String avatar;
String? getName() => null;
}
class UserWithName extends User {
const UserWithName(
{required super.id, required super.avatar, required this.name});
final String name;
String getName() => this.name;
}
void main() {
User user = new User(id: '0', avatar: 'avatar');
User userWithName = new UserWithName(id: '0', avatar: 'avatar', name: 'User Name');
print('hello ${user.getName()}');
print('hello ${userWithName.getName()}');
}
Returns:
hello null
hello User Name
Any suggestion or correction is very welcome.
4