I have around 200 classes. 5% of them are unique, 95% of them have properties
int CantonID
int EntityID
int MunicipalityID
// other fields
and around 70% of these 95% have
int CantonID
int EntityID
int MunicipalityID
int Year
int Month
//other fields
(other 30% of these 95% don't have year and month properties).
So what is best solution to approach this? My idea was:
- these 5% of unique should be independent
- remaining 95% will inherit
BaseClass
that have fields:
int CantonID
int EntityID
int MunicipalityID
but I am not sure what to do with Year and Month. I can't add them to BaseClass
because 30% of them will inherit properties that they should not have, but I don't know how to encapsulate them. I was reading about builder design pattern, but I'm not 100% sure it is for this situation.
CodePudding user response:
You don't need a common base class.
class A
{
public int CantonID {get; set;}
public int EntityID {get; set;}
public int MunicipalityID {get; set;}
}
class B : A
{
public int Year {get; set;}
public int Month {get; set;}
}
B inherits all the members of A and adds Year and Month
CodePudding user response:
but I don't know how to encapsulate them
OOP and specifically encapsulation is about behavior, not "properties". Trying to apply these concepts to "properties" will always be strange and foreign to OOP.
Your api (i.e. your classes and method signatures) should instead deal with what these things do, instead of what they consist of. Since you say you have 200 classes full of properties, I'm not sure what you're modeling. What is the behavior that these things are supposed to support?
If you have that, create classes/method that specifically support that, regardless of properties. I know that may be completely different to what you're used to. I leave this here, just to note that there are other ways to think about this.
CodePudding user response:
As an alternative to inheritance, we can use composition:
class A
{
public int CantonID { get; set; }
public int EntityID { get; set; }
public int MunicipalityID { get; set; }
}
class B
{
private A _a;
public B(A a)
{
_a = a;
}
public int Year { get; set; }
public int Month { get; set; }
}
Read more about design principle prefer composition over inheritance