继承 - 子类中的变量初始化 [英] Inheritance - variable initialisation in subclass
问题描述
我倾向于根据我在大学学到的最佳实践类课程,在可能的基础上,继承组合。我正在看一个应用程序中的一些代码,如下所示:
I tend to favour composition over inheritance where possible based on what I learnt at university on "best practices" type course. I am looking at some code in an application, which looks like this:
Public Class A
Protected _Name As String
Public Property Name() As String
Get
Return _Name
End Get
Set(ByVal value As String)
_Name = value
End Set
End Property
End Class
Public Class B
Inherits A
End Class
Public Class C
Inherits B
End Class
Public Class D
Inherits C
Public Sub SomeMethod()
'This isn't good
Name = "Ian"
End Sub
Public Shared Sub Main()
Dim d As New D
d.SomeMethod()
End Sub
End Class
在上面的例子中:D类是在A类中使用公共财产。以前的开发人员在类中初始化名称之后写了这不好 D.我相信他写这个评论的原因是由于业务规则,而不是他在D类中分配了a.Name的值。但是,我想检查上面的代码是否有任何错误。 a.Name由所有子类共享。 B,C和D类包含很多重载方法,所以我相信在这种情况下继承是正确的设计选择。
In the example above: Class D is using a public property in class A. The previous developer has written "this isn't good" above the initialisation of name in class D. I believe that the reason he has written this comment is due to business rules and not the fact that he has assigned the value of a.Name in class D. However, I wanted to check if there is anything wrong with the code above. a.Name is shared by all subclasses. Classes B,C and D contain lots of overloaded methods so I believe inheritance was the correct design choice in this case.
我希望以前的开发者留下更多的文档。 p>
I wish the previous developer left more documentation.
推荐答案
在派生类中为父属性分配值没有什么不妥,如果不会破坏父类的预期行为类型(请参阅 Liskov替代原则)。您示例中的D类仍然可以被视为类A.如果改变Name属性对于类A没有禁止的行为(我相信不是,因为该属性有一个setter),那么赋值很可能不是
There is nothing bad in assigning a value to a parent property in a derived class, if that does not break the expected behaviour of parent type (see Liskov substitution principle). The type D in your example still can be treated as class A. If changing of Name property is not forbidden behaviour for class A (which I believe is not, because there is a setter for that property), then the assignment is likely not a problem.
也许以前的开发者在他的评论中解决的问题是直接从数据层获取值,而不是从业务层获取价值?
Maybe the problem the previous developer addressed in his comment was in taking a value directly from the data layer and not from the business layer?
这篇关于继承 - 子类中的变量初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!