2

The Interface Segregation principle states that:

Clients should not be forced to depend on methods that they do not use.

In the Null object pattern the Null class that implements the interface does nothing with it. Which is intentional.

But, it is depending on methods that it doesn't use. Or does it not break the principle because it actually does simply just depend on it by not doing anything in the implemented methods?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Mahmut
  • 33
  • 6
  • 2
    The client *is* using the methods on the null object. That the method does nothing is opaque to the client. – Andy Turner May 20 '16 at 20:39
  • 2
    The point of a null object is that the methods *are* used, though; they just don't have significant effect. E.g., if an interface specifies a method that returns a list, the null object implementation of that interface can return an empty list. The point is that the client using that null object *does* call the method that returns a list, and needs to get a list. – Joshua Taylor May 20 '16 at 20:39
  • Thanks Joshua and Andy. Now I have a better understanding. – Mahmut May 21 '16 at 13:07
  • 1
    A much more interesting question would be: "Does Null Object Pattern break Liskov Substitution Principle?". – Steven May 22 '16 at 13:28

2 Answers2

3

Typically, the Null object pattern does not take any dependencies. Here is how a typical Null object looks like:

public class NullDataStore : IDataStore
{
    public void StoreData(Data data)
    {

    }
}

The NullDataStore class in this case has no dependencies and therefore it does not depend on methods that it does not use. So it does not break the ISP.

Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
0

Null object pattern doesn't break interface segregation principle per se.

It's not the null object who can break the whole principle, but it'll be the interface of the null object which may or may not expose members that have nothing to do with a given operation where the object is injected.

If the null object implements an interface and a part of the project may use a regular object with actual implementations of its members, and that interface exposes just what's actually required, then the interface segregation principle isn't broken by that given interface.

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206