I have the following code
internal abstract class Base
{
public DateTime Time;
public string Message;
public string Log;
public abstract void Invoke(string message);
}
internal class SubA : Base
{
public override void Invoke(string message)
{
Time = DateTime.Now;
// Do A
}
}
internal class SubB : Base
{
public override void Invoke(string message)
{
Time = DateTime.Now;
// Do B
}
}
I have these SubA and SubB classes which inherits from Base class, you can see that i have a code that repeating it self which is setting the Time, is there a way to move the setting of the time to the base class?
Don't Repeat Yourself (DRY): Using DRY or Do not Repeat Yourself principle, you make sure that you stay away from duplicate code as often as you can. Rather you replace the duplicate code with abstractions or use data normalization. To reduce duplicity in a function, one can use loops and trees.
By using the virtual keyword, duplication of data due to inheritance can be avoided. In the above example, only one copy of inheritable data in a is inherited by d(from b &c)/as opposed to the 2 copies that would have been inherited without the use of the virtual keyword.
Having to change the same code multiple times harms your cycle time. If you have to apply a change in multiple places, then implementing that change will take longer. If the duplication is pervasive enough, it'll lead to a decreased delivery speed.
Abstractions Don't Solve Duplication We as engineers have learned how to use abstraction to solve duplication problems. However this doesn't mean that every such problem requires an abstraction. We design one based on the current state of the code but that may be misleading.
You could do something like this:
internal abstract class Base
{
public DateTime Time;
public string Message;
public string Log;
public void Invoke(string message){
Time = DateTime.Now;
this.InvokeInternal(message);
}
protected abstract void InvokeInternal(string message);
}
internal class SubA : Base
{
protected override void InvokeInternal(string message)
{
// Do A
}
}
internal class SubB : Base
{
protected override void InvokeInternal(string message)
{
// Do B
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With