Search code examples
c++c++11static-methodsnon-static

Why is accessing a non static method from static method is Bad design


I am accessing non static method from static Method. Below is the code. I read its bad design source. Why this bad design please help me to understand. If so how can one achieve it.

#include<iostream>

class Base 
{
public :
    static Base* initialiser;
    void BaseMethod() 
    {
        std::cout<<"Non static method Invoked"<<std::endl;
    }

    static  Base* GetInstance() 
    {
        if (!initialiser)
            initialiser = new Base();

        return initialiser;
    }
};

Base* Base::initialiser = nullptr;

class Service 
{
public: 
    void ServiceMethod()
    {
        Base::GetInstance()->BaseMethod();
    }
};

int main()
{
     Service obj;
     obj.ServiceMethod();
}

Solution

  • Why is accessing a non static method from static method is Bad design

    It is not per se, as you are actually using a static member from a static methods

    Yet this code snipped is too damn rigid, too damn over-engineered. Which means more likely to be buggy, to be a mess once a new requirement come into play.

    • defect : This code isn't thread safe. You should instantiate initializer not in GetInstance,rather using Base* Base::initialiser{new Base()};, which is guaranteed to be thread-safe from c++11.
    • defect : A class such like this should be derived with extreme caution. Or add final to prevent this possibility.
    • design : This code has still zero line of functionality. You are still plumbing. You want to reconsider if this is the best design for the problem being solved.
    • design : The purpose is to provide a singleton. We dev like to enforce unnecessary constraints such as uniqueness. When the time comes to support two instances in a system designed for a singleton, we have to refactor a whole lot of things.