Cohesion and Coupling
Cohesion means that the whole of a class sticks together (well, roughly). A class should be responsible for itself, should do one thing and as far as possible do everything for that one thing. For example: A Carclass should remember its make, colour, speed. It is responsible for changing speed; the speedUp() and slowDown() methods should be in the Carclass; no other class should make your Car go faster or slower.
Cohesion is (to quote sellers and Yeatman) A Good Thing.
Coupling means that one class gets at the implementation of another class.
For example:
Driver campbell = new Driver();
Car ford = new Car("Ford", "red");
. . .
public class Driver
{
Car myCar;
. . .
public void goFaster(int speed)
{
myCar.speed += speed;
}
. . .
}
The Car class has allowed access to its speed field and the Driver class changes its value directly. This means other classes gain access to the implementation of the Car class; any changes to that implementation will "break" the Driver class. This is "tight coupling" and tight coupling is A Bad Thing, because any changes to one class can mean that other classes would have to be altered too.
To avoid tight coupling
* All classes should have as small a public interface as possible.
* All non-constant fields should have private access.
* Any alterations to the values of fields should be via method calls.
Cohesion means that the whole of a class sticks together (well, roughly). A class should be responsible for itself, should do one thing and as far as possible do everything for that one thing. For example: A Carclass should remember its make, colour, speed. It is responsible for changing speed; the speedUp() and slowDown() methods should be in the Carclass; no other class should make your Car go faster or slower.
Cohesion is (to quote sellers and Yeatman) A Good Thing.
Coupling means that one class gets at the implementation of another class.
For example:
Driver campbell = new Driver();
Car ford = new Car("Ford", "red");
. . .
public class Driver
{
Car myCar;
. . .
public void goFaster(int speed)
{
myCar.speed += speed;
}
. . .
}
The Car class has allowed access to its speed field and the Driver class changes its value directly. This means other classes gain access to the implementation of the Car class; any changes to that implementation will "break" the Driver class. This is "tight coupling" and tight coupling is A Bad Thing, because any changes to one class can mean that other classes would have to be altered too.
To avoid tight coupling
* All classes should have as small a public interface as possible.
* All non-constant fields should have private access.
* Any alterations to the values of fields should be via method calls.