none
Base Class Method reuse with different client. RRS feed

  • Question

  • I have a base class and 3 client inherit from base and all of them will use a same method with tiny logic change.

    Should I implement this method in 3 client class or Can I use if else in base class?

    public class BaseClass { protected string className; public BaseClass() { className = "Base";

    } private void ReuseMethod() { commonLogic1(); if (className.Equal("A") commonLogic2(); commonLogic3(); if (className.Equal("B") commonLogic4(); commonLogic5(); if (className.Equal("C") commonLogic6(); } } public class ClassA : BaseClass { public ClassA() : Base() { className = "A"; } } public class ClassB : BaseClass { public ClassB () : Base() { className = "B"; } } public class ClassC : BaseClass { public ClassC () : Base() { className = "C"; } }






    • Edited by Joshft Sunday, January 19, 2020 7:23 AM
    Sunday, January 19, 2020 7:17 AM

Answers

  • No, don't use if-else in the base class. This breaks the structure of the classes; the base class should have no knowledge about which classes are inheriting from it.

    Instead, write a method in the base class that contains all the common logic. For the parts that are not common, extract them away from the main method into a separate protected method, and mark it as virtual (or abstract). Then, in each child class, do an override of this virtual method to change its behavior in that class.

    So, basically, your example would look like this:

    public abstract class BaseClass
    {
        private void ReuseMethod()
        {
             commonLogicBegin();
             commonLogicDifferent();
             commonLogicEnd();
        }
        protected abstract void CommonLogicDifferent();
    }
    public class ClassA : BaseClass
    {
        protected override CommonLogicDifferent()
        {
            // Specific logic for ClassA
        }
    }
    public class ClassB : BaseClass
    {
        protected override CommonLogicDifferent()
        {
            // Specific logic for ClassB
        }
    }
    public class ClassC : BaseClass
    {
        protected override CommonLogicDifferent()
        {
            // Specific logic for ClassC
        }
    }
    


    Sunday, January 19, 2020 8:34 AM
    Moderator