Reputation: 27129
I never did proper class design, so bear with me.
Let's say we have a Project
class. Then let's say we have a ProjectGroup
class that has the same members as the Project
class, plus a list of Project
s.
Should ProjectGroup
be the superclass of Project
or is ProjectGroup
a specialization of Project
and the former should be a subclass of the latter?
Upvotes: 2
Views: 314
Reputation: 105059
I won't bother you with theory, because you're probably in a hurry to get a quick answer. So here it goes:
If your two classes are actually implying they should be related by inheritance then ProjectGroup
should inherit from Project
class. This is how it would look like in C#:
public class ProjectGroup: Project ...
If they are not, but they use some common class members (that define their state and some functionality over that state), then I'd write an interface and implement it in both classes. C# code again:
public interface ICommonState ...
public class Project: ICommonState ...
public class ProjectGroup: ICommonState
{
IEnumerable<ICommonState> projects
...
}
If your classes are actually Project
and ProjectGroup
and they both have properties like ID
and Name
in common (for instance), they still shouldn't be inherited. They just happen to have properties with the same name, but they are basically different entities.
They could both either
ICommonEntity
interface - use it when they have the same state+functionality but functionality behaves differently in each of themCommonEntity
class - use it when functionality is completely identical; this way you'll follow the DRY (don't repeat yourself) philosophySo your component may be an interface or a class (when using composite pattern).
Direct inheritance between two classes is more suitable where entities imply on being in relation to each other. Like User
and Person
classes. They can be inherited either way. Depending on the business scenario.
class User: Person
This would be the case where you have an application with contacts. Some of them are also users of this very same application.
class Person: User
This would be a web site where you can register as a user. In case you fill up some personal details as well your user data becomes of type Person
.
Upvotes: 2
Reputation: 362
It sounds like you might want the Composite pattern. Both LeafProject and CompositeProject implement the Project interface, and CompositeProject also holds a collection of Project instances.
Upvotes: 2
Reputation: 2203
if the member list of projects is unique to projectgroup and does not apply to all types of projects, then make project your super/base class and derive projectgroup from project.
Upvotes: 0