I know that it is poor programming and architecture when you have a class object that is only to be used in one place. But I've also been warned about creating an object that is all powerful and that can do too much. So how do I break this down? Here is an example of what I mean - please don't take these things literal as this is only an example.
Anyway I have an object that I am working with which is rather complex. A lot of information is stored in this object and it can perform much manipulation on the data. So, let's call this object Earth.
Public Class Planet
Private _population As UInteger = 0
Public ReadOnly Property Population() As UInteger
Get
Return _population
End Get
End Property
Public Overridable Sub CreatePerson(Optional ByVal numberOfPeople As Integer = 1)
_population += numberOfPeople
End Sub
End Class
Simple enough so far. But I could go on and on with the many things that object could possibly perform. So, in order to keep things from getting too complex I broke down "activites" that would happen during the day and during the night by creating two other Objects: Day and Night (these two are n开发者_StackOverflow社区ot shown). So now I have an updated Planet class.
Public Class Planet
Private _population As UInteger = 0
Private _day As New Day
Private _night As New Night
Public ReadOnly Property Day() As Day
Get
Return _day
End Get
End Property
Public ReadOnly Property Night() As Night
Get
Return _night
End Get
End Property
Public ReadOnly Property Population() As UInteger
Get
Return _population
End Get
End Property
Public Overridable Sub CreatePerson(Optional ByVal numberOfPeople As Integer = 1)
_population += numberOfPeople
End Sub
End Class
Now, these two classes - Day and Night - will never be used outside of the Planet class. Is this a good way to organize my methods and attributes for this "parent" class Planet? How else would I neatly organize similar?
I've read about refactoring but I don't think this helps my case. I like the idea that I can call on an Planet object like this: Earth.Night.BlowUpMoon
.
Think in terms of discoverability. If someone else were to use your object would they know that they have to go to a specific time of day to blow up the moon, which is the same as BirthdayCard.September25th.Send()
? Any by "someone else" I also include you in 6 months. Are you organizing for the sake of organizing or are you putting similar methods and properties together in a way that makes sense?
Although your example is contrived, this situation is common practive in Domain Driven Design. Your Planet class would be an aggregate - a root object that manages its own internal entities. Outside the aggregate boundary all interaction is via the root aggregate object.
Refactor your class and split it to several smaller classes, each with a single responsibility. It doesn't matter that each of them will only be used once - the code will still be better, easier to understand, and far more testable.
精彩评论