3

From Liskov Substitution Principle - www.blackwasp.co.uk

One common indication of non-compliance with the LSP is when a client class checks the type of its dependencies. This may be by reading a property of an object that artificially describes its type or by using reflection to obtain the type. Often a switch statement will be used to perform a different action according to the type of the dependency. This additional complexity also violates the Open / Closed Principle (OCP), as the client class will need to be modified as further subclasses are introduced.

Does following techonolgies (that use reflection) cause a violation of LSP?

  1. Dependency Injection
  2. Inversion Of Control

Note: I am from C# background.

From http://blogs.msdn.com/b/simonince/archive/2008/06/30/dependency-injection-is-dead.aspx

Reflection; most (perhaps all?) Dependency Injection containers rely on some extent on Reflection – dynamically inspecting objects and determining their dependencies.

REFERENCES:

  1. Hierarchy violates Liskov - so what?

  2. How can I avoid breaking Liskov Substitution Principle (LSP)?

  3. Does Liskov Substitution Principle also apply to classes implementing an interface?

  4. Does this violate the Liskov substitution principle, and if so, what do I do about it?

  5. Does GWT's ActivityMapper violate the Liskov Substitution Principle?

Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418
  • 2
    *"One common indication of non-compliance with the LSP is ... reflection"* - this does not mean that *all uses* of reflection violate LSP. – MattDavey Jun 19 '13 at 08:07

1 Answers1

3

The way i understand LSP, it simply states that subclasses should be substitutable for their base class in every situation, that is whenever you pass an instance of the base class (to a method, constructor, service, etc ..) you should be able to pass an instance of the subclass instead without any code modification for this to work. Like any other principle, LSP is a guideline and not a strict rule, it makes our code more open for extensibility. When framework writers use reflection they are not breaking LSP, you can simply contrast this with frameworks using Service Location which is now considered an anti-pattern by many OO proponents but they have to do that so their framework let you choose your own container. as always, it is a tradeoff and it depends on the Context (your own specific use case).

MattDavey
  • 8,897
  • 3
  • 31
  • 54
Ibrahim Najjar
  • 19,178
  • 4
  • 69
  • 95