Junior — Middle
What principles are important to consider for writing testable and reliable code?
sobes.tech AI
Answer from AI
To write testable and reliable code, it is important to consider the following principles:
- Single Responsibility Principle: Each class or module should be responsible for one specific task.
- Dependency Injection: Dependencies should be passed from outside, making it easier to replace them with stubs or mocks in tests.
- Avoid tight coupling: Use abstractions (protocols, interfaces) so that components are loosely coupled.
- Code coverage with tests: Write unit tests for key components to quickly identify errors.
- Simplicity and readability: Code should be understandable and maintainable.
Example of dependency injection in Swift:
protocol NetworkService {
func fetchData() -> String
}
class RealNetworkService: NetworkService {
func fetchData() -> String {
return "Real data"
}
}
class MockNetworkService: NetworkService {
func fetchData() -> String {
return "Mock data"
}
}
class DataManager {
let service: NetworkService
init(service: NetworkService) {
self.service = service
}
func getData() -> String {
return service.fetchData()
}
}
// In tests, you can use MockNetworkService
let mockService = MockNetworkService()
let dataManager = DataManager(service: mockService)
print(dataManager.getData()) // Outputs: Mock data
This approach facilitates testing and increases the reliability of the application.