问题
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