I have the same code in method Output()
in both classes Hour
and Day
.
Is there way to avoid it to change code in one place instead of two?
class Program
{
static void Main(string[] args)
{
Hour hour = new Hour("20150715 080000");
Day day = new Day(hour);
Console.WriteLine(String.Format("Hour: {0}", hour.Output()));
Console.WriteLine(String.Format("Day: {0}", day.Output()));
}
}
public interface IMoment
{
string OutputMoment();
}
class Hour : IMoment
{
public string Date;
public string Time;
public Hour (string s)
{
string[] parts = s.Split(';');
this.Date = parts[0];
this.Time = parts[1];
}
public string Output()
{
return Date + " " + Time;
}
}
class Day : IMoment
{
public string Date;
public string Time;
public Day(Hour hour)
{
this.Date = hour.Date;
this.Time = hour.Time;
}
public string Output()
{
return Date + " " + Time;
}
}
Don't make the mistake of creating a base class to share that method. That's a common misuse of inheritance. This technique breaks down in general and you introduce a meaningless class into the public interface of your class. Inheritance is not for code sharing. It's for "Liskov substitution".
Instead, create a static helper method, that takes both values as arguments and computes the result. This allows you to implement the formatting once. This is very easy to implement, works almost always and does not impact the public API of your classes. Don't fear the slightly larger syntax footprint. That's not a significant problem (most of the time).