Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract class, how to avoid code duplication?

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?

like image 639
user829174 Avatar asked Feb 16 '12 10:02

user829174


People also ask

How do you avoid code duplication?

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.

How does inheritance avoid duplication Java?

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.

Why do we avoid code duplication?

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.

Does abstraction avoid code duplication?

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.


1 Answers

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
    }
}
like image 144
Klaus Byskov Pedersen Avatar answered Oct 15 '22 07:10

Klaus Byskov Pedersen