My class has 3 properties that have to do the same thing in the custom set
that I made.
Now I have this repeated in all 3, which isn't DRY.
How do I make this DRY? Just put the foreach
into a method? I feel like there must be a more elegant way.
(also I wish I didn't need the private backing fields because they are kind of an eye-sore)
private List<string> _ImageTypes;
public List<string> ImageTypes
{
get { return _ImageTypes; }
set
{
_ImageTypes = new List<string>();
foreach (var type in value)
if (!string.IsNullOrEmpty(type))
_ImageTypes.Add("." + type.Replace(".", "").Replace("*", ""));
}
}
private List<string> _AnimationTypes;
public List<string> AnimationTypes
{
get { return _AnimationTypes; }
set
{
_AnimationTypes = new List<string>();
foreach (var type in value)
if (!string.IsNullOrEmpty(type))
_AnimationTypes.Add("." + type.Replace(".", "").Replace("*", ""));
}
}
private List<string> _VideoTypes;
public List<string> VideoTypes
{
get { return _VideoTypes; }
set
{
_VideoTypes = new List<string>();
foreach (var type in value)
if (!string.IsNullOrEmpty(type))
_VideoTypes.Add("." + type.Replace(".", "").Replace("*", ""));
}
}
Yes, put it in the method
private List<string> CreateListFrom(List<string> list)
{
return list.Where(type => !string.IsNullOrEmpty(type))
.Select(type => type.Replace(".", "").Replace("*", ""))
.Select(type => $".{type}")
.ToList();
}
Then use it in the setters
private List<string> _ImageTypes;
public List<string> ImageTypes
{
get { return _ImageTypes; }
set
{
_ImageTypes = CreateListFrom(value);
}
}
Another approach - do it in the constructor, then you can get rid of private members. But this will depend on how this class is consumed
Before talking about DRY - you should be sure that similar looking code are going to be changed for same reasons.