Question

I have a project in which one module keeps the state of the target device (things like current command level, but mostly status registers caches).

I'm aware that having a global public variable (Singleton pattern) is considered a very bad practice, and I understand why.

Instead, my approach is to use an opaque pointer (to a struct), allocate a single (static) instance of such struct in the *.c file (so it's not public) and provide it through a Handle GetHandle(void) function.

The above strategy is basically use the adaptor pattern, I still have a single instance. I have read that this is an anti-pattern as well.

Is there any better why to design this module?

Note: notice that in this project I can't use dynamic memory, so malloc etc. are forbidden

Était-ce utile?

La solution

It appears you have slightly misunderstood the articles about global state being an anti-pattern.

You file-scope variable is not what those articles consider to be "global state" anti-pattern. The global state that those articles warn about are variables that are accessible throughout the whole application and that can be written to by any part of the code without going through a common function that can apply a sanity check.

So, the fact that you use an opaque pointer and setter functions to change the stored state means that you have already applied the correct pattern to avoid the "global state" anti-pattern.

Having a single instance isn't a problem if two conditions are true

  • it reflects the current requirements for the project (i.e., only a single target device needs to be supported now)
  • it does not pervade your designs to the extent that it effectively becomes impossible to support multiple instances (i.e. multiple target devices) later on if the need arises. It is acceptable to have to do some rework, for example to identify which device you want to access the settings for, but it isn't good if you have to rewrite large portions of otherwise unrelated software just to support multiple devices.

    I get the feeling that your current design is already flexible enough in this regard.

Licencié sous: CC-BY-SA avec attribution
scroll top