I derive multiple DTOs (data transfer object) from a base DTO. I have a property in base DTO (isUpdateAvailable) which is shared across all derived class. I have a method which is common for multiple use case that takes the base DTO and uses it either directly or by converting it to the respective derived DTO.
I think this is not a good c# code design. There should not be a need to convert. Moreover, I also heard that this kind of code design breaks some SOLID principle.
I have created a short sample code to describe my point. Please have a look:
public class UpdateNotification
{
public void ChromeNotification(MyBaseDto baseDto, NotificationType type)
{
OnUpdateAvailable(baseDto, type);
}
public void OutlookUpdateNotification(MyBaseDto baseDto,
NotificationType type)
{
OnUpdateAvailable(baseDto, type);
}
public void OnUpdateAvailable(MyBaseDto baseDto, NotificationType type)
{
if (type == NotificationType.Chrome)
{
// it uses baseDto.IsUpdateAvailable as well as it downcast it
to DerivedAdto and uses other properties
var derivedDto = baseDto as DerivedAdto;
}
if (type == NotificationType.Outlook)
{
// currently it just uses baseDto.IsUpdateAvailable
}
}
public enum NotificationType
{
Chrome,
Outlook
}
}
I am focussing here on the use of DTO objects which are "MyBaseDto", "DerivedAdto" and "DerivedBdto". My current structure of DTOs are as follows:
public abstract class MyBaseDto
{
public MyBaseDto(bool isUpdateAvailable)
{
IsUpdateAvailable = isUpdateAvailable;
}
public bool IsUpdateAvailable { get; }
}
public class DerivedAdto : MyBaseDto
{
public DerivedAdto(bool isUpdateAvailable)
: base(isUpdateAvailable)
{
}
public string PropertyA { get; set; }
}
public class DerivedBdto : MyBaseDto
{
public DerivedBdto(bool isUpdateAvailable)
: base(isUpdateAvailable)
{
}
}
Is there a better design for these DTO classes?
Can I design something like below or can you suggest a better approach?
public abstract class MyBaseDto
{
public abstract bool IsUpdateAvailable { get; set;}
}
public class DerivedAdto : MyBaseDto
{
public override bool IsUpdateAvailable { get; set;}
public string PropertyA { get; set; }
}
public class DerivedBdto : MyBaseDto
{
public override bool IsUpdateAvailable { get; set;}
}
Thanks a lot.