Can I eliminate duplicate code for below derived classes and move to abstract base class

how to remove duplicate block of code in java
c++ call base class method in derived object
c# refactor duplicate code
calling derived class function from base class
design pattern for code duplication
find duplicate code
duplicated blocks of code must be removed pojo
polymorphism

I have a abstract base class, starting a timer which is common to all derived class,

public abstract class BaseClass
{
    public virtual void Start() { _timer.Start(); }
}

Now I need to load different JSON configuration files for each derived class and create the file,

public class DerivedClass1 : BaseClass
{
    private readonly List<config> configs = new List<config>();

    public DerivedClass1()
    {
        configs = JsonSettings.GetConfigurations(@"./Configurations/1.json");
    }
    public override void Start()
    {
        base.Start();

        foreach (var configuration in configs)
        {
            JsonSettings.CreateConfigFile(configuration);
        }
    }
}

public class DerivedClass2 : BaseClass
{
    private readonly List<config> configs = new List<config>();

    public DerivedClass2()
    {
        configs = JsonSettings.GetConfigurations(@"./Configurations/2.json");
    }
    public override void Start()
    {
        base.Start();

        foreach (var configuration in configs)
        {
            JsonSettings.CreateConfigFile(configuration);
        }
    }
}

As I see there are lots of codes are duplicated in various derived class.

Can I move these piece of code as well as abstract base class or is there another way?

I think you could simplify your code to this:

public abstract class BaseClass
{
    protected virtual List<config> configs { get; set; } = new List<config>();
    public virtual void Start()
    {
        _timer.Start();
        foreach (var configuration in configs)
        {
            JsonSettings.CreateConfigFile(configuration);
        }
    }
}

public class DerivedClass1 : BaseClass
{
    public DerivedClass1()
    {
        configs = JsonSettings.GetConfigurations(@"./Configurations/1.json");
    }
}

public class DerivedClass2 : BaseClass
{
    public DerivedClass2()
    {
        configs = JsonSettings.GetConfigurations(@"./Configurations/2.json");
    }
}

How to remove duplicate code (in general)?, So I moved it here. Recently I found a good answer to my question in Uncle Bob's "Clean Code", which I want These are hardest to find, as no clone detector can find them. and within a set of classes the pulled-up method within the base class. I always imagine base classes as physically under the derived classes. The other class is called a superclass, or a base class. When you define a class that inherits from another class, the derived class implicitly gains all the members of the base class, except for its constructors and finalizers. The derived class can thereby reuse the code in the base class without having to re-implement it.

public interface BaseClass
{
    void Start();
}

public interface IBaseClassUtil
{
    void Start();
    void setConfigs(List<config> configs);
}

public class BaseClassUtil : IBaseClassUtil
{
    System.Timers.Timer _timer;
    public  List<config> _configs { get; set; } = new List<config>();
    public void Start()
    {
        _timer.Start();
        foreach (var configuration in _configs)
        {
            JsonSettings.CreateConfigFile(configuration);
        }
    }

    public void setConfigs(List<config> configs)
    {
        _configs = configs;
    }
}
public class DerivedClass1 : BaseClass
{
    private IBaseClassUtil _baseUtility;
    public DerivedClass1(IBaseClassUtil baseUtility)
    {
        _baseUtility = baseUtility;
        _baseUtility.setConfigs( JsonSettings.GetConfigurations(@"./Configurations/1.json"));
    }

    public void Start()
    {
        _baseUtility.Start();
    }
}

public class DerivedClass2 : BaseClass
{
    private IBaseClassUtil _baseUtility;
    public DerivedClass2(IBaseClassUtil baseUtility)
    {
        _baseUtility = baseUtility;
        _baseUtility.setConfigs(JsonSettings.GetConfigurations(@"./Configurations/2.json"));
    }

    public void Start()
    {
        _baseUtility.Start();
    }
}

This might be oveer engineered. Or might not suit ur current requirement. Advantages would be

  1. In future if you want u want to have different implementation for IBaseClassUtil it will be easier

    1. And huge advantage would be this code is testable

Inheritance, When my base class's constructor calls a virtual function on its this object, why doesn't my in the derived classes, and the little pieces of common code can be written once (to avoid code duplication) and stashed somewhere (anywhere!) There are at least two good reasons to use protected virtuals (see below), but just​  Basically, I have code which defines a single abstract class which has many derived classes. I would like to declare one of each derived class and put them all into a set, but I don't want to have to write out numerous lines of code to do this. What I currently have is similar to the following: 1. 2.

If the classes differ by nothing but the configuration path, then you can have only one derived class that takes the path as a parameter in its ctor.

public DerivedClass(string configurationPath)
{
    configs = JsonSettings.GetConfigurations(configurationPath);
}

Put please note that a decision on including inheritance in your architecture is not about code duplication, and by not giving us any information on the functions or even names of the classes (BaseClass and DerivedClass mean nothing. What do they represent? What's their function? Why are they related?) you give us no way of really helping you with your design.

Inheritance, In C++, abstract classes often serve as interfaces and a class can have many helps you avoid situations where you need to inherit data or code along two paths, If both answers are “yes,” multiple inheritance is probably the best way to go. derived classes below both the hierarchy of geographies and the hierarchy of  e. virtual void print ( ostream& out); and void print( ostream& out); True. If a base class has a public member function, and the derived class has a member function with the same name, but with a different parameter list, this function is said to be. a) overloaded. When deriving a class, you should.

Three Reasons Why We Should Not Use Inheritance In Our Tests, Building objects used in our tests creates duplicates code. So we get to work and remove the duplicate code by creating a base class (or classes) which a two abstract classes which ensure that we will not violate this principle. It was possible to move some code into utility classes but when it comes to  Adding complexity to remove duplicate code. I have several classes that all inherit from a generic base class. The base class contains a collection of several objects of type T. Each child class needs to be able to calculate interpolated values from the collection of objects, but since the child classes use different types, the calculation varies a tiny bit from class to class.

Inheritance and Composition: A Python OOP Guide – Real Python, Basic inheritance between Base and Derived classes Composition enables you to reuse code by adding objects to other objects, as opposed to Every class that you create in Python will implicitly derive from object . library provides functionality to prevent creating objects from abstract base classes. If we were to move this code to the derived classes then we would end up with this duplicated code in both of the derived classes. Now we will move this code to both of the classes. And in the base class we remove the constructor and make the property abstract. And we need to override the property in the derived classes using the following code.

Virtual base class in C++, Virtual base classes are used in virtual inheritance in a way of preventing multiple class are inherited into another in a new class D as shown in figure below. As we can see from the figure that data members/function of class A are inherited virtual base, it can act as an indirect base more than once without duplication of  Although an instance of an abstract class cannot be created directly, it is a very good place to implement default behaviors (the interface) for the derived classes to eliminate duplicate codes

Comments
  • What does your BaseClass and derived classes represent? What are their function?
  • The best practice would be having a separate utility class implementation, which will have these duplicate code. And inject that class into your new classes via dependency injection. "Favor Composition over Inheritance"
  • I'm not putting full code, but what is missing?
  • @Naruto, could you please give some example?
  • sure! give me a minute!