Swift.fatalError() in iOS apps can violate this design principle
Articles Blog

Swift.fatalError() in iOS apps can violate this design principle

February 7, 2020


Caio: Next, the Liskov Substitution Principle. Objects should be replaceable with instances of their subtypes. What does that mean? Jose: For me, it’s when one of your implementations doesn’t implement something… or causes a fatal error or a crash. Caio: So without breaking the system. Let’s say you have a protocol Service… and you have a function “load” and you pass a service. If you check here… “guard let myService=service as? MyService” which is a specific type and if it’s not you call fatal error which crashes the app. So this interface is saying “I accept any service…” but internally it says “I only accept a MyService subtype.” And this is problematic because you have problems at runtime. Another problem is if you have two methods, for example, “start” and “stop”. And your MyService implementation can only start but it can’t stop. So in the “stop” implementation, you call fatal error “cannot stop.” That’s also a problem at runtime because… even if this function accepts it… if it calls “stop” you’ll have a runtime error if it passes a MyService instance. So, that’s not actually a subtype of Service… because every Service should be able to handle the message stop and start. So any type that doesn’t handle something that is exposed in the interface… is a violation of the Liskov Substitution Principle.

Leave a Reply

Your email address will not be published. Required fields are marked *