Sobes.tech
Junior — Middle

Could you give an example where the principle of single responsibility is violated in code?

sobes.tech AI

Answer from AI

The Single Responsibility Principle (SRP) states that a class or module should have only one reason to change, meaning it should be responsible for a single specific task.

Example of SRP violation in Android:

public class UserProfileActivity extends AppCompatActivity {
    // Responsible for UI, data loading, and settings saving

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_profile);

        // Loading user data from network
        loadUserData();

        // Handling save button click
        findViewById(R.id.saveButton).setOnClickListener(v -> saveUserSettings());
    }

    private void loadUserData() {
        // Network operation
    }

    private void saveUserSettings() {
        // Saving settings
    }
}

Here, UserProfileActivity is responsible for UI display, data loading, and settings saving — this violates SRP. It is better to separate these responsibilities into different classes, for example, using a ViewModel for business logic and a separate class for network operations.