I have the following set of Interfaces and Classes.
public interface IValidatableObject
{
List<string> ValidationErrors { get; }
bool Validate();
}
public class ValidatableObject : IValidatableObject
{
public List<string>ValidationErrors { get; }
public bool Validate()
{
//dostuff
}
}
public interface IDeviceDataObject
{
int Id { get; set; }
string Name { get; set; }
}
public class DeviceDataObject : ValidatableObject, IDeviceDataObject
{
public int Id { get; set; }
public string Name { get; set; }
}
public class DeviceService
{
public bool ValidateDevice(IDeviceDataObject device)
{
return device.Validate(); // This throws a compiler error
}
}
The problem in the service operation ValidateDevice above is that the compiler can’t resolve device.Validate() because IDeviceDataObject does not implement the IValidatableObject interface.
My question is, is it then correct to change IValidatableObject to implement IValidatableObject. I’m a little uncertain as to whether this is good practice because the way I kind of see it, DeviceDataObject is implementing IValidatableObject twice – once through ValidatableObject and once through IDeviceDataObject. Can anyone help clear this up for me?
public interface IDeviceDataObject : IValidatableObject
{
int Id { get; set; }
string Name { get; set; }
}
I may understand something wrong here (and I dont know your class architecture as a whole), but why doesn’t your ValidateDevice method just take validatable objects? The signature would look like:
Isnt that what expresses the functionality of a method that does validation: it takes something that is validatable. Everything else could stay the way it is (i.e. dont let
IDeviceDataObjectinherit fromIValidatableObject, as you may want to express that not every devicedataobject is also validatable for example)A second way, if you want to make sure that
ValidateDeviceonly takes objects implementingIDeviceDataObject, you could also try to cross-cast toIValidatableObject: