Implementing SOLID principles with TypeScript in a Password Generator Project.
- Single Responsibility Principle (SRP)
- Open/Closed Principle (OCP)
- Liskov Substitution Principle (LSP)
- Interface Segregation Principle
- Dependency Inversion Principle
Every class should have a single responsibility. A class should have one, and only one, reason to change.
You should be able to extend a classes behavior, without modifying it. Software entities should be open for extension, but closed for modification.
Derived classes must be substitutable for their base classes. Functions that use references to base classes must be able to use objects of derived classes without knowing it.
Make fine grained interfaces that are client specific. Clients should not be forced to depend on interfaces they do not use.
Depend on abstractions, not on concretions. High-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details. Details should depend on abstractions.
We can generate a password based on the following rules:
- Require a minimum of characters;
- Require at least one upper case character;
- Require at least one number character;
- Require at least one special character.
- We created a class for each rule under the
./src/domain/rules
folder to ensure the Single Responsibility Principle (SRP). - We created the
RuleFactory
class to be responsible for creating a list of rules based on user options, following again the SRP. - We created the
RuleFactory
class to be open for extension but closed for modification. We can easily add new rules by extending theruleClassMap
without modifying existing code (OCP). - Each rule under the
./src/domain/rules
folder implements theIPasswordGenerationRule
interface, ensuring that they are substitutable for the base type without altering the correctness of the program (LSP). - The
IPasswordGenerationRule
interface follows the Interface Segregation Principle by providing a specific method (applyRule
) relevant to the implementing rule classes. The Rule class (e.g., RequireNumberRule, RequireSpecialCharacterRule, RequireUpperCaseRule) are not forced to depend on unnecessary methods (ISP). - The
RuleFactory
class depends on the abstraction provided by theIPasswordGenerationRule
interface, ensuring that high-level modules depend on abstractions rather than concrete implementations.
- nodejs
18.12.1
- typescript
5.3.3
- jest
^29.7.0
- yarn
1.22.19
yarn install
yarn test
Feel free to contribute and share your ideas. Open an issue and/or a Pull Request. Let's talk about SOLID principles and implementing the best practices!
@laisfrigerio |
---|
This project is licensed under the MIT License - see the LICENSE.md file for details