Search code examples
objective-coopsolid-principles

How does the SOLID principle apply to method overrides in Objective-C?


I read an explanation of the "SOLID" principle. Here is an explanation of the 'L' part:

objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program

So for example I have MYViewController : UIViewController

when I override viewDidLoad, it means that I changed the base view controller's logic. Right? Does it mean that I am altering the correctness of that program?

Or did I misunderstand that point?


Solution

  • The fact that you override viewDidLoad does not constitute a violation of Liskov substitution principle (LSP). (The function of a subclass generally is to expand upon the behavior of the superclass.) It's actually the other way around, that you violate this LSP if you implement behavior in the subclass such that it could no longer be used in cases where you reference the base class.

    But LSP isn't a situation where we're contemplating a completely different class (e.g. ice cream object; lol). We're generally concerned where we're dealing with an actual subclass, but one that can no longer replace a reference to its base class.

    When overriding a method, if the the code calls the super implementation as appropriate, it generally satisfies LSP. And to your question about viewDidLoad, you always want to call super in that case.