Junior — Middle
Do you use SOLID principles when writing code?
sobes.tech AI
Answer from AI
Yes, I use SOLID principles when writing code because they help create more maintainable, extendable, and readable code. For example:
- Single Responsibility Principle (SRP): each module or class is responsible for one specific task.
- Open/Closed Principle (OCP): classes are open for extension but closed for modification.
- Liskov Substitution Principle (LSP): subclasses can replace base classes without breaking logic.
- Interface Segregation Principle (ISP): it's better to have several specialized interfaces than one universal.
- Dependency Inversion Principle (DIP): dependencies should be based on abstractions, not on concrete implementations.
Example in Node.js (simplified):
// SRP example: class only responsible for user management
class UserService {
constructor(userRepository) {
this.userRepository = userRepository;
}
createUser(data) {
// user creation logic
return this.userRepository.save(data);
}
}
// DIP example: UserService depends on an abstraction userRepository
class UserRepository {
save(user) {
// save to database
}
}
const userRepository = new UserRepository();
const userService = new UserService(userRepository);
This approach makes the code easier to test and maintain.