Inheritance - variable initialisation in subclass

柔情痞子 提交于 2020-01-17 02:36:13

问题


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

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.

I wish the previous developer left more documentation.


回答1:


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?



来源:https://stackoverflow.com/questions/15772573/inheritance-variable-initialisation-in-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!