viernes, 27 de septiembre de 2013

Dependency Inversion Principle

This is the last principle of the SOLID principles and what it states is:
“A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.” (wikipedia)
This principle was stated by Robert C Martin. The main goal of this principle is decoupling.
Now as an example, let’s consider a “manager class which is a high level class, and the low level class Worker. We need to add a new module to our application because in the company there are some new specialized workers employed. We created a new class SuperWorker for this.”
“Let's assume that the Manager class is a complex one containing a very complex logic. And now we have to change it in order to introduce the new SuperWorker. Let's see the disadvantages:
we have to change the Manager class (remember it is a complex one and this will involve some time and effort). 
some present functionality from the manager class might be affected.
the unit testing should be redone.”
So, here is the code that violates the principle:
class Worker {
public void work() {
// ....working
}
}
class Manager {
Worker m_worker;

public void setWorker(Worker w) {
m_worker=w;
}

public void manage() {
m_worker.work();
}
}
class SuperWorker {
public void work() {
//.... working much more
}


And applying this principle we should obtain something like:

interface IWorker {
public void work();
}

class Worker implements IWorker{
public void work() {
// ....working
}
}

class SuperWorker  implements IWorker{
public void work() {
//.... working much more
}
}

class Manager {
IWorker m_worker;

public void setWorker(IWorker w) {
m_worker=w;
}

public void manage() {
m_worker.work();
}
}

Bibliography
OODesign.com. (n.d.). OODesign.com. Retrieved august 11, 2013, from http://www.oodesign.com/dependency-inversion-principle.html
wikipedia. (n.d.). wikipedia.org. Retrieved august 11, 2013, from http://en.wikipedia.org/wiki/Dependency_inversion_principle

No hay comentarios:

Publicar un comentario