global variables for "things" that are global and "single"? - c++

When dealing with microcontrollers there are things that are inherently global - I'm thinking about peripherals like serial ports or other interfaces. There are also peripherals that are not only global but there is only one (and there will never be more) - like peripheral controlling core clocks or interrupt controller. These peripherals do have some kind of global state (for example - core clock is set to something) and it's inefficient to reverse-calculate these values.
If I'd like my program to be nicely object-oriented, I'm having hard time deciding how to deal with such objects... Global variables are not nice and this is obvious, but I just don't know (not enough experience) whether I should try to "hide" the fact that these things ARE global... For example "cin" or "stdout" are globals too (let's ignore the fact that in multithreaded apps these are usually thread-specific) and noone is hiding that... Let's stick with the clock generator peripheral - there is only one, so I could use the singleton anti-pattern (; or make the class static or just have the single object global (that's what I have usually done), as this object has the current clock setting stored and this value is needed for LOTS of other things - it's needed to set system timer used by RTOS, it's needed to set clocks for other peripherals (UART baudrate, SPI bitrate, ...), it's needed to set correct clock for external memories or configure memory wait states. That's why I think that creating one object in main() and passing it around everywhere would be a bit cumbersome...
I could write the methods so that all "global" information would come from the peripheral registers (for example the core frequency could be reverse-calculated from current PLL settings), but this also seems like a wrong idea, not to mention that creating object for clock generator peripheral everywhere would look funny...
Current clock setting could be stored in static member of the class, but from here there's only one small step towards a fully static class (as "this" pointer will be useless for a class that has no state)...
The solution usually found in not-object-oriented programs is closest to fully static class - there are only functions that operate on global variables.
Anyone has some nice idea how to deal with such scenario nicely or whether this problem is worth the time? Maybe I should just use one global object and be done with it? (;

If I'd like my program to be nicely object-oriented, I'm having hard time deciding how to deal with such objects... Global variables are not nice and this is obvious, but I just don't know (not enough experience) whether I should try to "hide" the fact that these things ARE global...
When I read that, I wonder if you know why you are using OOP and why you don't use globals.
Firstly, OOP is a tool, not a goal. In your case, the interrupt controller doesn't need things like derivation and virtual functions. All you will need is an interface to program it, wrapped in a single class. You could even use a set of plain functions that do that (C=style modular programming) without giving up on maintainability. In your case, making the single instance global is even clearer. Imagine the alternative, where different parts of the program could instantiate a class that is used to access the same UART underneath. If you're using globals, the code (or rather the author) is aware of this and will think about how to coordinate access.
Now, concerning the globals, here's an example why not to use them:
int a, b, c;
void f1()
{
c = a;
f3();
}
void f2()
{
c = b;
f3();
}
void f3()
{
// use c
}
int main()
{
a = 4;
f1();
b = 5;
f2();
}
The point here is that parameters are stored in globals instead of passing them around as actual parameters and making it difficult to see where and when they are used. Also, the use above totally rules out any recursive calls. Concerning your environment, there are things that are inherently global though, because they are unique parts of the environment, like the interrupt controller (similar to cin/cout/cerr/clog). Don't worry about those. There have to be really many of them used all over the place until you need to think about restricting access.
There are two guidelines to make this easier:
The larger the scope of an object, the more it needs a speaking name (compare to a, b, c above). In your case, I'd store all hardware-specific objects in a common namespace, so it is obvious that some code is accessing globals. This also allows separate testing and reuse of this namespace. Many hardware vendors even provide something like this in the form of a library, in order to help application development.
In the code wrapping/modelling the hardware, perform requests but don't make decisions that are specific to the application on top of it. Compare to e.g. the standard streams, that are provided but never used by the standard library itself, except maybe for dumping fatal error information before aborting after a failed assertion.

You have pretty much outlined your options:
globals
static data members of classes / singletons
It's ultimately up to you to decide between the two, and choose which you like more from the aesthetic or other prospective.
At the end of the day, just as you have said, you'll still have one clock generator, one UART, etc.
One thing to keep in mind is that too much abstraction solely for the purpose of abstraction isn't going to buy you much if anything. What it may do, however, is make it harder for someone unfamiliar to your code figure out how things really work behind the layers of classes. So, take into account your team, if any.

The Singleton pattern is a source of debate, for sure. Some people simply say it's "bad", but I would disagree; it is just widely misused and misunderstood. It is definitely useful in certain situations. In fact, it applies to exactly the situation you've described.
If you have a class that needs to be available globally and by its very nature cannot have multiple instances, then a singleton is the best option.

Singletons, global objects, static classes, they are all the same. Dress the evil global state in whatever sauce you want, it's still global state. The problem is in the salad, not in the dressing, so to speak.
A little-explored path is monadic code, Haskell-style (yes in C++). I have never tried it myself, but from the looks of it, this option should be fun. See e.g. here for an example implementation of Monad interface in C++.

Related

How to make an old C codebase with many globals reentrant

I'm working with a large, old C codebase (an interpreter) that uses global variables a great deal, with the result that I cannot have two instances of it at once. Is there a straightforward (ideally automated) approach to convert this code to something reentrant? i.e. some refactor tool that would make all globals part of a struct and prepend the pointer to all variables?
Could I convert to C++ and wrap the entire thing in a class definition?
I would recommend to convert your project into C++11 project and change all your static vars into threadlocal.
This can be up to several days of work depending on the size of your project. In certain cases this will work.
I'm not aware of any "ready made" solution for this type of problem.
As a general rule, global variables are going to make it hard to make the code reentrant.
If you can remove all the global variables [simply delete the globals and see where you get compiler errors]. Replace the globals with a structure, and then use a structure per instance that is passed along, you'd be pretty much done (as long as the state of the interpreter instances is independent, and the instances don't need to know about each other). [Of course, you may need to have more than a single structure to solve the problem, but your global variables should be possible to "stick in a structure"].
Of course, making the structure and the code go together as a C++ class (which may have smaller classes as part of the solution) would be the "next step", but it's not entirely straight forward to do this, if you are not familiar with C++ and class designs.
Are you trying to make it reentrant in order to be able to make it multi-thread, and divide the work between threads?
If so, I would consider making it multi process, instead of multy-thread,
What I usually do with interpreters is go straight to a class with instance vars rather than globals. Not sure what you are interpreting, but it could be possible to pass in a file path or string container that the class interprets with an internal thread, so encapsulating the entire interpretation run.
It is possible to wrap the whole thing in a class definition, but it will not work for code that takes addresses of functions and passes them to C code. Also, converting a large legacy code base to be compilable by a C++ compiler is tedious enough that it probably outweighs the effort of removing the global variables by hand.
Barring that one, you have two options:
Since you need reentrancy to implement threading, it might be easiest to declare all global variables thread-local. If you have a C compiler that supports thread-locals, this is typically as easy as slapping a __thread (or other compiler-specific keyword) before every declaration. Then you create a new interpreter simply by creating a new thread and initializing the interpreter in the normal way.
If you cannot use __thread or equivalent, then you have to do a bit more footwork. You need to place all global variables in a structure, and replace every access to global variable foo with get_ctx()->foo. This is tedious, but straightforward. Once you are done, get_ctx() can allocate and return a thread-local interpreter state, using an API of your choosing.
A program transformation tool that can handle the C language would be able to automate such changes.
It needs to be able to resolve each symbol to its declaration, and preprocessor conditionals are likely to be trouble. I'd name one, but SO zealots object when I do that.
Your solution of a struct containing the globals is the right idea; you need rewrite that replaces each global declaration with a slot member, and each access to a global with access to the corresponding struct member.
The remaining question is, where does the struct pointer come from? One answer is a global variable that is multiplexed when threads are switched; a better answer if available under your OS is the get the struct pointer from thread local variables.

Use of global variables in simulation code [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Are global variables bad?
I am writing a simulation code making use of material and energy specific data. This data is stored in global arrays, because once uploaded, they are used during the simulation and should be accessible by most of the functions.
I read everywhere that it is not good practice to use global variables.
Could someone explain me or point me to material on the web explaining how I could avoid using global arrays in simulation application coding while massive data arrays need to be used. I try to code in C++ and make use as much as possible of object oriented features.
Thanks in advance for your help.
You are right about the fact that, using globals are not recommended. You can declare those unrelated golbals inside a namespace,
//Globals.h
namespace Globals
{
extern int a[100];
extern double d;
}
and define them in a .cpp file.
//Globals.cpp
int Globals::a[100] = { ... };
double Globals::d = 3.14;
Now use them as Globals::a, Globals::d etc. My answer is in code management perspective.
Yes you are right, global variables are not good.
This is a useful link which explains why global variables are bad and how to avoid them.
http://c2.com/cgi/wiki?GlobalVariablesAreBad
EDIT:
#sergio's post also points to the same link, you can ignore this answer
Could someone explain me or point me to material on the web explaining how I could avoid using global arrays in simulation application coding while massive data arrays need to be used.
The same way you avoid globals in general: by using locals instead. The natural way to get data into a function is to pass it as a parameter. This is not expensive, especially if you pass by reference where appropriate.
Have a look at this article about global variables. This is an excerpt:
Why Global Variables Should Be Avoided When Unnecessary
Non-locality -- Source code is easiest to understand when the scope of its individual elements are limited. Global variables can be read or modified by any part of the program, making it difficult to remember or reason about every possible use.
No Access Control or Constraint Checking -- A global variable can be get or set by any part of the program, and any rules regarding its use can be easily broken or forgotten. (In other words, get/set accessors are generally preferable over direct data access, and this is even more so for global data.) By extension, the lack of access control greatly hinders achieving security in situations where you may wish to run untrusted code (such as working with 3rd party plugins).
Implicit coupling -- A program with many global variables often has tight couplings between some of those variables, and couplings between variables and functions. Grouping coupled items into cohesive units usually leads to better programs.
Concurrency issues -- if globals can be accessed by multiple threads of execution, synchronization is necessary (and too-often neglected). When dynamically linking modules with globals, the composed system might not be thread-safe even if the two independent modules tested in dozens of different contexts were safe.
Namespace pollution -- Global names are available everywhere. You may unknowingly end up using a global when you think you are using a local (by misspelling or forgetting to declare the local) or vice versa. Also, if you ever have to link together modules that have the same global variable names, if you are lucky, you will get linking errors. If you are unlucky, the linker will simply treat all uses of the same name as the same object.
Memory allocation issues -- Some environments have memory allocation schemes that make allocation of globals tricky. This is especially true in languages where "constructors" have side-effects other than allocation (because, in that case, you can express unsafe situations where two globals mutually depend on one another). Also, when dynamically linking modules, it can be unclear whether different libraries have their own instances of globals or whether the globals are shared.
Testing and Confinement - source that utilizes globals is somewhat more difficult to test because one cannot readily set up a 'clean' environment between runs. More generally, source that utilizes global services of any sort (e.g. reading and writing files or databases) that aren't explicitly provided to that source is difficult to test for the same reason. For communicating systems, the ability to test system invariants may require running more than one 'copy' of a system simultaneously, which is greatly hindered by any use of shared services - including global memory - that are not provided for sharing as part of the test.
It also discusses several alternatives. Possibly in your case, you could consider:
hiding your globals (e.g., private static variables);
stateful procedures: setter and getter functions allowing access to the arrays while also "masking" it;
the singleton pattern.
EDIT:
I understand that a part of the development community are against the use of the singleton pattern. I fully respect this opinion. Anyway, in the context of the present discussion, the singleton offers several advantages over the raw use of globals:
improved access control;
opportunity for synchronization;
ability to abstract away the implementation.
In this respect, it is not better from a setter/getter set of functions, but still, not worse. I leave to the OP the hard task of choosing what to do with his own code. (BTW, the article discusses more approaches, like Context Objects, DependencyInjection, etc).
Introducing global state into your code can make it difficult to do things in a multi-threaded way.
I would also argue it can make the intent of your code more difficult to follow. If you pass all of the arguments to a function as parameters at least it's clear what data the function has access to, and what has the potential of changing. The use of global variables doesn't give someone reading the code this chance...
It's also not generally true that using global variables is in any way faster. If you have large objects that you need to pass to functions, pass these arguments via references and there won't be any issues with copying.
Without knowing more about your setup, it's difficult to make any recommendations, but if you have a large amount of data that needs to be passed around to a series of routines I would be tempted to put it all in a struct, and to pass that struct by reference:
struct my_data_type
{
double some_data;
double some_other_data;
std::vector<double> some_coefficients;
std::vector<double> some_other_coefficients;
std::string some_name;
std::string some_other_name;
// add more members as necessary...
};
void foo(my_data_type &data)
{
// there's no big overhead passing data by reference
}
If you only need to access the data in a read-only fashion, it's best to pass as a const reference:
void foo(my_data_type const&data)
{
// again, efficient, but ensures that data can't be modified
}
EDIT: In answer to your comment, I'm not talking about a "global" structure. You would need to declare a local struct variable, read the data from your file into the struct and then pass it by reference to any functions that need to be called:
int main()
{
// a local struct to encapsulate the file data
my_data_type file_data;
// read the data from your file into file_data
// the struct containing the data is passed by reference
foo(file_data);
return 0;
}

Single-use class

In a project I am working on, we have several "disposable" classes. What I mean by disposable is that they are a class where you call some methods to set up the info, and you call what equates to a doit function. You doit once and throw them away. If you want to doit again, you have to create another instance of the class. The reason they're not reduced to single functions is that they must store state for after they doit for the user to get information about what happened and it seems to be not very clean to return a bunch of things through reference parameters. It's not a singleton but not a normal class either.
Is this a bad way to do things? Is there a better design pattern for this sort of thing? Or should I just give in and make the user pass in a boatload of reference parameters to return a bunch of things through?
What you describe is not a class (state + methods to alter it), but an algorithm (map input data to output data):
result_t do_it(parameters_t);
Why do you think you need a class for that?
Sounds like your class is basically a parameter block in a thin disguise.
There's nothing wrong with that IMO, and it's certainly better than a function with so many parameters it's hard to keep track of which is which.
It can also be a good idea when there's a lot of input parameters - several setup methods can set up a few of those at a time, so that the names of the setup functions give more clue as to which parameter is which. Also, you can cover different ways of setting up the same parameters using alternative setter functions - either overloads or with different names. You might even use a simple state-machine or flag system to ensure the correct setups are done.
However, it should really be possible to recycle your instances without having to delete and recreate. A "reset" method, perhaps.
As Konrad suggests, this is perhaps misleading. The reset method shouldn't be seen as a replacement for the constructor - it's the constructors job to put the object into a self-consistent initialised state, not the reset methods. Object should be self-consistent at all times.
Unless there's a reason for making cumulative-running-total-style do-it calls, the caller should never have to call reset explicitly - it should be built into the do-it call as the first step.
I still decided, on reflection, to strike that out - not so much because of Jalfs comment, but because of the hairs I had to split to argue the point ;-) - Basically, I figure I almost always have a reset method for this style of class, partly because my "tools" usually have multiple related kinds of "do it" (e.g. "insert", "search" and "delete" for a tree tool), and shared mode. The mode is just some input fields, in parameter block terms, but that doesn't mean I want to keep re-initializing. But just because this pattern happens a lot for me, doesn't mean it should be a point of principle.
I even have a name for these things (not limited to the single-operation case) - "tool" classes. A "tree_searching_tool" will be a class that searches (but doesn't contain) a tree, for example, though in practice I'd have a "tree_tool" that implements several tree-related operations.
Basically, even parameter blocks in C should ideally provide a kind of abstraction that gives it some order beyond being just a bunch of parameters. "Tool" is a (vague) abstraction. Classes are a major means of handling abstraction in C++.
I have used a similar design and wondered about this too. A fictive simplified example could look like this:
FileDownloader downloader(url);
downloader.download();
downloader.result(); // get the path to the downloaded file
To make it reusable I store it in a boost::scoped_ptr:
boost::scoped_ptr<FileDownloader> downloader;
// Download first file
downloader.reset(new FileDownloader(url1));
downloader->download();
// Download second file
downloader.reset(new FileDownloader(url2));
downloader->download();
To answer your question: I think it's ok. I have not found any problems with this design.
As far as I can tell you are describing a class that represents an algorithm. You configure the algorithm, then you run the algorithm and then you get the result of the algorithm. I see nothing wrong with putting those steps together in a class if the alternative is a function that takes 7 configuration parameters and 5 output references.
This structuring of code also has the advantage that you can split your algorithm into several steps and put them in separate private member functions. You can do that without a class too, but that can lead to the sub-functions having many parameters if the algorithm has a lot of state. In a class you can conveniently represent that state through member variables.
One thing you might want to look out for is that structuring your code like this could easily tempt you to use inheritance to share code among similar algorithms. If algorithm A defines a private helper function that algorithm B needs, it's easy to make that member function protected and then access that helper function by having class B derive from class A. It could also feel natural to define a third class C that contains the common code and then have A and B derive from C. As a rule of thumb, inheritance used only to share code in non-virtual methods is not the best way - it's inflexible, you end up having to take on the data members of the super class and you break the encapsulation of the super class. As a rule of thumb for that situation, prefer factoring the common code out of both classes without using inheritance. You can factor that code into a non-member function or you might factor it into a utility class that you then use without deriving from it.
YMMV - what is best depends on the specific situation. Factoring code into a common super class is the basis for the template method pattern, so when using virtual methods inheritance might be what you want.
Nothing especially wrong with the concept. You should try to set it up so that the objects in question can generally be auto-allocated vs having to be newed -- significant performance savings in most cases. And you probably shouldn't use the technique for highly performance-sensitive code unless you know your compiler generates it efficiently.
I disagree that the class you're describing "is not a normal class". It has state and it has behavior. You've pointed out that it has a relatively short lifespan, but that doesn't make it any less of a class.
Short-lived classes vs. functions with out-params:
I agree that your short-lived classes are probably a little more intuitive and easier to maintain than a function which takes many out-params (or 1 complex out-param). However, I suspect a function will perform slightly better, because you won't be taking the time to instantiate a new short-lived object. If it's a simple class, that performance difference is probably negligible. However, if you're talking about an extremely performance-intensive environment, it might be a consideration for you.
Short-lived classes: creating new vs. re-using instances:
There's plenty of examples where instances of classes are re-used: thread-pools, DB-connection pools (probably darn near any software construct ending in 'pool' :). In my experience, they seem to be used when instantiating the object is an expensive operation. Your small, short-lived classes don't sound like they're expensive to instantiate, so I wouldn't bother trying to re-use them. You may find that whatever pooling mechanism you implement, actually costs MORE (performance-wise) than simply instantiating new objects whenever needed.

How to deal with the idea of "many small functions" for classes, without passing lots of parameters?

Over time I have come to appreciate the mindset of many small functions ,and I really do like it a lot, but I'm having a hard time losing my shyness to apply it to classes, especially ones with more than a handful of nonpublic member variables.
Every additional helper function clutters up the interface, since often the code is class specific and I can't just use some generic piece of code.
(To my limited knowledge, anyway, still a beginner, don't know every library out there, etc.)
So in extreme cases, I usually create a helper class which becomes the friend of the class that needs to be operated on, so it has access to all the nonpublic guts.
An alternative are free functions that need parameters, but even though premature optimization is evil, and I haven't actually profiled or disassembled it...
I still DREAD the mere thought of passing all the stuff I need sometimes, even just as reference, even though that should be a simple address per argument.
Is all this a matter of preference, or is there a widely used way of dealing with that kind of stuff?
I know that trying to force stuff into patterns is a kind of anti pattern, but I am concerned about code sharing and standards, and I want to get stuff at least fairly non painful for other people to read.
So, how do you guys deal with that?
Edit:
Some examples that motivated me to ask this question:
About the free functions:
DeadMG was confused about making free functions work...without arguments.
My issue with those functions is that unlike member functions, free functions only know about data, if you give it to them, unless global variables and the like are used.
Sometimes, however, I have a huge, complicated procedure I want to break down for readability and understandings sake, but there are so many different variables which get used all over the place that passing all the data to free functions, which are agnostic to every bit of member data, looks simply nightmarish.
Click for an example
That is a snippet of a function that converts data into a format that my mesh class accepts.
It would take all of those parameter to refactor this into a "finalizeMesh" function, for example.
At this point it's a part of a huge computer mesh data function, and bits of dimension info and sizes and scaling info is used all over the place, interwoven.
That's what I mean with "free functions need too many parameters sometimes".
I think it shows bad style, and not necessarily a symptom of being irrational per se, I hope :P.
I'll try to clear things up more along the way, if necessary.
Every additional helper function clutters up the interface
A private helper function doesn't.
I usually create a helper class which becomes the friend of the class that needs to be operated on
Don't do this unless it's absolutely unavoidable. You might want to break up your class's data into smaller nested classes (or plain old structs), then pass those around between methods.
I still DREAD the mere thought of passing all the stuff I need sometimes, even just as reference
That's not premature optimization, that's a perfectly acceptable way of preventing/reducing cognitive load. You don't want functions taking more than three parameters. If there are more then three, consider packaging your data in a struct or class.
I sometimes have the same problems as you have described: increasingly large classes that need too many helper functions to be accessed in a civilized manner.
When this occurs I try to seperate the class in multiple smaller classes if that is possible and convenient.
Scott Meyers states in Effective C++ that friend classes or functions is mostly not the best option, since the client code might do anything with the object.
Maybe you can try nested classes, that deal with the internals of your object. Another option are helper functions that use the public interface of your class and put the into a namespace related to your class.
Another way to keep your classes free of cruft is to use the pimpl idiom. Hide your private implementation behind a pointer to a class that actually implements whatever it is that you're doing, and then expose a limited subset of features to whoever is the consumer of your class.
// Your public API in foo.h (note: only foo.cpp should #include foo_impl.h)
class Foo {
public:
bool func(int i) { return impl_->func(i); }
private:
FooImpl* impl_;
};
There are many ways to implement this. The Boost pimpl template in the Vault is pretty good. Using smart pointers is another useful way of handling this, too.
http://www.boost.org/doc/libs/1_46_1/libs/smart_ptr/sp_techniques.html#pimpl
An alternative are free functions that
need parameters, but even though
premature optimization is evil, and I
haven't actually profiled or
disassembled it... I still DREAD the
mere thought of passing all the stuff
I need sometimes, even just as
reference, even though that should be
a simple address per argument.
So, let me get this entirely straight. You haven't profiled or disassembled. But somehow, you intend on ... making functions work ... without arguments? How, exactly, do you propose to program without using function arguments? Member functions are no more or less efficient than free functions.
More importantly, you come up with lots of logical reasons why you know you're wrong. I think the problem here is in your head, which possibly stems from you being completely irrational, and nothing that any answer from any of us can help you with.
Generic algorithms that take parameters are the basis of modern object orientated programming- that's the entire point of both templates and inheritance.

C++ program design question

In couple of recent projects that I took part in I was almost addicted to the following coding pattern: (I'm not sure if there is a proper name for this, but anyway...)
Let's say some object is in some determined state and we wan't to change this state from outside. These changes could mean any behaviour, could invoke any algorithms, but the fact is that they focus on changing the state (member state, data state, etc...) of some object.
And let's call one discrete way of changing those object a Mutator. Mutators are applied once (generally) and they have some internal method like apply(Target& target, ...), which instantly provokes changing the state of the object (in fact, they're some sort of functional objects).
They also could be easily assimilated into chains and applied one-by-one (Mutator m1, m2, ...); they also could derive from some basic BasicMutator with virtual void apply(...) method.
I have introduced classes called InnerMutator and ExplicitMutator which differ in terms of access - first of them can also change the internal state of the object and should be declared as a friend (friend InnerMutator::access;).
In those projects my logic turned to work the following way:
Prepare available mutators, choose which to apply
Create and set the object to some determined state
foreach (mutator) mutator.apply(object);
Now the question.
This scheme turnes to work well and
(to me) seems as a sample of some non-standard but useful design
pattern.
What makes me feel uncomfortable is that InnerMutator stuff. I don't
think declaring mutator a friend to
every object which state could be
changed is a good idea and I wan't to
find the appropriate alternative.
Could this situation be solved in terms of Mutators or could you
advice some alternative pattern with
the same result?
Thanks.
I hope this isn't taken offensively, but I can't help but think this design is an overly fancy solution for a rather simple problem.
Why do you need to aggregate mutators, for instance? One can merely write:
template <class T>
void mutate(T& t)
{
t.mutate1(...);
t.mutate2(...);
t.mutate3(...);
}
There's your aggregate mutator, only it's a simple function template relying on static polymorphism rather than a combined list of mutators making one super-mutator.
I once did something that might have been rather similar. I made function objects which could be combined by operator && into super function objects that applied both operands (in the order from left to right) so that one could write code like:
foreach(v.begin(), v.end(), attack && burn && drain);
It was really neat and seemed really clever to me at the time and it was pretty efficient because it generated new function objects on the fly (no runtime mechanisms involved), but when my co-workers saw it, they thought I was insane. In retrospect I was trying to cram everything into functional style programming which has its usefulness but probably shouldn't be over-relied on in C++. It would have been easy enough to write:
BOOST_FOR_EACH(Something& something, v)
{
attack(something);
burn(something);
drain(something);
}
Granted it is more lines of code but it has the benefit of being centralized and easy to debug and doesn't introduce alien concepts to other people working with my code. I've found it much more beneficial instead to focus on tight logic rather than trying to forcefully reduce lines of code.
I recommend you think deeply about this and really consider if it's worth it to continue with this mutator-based design no matter how clever and tight it is. If other people can't quickly understand it, unless you have the authority of boost authors, it's going to be hard to convince people to like it.
As for InnerMutator, I think you should avoid it like the plague. Having external mutator classes which can modify a class's internals as directly as they can here defeats a lot of the purpose of having internals at all.
Would it not be better to simply make those Mutators methods of the classes they're changing? If there's common functionality you want several classes to have then why not make them inherit from the same base class? Doing this will deal with all the inner mutator discomfort I would imagine.
If you want to queue up changes you could store them as sets of function calls to the methods within the classes.