Topic 7: Design Patterns: Coupling, Cohesion and Separation of Concerns

Note: this topic is a lecture-only topic. There is no accompanying practical. This is to allow you all to catch up with Week 7, which only a few of you have completed.

Credits for this week's notes

What is a design pattern?

A software pattern is:

General good design principles

Following patterns is a way to ensure that your code follows general good design principles:

Low coupling

What is wrong with dependency on other classes?

Minimise, do not necessarily eliminate, dependencies

Coupling example - College, Course and Student

High coupling design (bad)

An even worse example

Low coupling alternative

Student no longer depends on College in this example

 

class Student
{
    ArrayList<Course> courses;

    public Student()
    {
        courses = new ArrayList<Course>();
    }
    
    public void enrolOn(Course course)
    {
        courses.add(course);
    }
}

Coupling and user interfaces - summary

High Cohesion pattern

Example of a high cohesion pattern

Another example of a high cohesion pattern: web communication

Exercise

Look at these two github repositories:

https://github.com/nwcourses/coupling.git
https://github.com/nwcourses/cohesion.git
The former shows a high coupling design, the latter a low cohesion design. Redesign and change the code so they have low coupling and high cohesion, respectively. Also look for other problems with their design and correct them!