Senior
What is your attitude towards very long classes containing from 2000 to 4000 lines of code?
sobes.tech AI
Answer from AI
I am extremely negative about this. It is a clear sign of violations of SOLID principles, particularly the Single Responsibility Principle (SRP). Such classes are difficult to read, debug, test, and modify.
Problems that arise with very long classes:
- Low readability and understanding: Difficult to quickly grasp the entire functionality of the class.
- High coupling: Changes in one part of the class can unintentionally affect others.
- Low cohesion: The class likely performs too many heterogeneous tasks.
- Testing difficulties: Hard to write unit tests for individual parts of the logic.
- Code duplication: Changes or additions often lead to duplication.
- Increased build time: Large files can slow down compilation.
Solution – refactoring:
- Extracting functional blocks into new classes or interfaces.
- Using design patterns to improve structure (e.g., Strategy, Observer, Factory).
- Applying KISS (Keep It Simple, Stupid) and DRY (Don't Repeat Yourself) principles.
// Example of SRP violation
class BigActivity {
fun loadUserData() { /* ... lots of code ... */ }
fun processPayment() { /* ... lots of code ... */ }
fun displayUI() { /* ... lots of code ... */ }
}
// Example of improvement – separation of responsibilities
class UserDataLoader {
fun loadUserData() { /* ... loading code ... */ }
}
class PaymentProcessor {
fun processPayment() { /* ... payment code ... */ }
}
class UserActivity { // now only responsible for UI and coordination
private val userDataLoader = UserDataLoader()
private val paymentProcessor = PaymentProcessor()
fun init() {
userDataLoader.loadUserData()
}
fun onPaymentButtonClick() {
paymentProcessor.processPayment()
}
fun displayUI() { /* ... UI rendering code ... */ }
}
Overall, such classes are "code smell" and require immediate attention to improve maintainability and system stability.