viernes, 13 de septiembre de 2013

Interface Segregation Principle

This principle was postulated by Robert C Martin. It says that “no client should be forced to depend on methods it does not use” (wikipedia.org). But also in another site I found this other that I like much more “The ISP specifies that clients should not be forced to depend upon interfaces that they do not use. Instead, those interfaces should be minimised.” (Carr, 2011)
As an example of the violation of this principle we can have:

public class Contact
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string EmailAddress { get; set; }
    public string Telephone { get; set; }
}

public class Emailer
{
    public void SendMessage(Contact contact, string subject, string body)
    {
        // Code to send email, using contact's email address and name
    }
}
  
public class Dialler
{
    public void MakeCall(Contact contact)
    {
        // Code to dial telephone number of contact
    }
}

But wait, why that this code violates the principle?? well the answer is that the classes Emailer and Dialler just need  some “attributes” of the class Contact, but they have access to all of them. And what we do is to hide the attributes or properties that are not needed for the classes.Doing that we got a consequence an violate another SOLID principle, but it represents clearly what  this principle means.
So, applying this principle we should get:

public interface IEmailable
{
    string Name { get; set; }
    string EmailAddress { get; set; }
}
public interface IDiallable
{
    string Telephone { get; set; }
}
public class Contact : IEmailable, IDiallable
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string EmailAddress { get; set; }
    public string Telephone { get; set; }
}


public class MobileEngineer : IDiallable
{
    public string Name { get; set; }
    public string Vehicle { get; set; }
    public string Telephone { get; set; }
}

public class Emailer
{
    public void SendMessage(IEmailable target, string subject, string body)
    {
        // Code to send email, using target's email address and name
    }
}


public class Dialler
{
    public void MakeCall(IDiallable target)
    {
        // Code to dial telephone number of target
    }
}


Bibliography
Carr, R. (2011, january). blackwasp.co.uk. Retrieved august 11, 2013, from http://www.blackwasp.co.uk/ISP.aspx
wikipedia.org. (n.d.). wikiperia.org. Retrieved august 11, 2013, from http://en.wikipedia.org/wiki/Interface_segregation_principle

No hay comentarios:

Publicar un comentario