I would agree that you should create a Dimensions
class that has the Thickness
, Length
, Width
properties, along with the GetVolume()
method. You probably do NOT want to create a base class with these members and have Member
and OtherMember
inherit from it because Member
and OtherMember
have dimensions, they are not super classes of dimensions. I'll try to lay out some guidelines so you can make the best decision for your case below.
For the interface, it is possibly a good idea since there are multiple ways volume can be calculated.
public interface ISolid{
double Volume { get; }
}
public class Cylinder: ISolid{
public double Height { get; set; }
public double Radius { get; set; }
public double Volume {
get
{
return (2 * Math.Pi * Radius ^ 2) * Height;
}
}
}
public class Cube: ISolid{
public double Width { get; set; }
public double Height { get; set; }
public double Depth { get; set; }
public double Volume {
get
{
return Width * Height * Depth;
}
}
}
It isn't clear what Member and OtherMember are, they have labels and other things that may not be represented well by inheriting straight from these types defined above. Also, multiple inheritance can make things complicated. So you need to look at your own domain objects and ask yourself, is this class a superclass (inheritance) or does it just need to use the other class to define some characteristic of itself (composition)
public class SodaCan: Cylinder
{
public SodaCan(string brand)
{
Brand = brand;
IsFull = true;
Height = 5D;
Radius = 1.5D;
}
public string Brand { get; private set; }
public bool IsFull { get; set; }
}
or
public class SodaCan: BeverageHolder
{
public SodaCan(string brand)
{
Brand = brand;
IsFull = true;
Dimensions = new Cylinder { Height = 5D, Radius = 1.5D };
}
private ISolid Dimensions { get; set; }
public double Volume {
get {
return Dimensions.Volume;
}
}
}
If all of your objects volumes can be found by using the Lenth * Height * Thickness, then you probably don't need the interface. Interfaces are good when you might have a bunch of objects with the same behavior, but the behavior is performed different. For example the volume of a cylinder vs. the volume of a cube. It doesn't hurt to create an interface anyway, but in this case you might not need it. In terms of should you create a base class, or a class to encapsulate the common behavior and use composition, that depends on your Domain. The soda can could be a cylinder, or it could be a BeverageHolder. A box of wine could also be a beverage holder, and those are not both Cylinders, so you have to look at what else you might want to inherit from in your domain.