Software

Separation of Concerns

Separation of Concerns principle helps to create flexible, reusable and maintainable software systems. But it is an ongoing process throughout the design process.

Concern it is anything that matters in providing a solution to a problem. Some of the concerns in software may involve:

  • What information the implementation represents.
  • What it manipulates.
  • What gets presented at the end.

Example with SmartPhone, let’s say we have the next class:

//The code has low cohesion.
public class SmartPhone{
    private byte camera;
    private byte phone;

    public SmartPhone() { ... }

    public void takePhoto() { ... }
    public void savePhoto() { ... }
    public void cameraFlash() { ... }

    public void makePhoneCall() { ... }
    public void encryptOutgoingSound() { ... }
    public void dechipherIncomingSound() { ... }
}

The SmartPhone class has 2 concerns:

  • Act as a traditional phone.
  • Be able to use the built-in camera to take pictures.

As the concerns were identified, we can separate them out into their own more cohesive classes nd encapsulate all the details about each into functionally distinct and independent classes. Hence the SmartPhone don’t know how each component behaves.

Separation of Concern SmartPhone Class Diagram.png

Firstly must extract the attributes and behaviors of both camera and traditional phone into 2 separate interfaces. Then can implement the interfaces.

// Now the SmartPhone class more cohesive.
public class SmartPhone {
    private ICamera myCamera;
    private IPhone myPhone;

    public SmartPhone(ICamera aCamera, IPhone aPhone) {
        this.myCamera = aCamera;
        this.myPhone = aPhone;
    }

    public void useCamera() {
        return this.myCamera.rakePhoto();
    }

    public void usePhone() {
        return this.myPhone.makePhoneCall();
    }
}

The Separation of Concerns creates more cohesive classes using abstraction, encapsulation, decomposition and generalization. This creates a system which easier to maintain because each class is organized so it only contains the code that it needs to do its job. Modularity allows developers to reuse and build up individual classes without affecting others and it is clear where the boundaries of each class are.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.