4

If a base class Logger has a method reportError that takes an Error object and formats it as a string.

If a subclass implements that method but outputs the string in a different format, yet a string format nonetheless, does it violate the LSP?

I know that adding methods to the subclass doesn’t violate the LSP, it just needs to be able to be tested where it’s base class is used.

1 Answer 1

8

That depends.

The LSP is about constraints on the methods - their inputs, their outputs, and their calling sequence.

If the requirements on the output of reportError are just "returns some string", then you're fine.

If the requirements explicitly state that the string has to be in a certain format, then you're in trouble.

Remember, not all requirements are necessarily expressible in the typesystem.

12
  • So if the requirement were that latter one, would it be better to add another method that produces the new format rather than attempting to override the base implementation?
    – pstatix
    Oct 22, 2020 at 21:02
  • 1
    @datta, Perhaps it would be good to add as a new method. Though without changing the consuming clients, no on will call your new method. You might also consider changing the definition of the original method (and fix any issues with that, as software is soft).
    – Erik Eidt
    Oct 22, 2020 at 21:58
  • @ErikEidt Unfortunately I have no control over the base class. The result from the method in question goes to file for later reading (review of the log). The only dependency would be if somebody was parsing log files. I need to add additional behavior to the base class, but I wanted to change how one of its implementations functioned (as in, altering the final format). Current consumers of the base class method will just see a new output format, does that cause an LSP violation? The program is not dependent on the output of the method.
    – pstatix
    Oct 22, 2020 at 22:41
  • 1
    @datta - in other words, if you have a lot of other code that relies on that string being in a certain format, then adding an override that violates that expectation gets you in trouble. If you don't have a lot of code that's like that, you can introduce a change on the expectations set by the base class (and require future clients that want to use it polymorphically not to expect a specific string format), or you can choose to leave it as is, and introduce a new method. Oct 22, 2020 at 22:41
  • 1
    Still, something worth documenting. Requirements like to change. Oct 22, 2020 at 22:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.