Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

non-static member function update static data [closed]

Tags:

c++

oop

static

Obviously non-static member function can read static data. In fact, that's an important point of having static data - so that instance member functions can read it.

But, is there a good reason (from a OOP design point of view) of having non-static member functions UPDATE the static data variable?

I know of the trivial example of how one might want to keep a counter of how many instances we've created of a particular object. So we can have the constructor update a static int counter. Like so

class Foo
{
    static int ctr;

    Foo()
    {
        ctr++;
    }
}

But other than this specific example, is there a good general reason of having non-static function update static variables?

Personally I think it seems a bit goofy, but I can't put my finger on what exactly is bothering me.

like image 771
user3240688 Avatar asked Apr 29 '26 01:04

user3240688


1 Answers

Sort of. You may have workers who are supposed to throw out tasks if they are duplicated, and you may do this by having a static set of in-process tasks to check against.

The problem with this sort of static use is it means you can only have one such class per... program. And what if the owner of the larger program wants to run this class twice? Oops. Or, what if another part of your program decides it really could use this task management system for something else? Oops. Any small program can become part of a large program to conserve threads and other resources (I'm especially used to a Java context where the JVM itself is very expensive).

So when you feel like you have a need for this pattern, try having an umbrella class to own the candidate static data as non-static data, and have one umbrella class instance for many sub instances. e.g.

class Worker {
    static set<WorkItem*> inProcess; // the old way of doing it
    void work(WorkItem* w) {
        inProcess.add(w);
}

Should become

class Worker {
    Manager* manager; // shared between all instances, until your program grows
    void work(WorkItem* w) {
        manager->accept(w);
    }
}

class Manager {
    set<WorkItem> inProcess;
    void accept(WorkItem* w) {
        inProcess.add(w);
    }
}

This problem applies to any static, non-constant data. But the problem becomes successively riskier as the data goes from read-only to read-write. Singleton is an anti-pattern.

like image 148
djechlin Avatar answered May 01 '26 15:05

djechlin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!