违反层次里氏 - 那又怎么样呢? [英] Hierarchy violates Liskov - so what?

查看:86
本文介绍了违反层次里氏 - 那又怎么样呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用违反了里氏替换原则的API:它抛出一个扩展异常了自己的异常类型,但在一个新的错误码现场把异常消息从基类,并在消息把自己的(无用)消息领域。因此,以显示正确的消息,我需要异常转换为DerivedException类型和使用错误码字段。如果我把它当作一个Exception对象,我得到了错误的信息。

I am using an API that violates the Liskov substitution principle : it throws its own Exception type that extends Exception, but puts the exception message from the base class in a new ErrorCode field and puts its own (useless) message in the Message field. Therefore to display the correct message I need to cast the Exception to the DerivedException type and use the ErrorCode field. If I treat it as an Exception object I get the wrong message.

现在这惹恼了我对文体的水平,但它是很容易得到解决:我可以赶上DerivedException并把它作为预期的程序设计师。所以我的问题是:什么是关于Liskov的原则大不了的? ?什么是实际问题,人们可能会遇到的使用违反原则的层次结构

Now this irks me on a stylistic level, but it is easy enough to get around : I can just catch DerivedException and use it as the programer intended. So my question is this : what's the big deal about the Liskov principle? What are the practical problems that people might encounter using hierarchies that violate the principle?

推荐答案

一个实际的例子:

如果你将有一个日志类的方法 LogException(异常前)它会记录你把没用的信息,而不是真正的消息。

If you would have a logging class with a method LogException(Exception ex) it will log the message you regard useless, instead of the "real" message.

日志方法的说明会由记录异常的信息改为记录异常消息,但有时记录了无用短信。

The description of the log method would change from "logs Exception messages" to "logs Exception messages, but sometimes logs useless messages".

这篇关于违反层次里氏 - 那又怎么样呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆