5. You want to improve a blockchain smart contract's code quality by making it reusable and easier to maintain. Which design pattern should you apply and why?
Options:
A) Singleton - to ensure only one contract instance exists.
B) Factory - to create different contract types from a single interface.
C) Observer - to notify multiple contracts about state changes.
D) Decorator - to add new features to contracts without changing their code.
hard
A. Factory - creates various contract types, improving reusability and maintenance.
B. Singleton - limits to one instance, not focused on reusability.
C. Observer - manages notifications, not primarily for reusability.
D. Decorator - adds features but can complicate maintenance.
Solution
Step 1: Identify goal - reusability and easier maintenance
The Factory pattern helps by creating different contract types through a single interface, making code reusable and easier to maintain.
Step 2: Compare other patterns
Singleton restricts instances, Observer handles notifications, and Decorator adds features but may increase complexity.
Final Answer:
Factory - creates different contract types from a single interface. -> Option A
Quick Check:
Reusability and maintenance = Factory pattern B [OK]