Explain how the open-closed principle is applied in the development of software components in practice.
sobes.tech AI
Answer from AI
The Open/Closed Principle in software component development means that a class or module should be open for extension but closed for modification. In the context of Flutter, this is often implemented through the use of abstractions, inheritance, and composition.
For example, if you have a widget that displays a list and you want to add new sorting or filtering logic, instead of modifying the existing widget, you create a new class that extends or wraps the original, adding new functionality. This allows you to avoid touching tested code, reducing the risk of errors.
Example:
abstract class SortStrategy {
List<String> sort(List<String> items);
}
class AlphabeticalSort implements SortStrategy {
@override
List<String> sort(List<String> items) => items..sort();
}
class CustomListWidget extends StatelessWidget {
final List<String> items;
final SortStrategy sortStrategy;
CustomListWidget({required this.items, required this.sortStrategy});
@override
Widget build(BuildContext context) {
final sortedItems = sortStrategy.sort(items);
return ListView(
children: sortedItems.map((item) => Text(item)).toList(),
);
}
}
Here, CustomListWidget is open for extension through passing different sorting strategies but does not change itself when new sorting methods are added.