My team works on an HTTP web server in C++. The codebase has aged over time, and has a widespread problem of 12+ parameters being passed to every function.
A fake example: We need to build a Car, but in order to do that, we have the following function:
MaybeBuildCar(engine_params, steering_params, interior_params, fuel_params, available_inventory, parts, &debug);
Someone on our team has proposed that we create a wrapper CarBuilder class whose constructor takes in the params and "stateful" objects like available_inventory, then has a separate function for BuildCar as follows:
CarBuilder car_builder(engine_params, steering_params, interior_params, fuel_params, available_inventory, &debug);
auto car = car_builder.BuildCar(parts);
Personally, I don't see much value in having a class with a single public function that is always called. We'll always need these parameters, and we'll always need the parts, so this just adds more steps to build the car. It could even add confusion, as now a user of CarBuilder must know to both construct it and call BuildCar.
Admittedly, this simplifies our helper functions within car_builder.cc, as they also require passing these params, but to me that's misusing what a class is for: maintaining state.
Is creating this CarBuilder a misuse of the class, or is simply cleaning up function signatures a valid use? Does anyone have any suggestions on how to tackle this problem?
Minimizing function parameters can be a blessing for heavily used functions in a performance-sensitive environment:
If you pass 6 references to a function, that is 6 pointer copies pushed to the stack;
If you pass a single CarBuilder, it is one "reference-that-contains-6-other-references".
It depends on your situation.
you could define a class that contains all parameters and in each function just passed this object.
struct CarComponent
{
public:
EngineParams engine_params;
SteeringParams steering_params;
InteriorParams interior_params;
FuelParams fuel_params;
AvailableInventory available_inventory
};
MaybeBuildCar(car_component);
other_function(car_component);
Advantage:
Function's signature is decoupled from changing members of the struct (CarComponent). easy to change.
Refactor all the parameters in each function with a specific object. it prevents repetition and it becomes easier to read the code.
Related
I'm fairly new to c++ templates.
I have a class whose constructor takes two arguments. It's a class that keeps a list of data -- it's actually a list of moves in a chess program.
I need to keep my original class as it's used in other places, but I now need to pass extra arguments to the class, and in doing so have a few extra private data members and specialize only one of the private methods -- everything else will stay the same. I don't think a derived class helps me here, as they aren't going to be similar objects, and also the private methods are called by the constructor and it will call the virtual method of the base class -- not the derived method.
So I guess templates are going to be my answer. Just looking for any hints about how might proceed.
Thanks in advance
Your guess is wrong. Templates are no more the answer for your problem than inheritance is.
As jtbandes said in comment below your question, use composition.
Create another class that contains an instance of your existing class as a member. Forward or delegate operations to that contained object as needed (i.e. a member function in your new class calls member functions of the contained object). Add other members as needed, and operations to work with them.
Write your new code to interact with the new class. When your new code needs to interact with your old code, pass the contained object (or a reference or a pointer to it) as needed.
You might choose to implement the container as a template, but that is an implementation choice, and depends on how you wish to reuse your container.
Templates are used when you want to pass at compile time parameter like values,typenames, or classes. Templates are used when you want to use exactly the same class with the same methods, but applying it to different parameters. The case you described is not this I think.
If they aren't goign to be similar objects you may want to create a specialized class (or collections of function) to use from the various other classes.
Moreover you can think of creating a base class and extending it as needed. Using a virtual private method should allow you to select the method implementation of the object at runtime instead of the method of the base class.
We may help you more if you specify what does they need to share, what does your classes have in common?
The bare bones of my present code looks like this:
class move_list{
public:
move_list(const position& pos, unsigned char ply):pos_(pos),ply_(ply){
//Calculates moves and calls add_moves(ply,target_bitboard,flags) for each move
}
//Some access functions etc...
private:
//private variables
void add_moves(char,Bitboard,movflags);
};
Add_moves places the moves on a vector in no particular order as they are generated. My new class however, is exactly the same except it requires extra data:
move_list(const position& pos, unsigned char ply,trans_table& TT,killers& kill,history& hist):pos_(pos),ply_(ply),TT_(TT),kill_(kill),hist_(hist) {
and the function add_moves needs to be changed to use the extra data to place the moves in order as it receives them. Everything else is the same. I guess I could just write an extra method to sort the list after they have all been generated, but from previous experience, sorting the list as it receives it has been quicker.
I have many small functions which every is doing a single thing like for example:
pingServer, checkUserValidAccount, countDistance.
It is not worth of wrapping every function into single class.
What is the best practice in c++ to handle such a different many small functions?
Maybe writing some class called Helpers like for example NetworkHelpers?
Placing them in a namespace is an option. I don't see the need for a class. An instance of a class is mean to represent a state, but you're describing a bunch of free functions, so a stateless system.
"It is not worth of wraping every function into single class." - this is not a valid argument for making the decision not to write a class. A class can have a single member and a single method, but if there is logic behind it, you should write it.
If your functions and your logic mandates the use of a class, where your functions have the same logic but operate differently depending on the object, by all means, write a class. If your sole purpose is to group the functions together, when their logic doesn't really rely on the same instance of a class, group them in a namespace.
An example based on your question:
namespace NetworkHelpers
{
//free function, use a namespace
bool pingServer(std::string hostname);
}
//alternative, where the object has a state:
class ServerConnection
{
std::string _hostname;
public:
NetworkHelpersClass(std::string hostname)
{
_hostname = hostname;
}
bool pingServer()
{
return NetworkHelpersNamespace::pingServer(_hostname);
}
};
As you can see, inside the namespace, the function doesn't depend on anything other than the parameter.
Inside the class, since it has a state and you create an object for each server (so similar behavior, yet different depending on the object), you call the function with no parameters as the object has a state.
I hope this makes it clear.
Unlike some languages, C++ does not require that you put every function in a class. If you have functions that don't belong in a class, put them in a namespace.
If I may add another best practice other than namespaces: group your functions in DLLs minding their dependencies.
Avoid circular linking and create low-level libraries with the smallest number of dependencies as possible.
I have a class that needs 12 parameters to be passed to its constructor. So I think that there is something wrong with the design of this class.
I would like to ask if there is any design pattern or a general collection of rules regarding the design of a class, especially its constructor.
12 parameters definitely sound too many to me. Options to reduce their numbers are:
Introduce Parameter Object by grouping logically related parameters into an object and passing that object instead of the individual parameters.
Introduce a Builder (optionally with method chaining). This does not reduce the actual parameter list but it makes the code more readable, and is especially useful if you have several different creation scenarios with varying parameters. So instead of
MyClass someObject = new MyClass(aFoo, aBar, aBlah, aBaz, aBorp, aFlirp,
andAGoo);
MyClass anotherObject = new MyClass(aFoo, null, null, aBaz, null, null,
andAGoo);
you can have
MyClass someObject = new MyClassBuilder().withFoo(aFoo).withBar(aBar)
.withBlah(aBlah).withBaz(aBaz).withBorp(aBorp).withFlirp(aFlirp)
.withGoo(aGoo).build();
MyClass anotherObject = new MyClassBuilder().withFoo(aFoo).withBaz(aBaz)
.withGoo(aGoo).build();
(Maybe I should have started with this ;-) Analyse the parameters - Are all of them really needed in the constructor (i.e. mandatory)? If a parameter is optional, you may set it via its regular setter instead of the constructor.
If your function takes eleven parameters, you probably have forgotten one more
I love this sentence because it sums it all: Bad design calls for bad design.
I took this is from the book C++ Coding Standards: 101 Rules, Guidelines, And Best Practices by Herb Sutter, Andrei Alexandrescu.
Edit: The direct quote is If you have a procedure with ten parameters, you probably missed some. It is itself a quote from Alan Perlis.
Functions with so many parameters are a symtom of bad design.
One of the possibility is to try to encapsulate part of these parameters in an entity/class that has a defined goal. (not a garbage class that would list all parameters without meaningful structure).
Never forget the Single Responsibility Principle
As a consequence, classes remain limited in size, and as a consequence, limited in number of member paramters, and thus limited in the size of parameters needed for its constructors. Like one of the comments below says, the class with so much constructor parameters may handle too much futile details independent of its main goal.
A look at this one is advised too: How many parameters are too many?
12 Parameters, something is most probably wrong with the design.
What is done with the parameters?
Does the class just send them into other constructors? Then perhaps it should just accept interfaces to ready constructed objects.
Is the class large and does a lot of things with all these parameters? Then the class has to much responsibility and should accept classes that takes care of the details instead.
Are there any "clusters" in the parameters? Perhaps are some of the parameters a class in the creation. Encapsulate them and give them the appropriate responsibility.
The alternative is that this is parameters for a lowlevel, performance critical construction, in which case the design just have to take back seat, but that is rarely the case.
if it is possible you may group the parameters by classes and pass their instances to the constructor.
I think this can be acceptable when using the State pattern for example. However, might I suggest passing the object (if appropriate) that those parameters come from instead? And then in the constructor loading the data from it?
I have a class which I can write like this:
class FileNameLoader
{
public:
virtual bool LoadFileNames(PluginLoader&) = 0;
virtual ~FileNameLoader(){}
};
Or this:
class FileNameLoader
{
public:
virtual bool LoadFileNames(PluginLoader&, Logger&) = 0;
virtual ~FileNameLoader(){}
};
The first one assumes that there is a member Logger& in the implementation of FileNameLoader. The second one does not. However, I have some classes which have a lot of methods which internally use Logger. So the second method would make me write more code in that case. Logger is a singleton for the moment. My guess is that it will remain that way. What is the more 'beautiful' of the two and why? What is the usual practice?
EDIT:
What if this class was not named Logger? :). I have a Builder also. How about then?
I don't see what extra advantage approach two has over one (even considering unit testing!), infact with two, you have to ensure that everywhere you call a particular method, a Logger is available to pass in - and that could make things complicated...
Once you construct an object with the logger, do you really see the need to change it? If not, why bother with approach two?
I prefer the second method as it allows for more robust black box testing. Also it makes the interface of the function clearer (the fact that it uses such a Logger object).
The first thing is to be sure that the Logger dependency is being provided by the user in either case. Presumably in the first case, the constructor for FileNameLoader takes a Logger& parameter?
In no case would I, under any circumstances, make the Logger a Singleton. Never, not ever, no way, no how. It's either an injected dependency, or else have a Log free function, or if you absolutely must, use a global reference to a std::ostream object as your universal default logger. A Singleton Logger class is a way of creating hurdles to testing, for absolutely no practical benefit. So what if some program does create two Logger objects? Why is that even bad, let alone worth creating trouble for yourself in order to prevent? One of the first things I find myself doing, in any sophisticated logging system, is creating a PrefixLogger which implements the Logger interface but prints a specified string at the start of all messages, to show some context. Singleton is incompatible with with this kind of dynamic flexibility.
The second thing, then, is to ask whether users are going to want to have a single FileNameLoader, and call LoadFileNames on it several times, with one logger the first time and another logger the second time.
If so, then you definitely want a Logger parameter to the function call, because an accessor to change the current Logger is (a) not a great API, and (b) impossible with a reference member anyway: you'd have to change to a pointer. You could perhaps make the logger parameter a pointer with a default value of 0, though, with 0 meaning "use the member variable". That would allow uses where the users initial setup code knows and cares about logging, but then that code hands the FileNameLoader object off to some other code that will call LoadFileNames, but doesn't know or care about logging.
If not, then the Logger dependency is an invariant for each instance of the class, and using a member variable is fine. I always worry slightly about reference member variables, but for reasons unrelated to this choice.
[Edit regarding the Builder: I think you can pretty much search and replace in my answer and it still holds. The crucial difference is whether "the Builder used by this FileNameLoader object" is invariant for a given object, or whether "the Builder used in the call" is something that callers to LoadFileNames need to configure on a per-call basis.
I might be slightly less adamant that Builder should not be a Singleton. Slightly. Might.]
In general I think less arguments equals better function. Typically, the more arguments a function has, the more "common" the function tends to become - this, in turn, can lead to large complicated functions that try to do everything.
Under the assumption that the Logger interface is for tracing, in this case I doubt the the user of the FileNameLoader class really wants to be concerned with providing the particular logging instance that should be used.
You can also probably apply the Law of Demeter as an argument against providing the logging instance on a function call.
Of course there will be specific times where this isn't appropriate. General examples might be:
For performance (should only be done after identification of specific performance issues).
To aid testing through mock objects (In this case I think a constructor is a more appropriate location, for logging remaining a singleton is probably a better option...)
I would stick with the first method and use the Logger as a singleton. Different sinks and identifying where data was logged from is a different problem altogether. Identifying the sink can be as simple or as complex as you want. For example (assuming Singleton<> is a base-class for singletons in your code):
class Logger : public Singleton<Logger>
{
public:
void Log(const std::string& _sink, const std::string& _data);
};
Your class:
class FileNameLoader
{
public:
virtual bool LoadFileNames(PluginLoader& _pluginLoader)
{
Logger.getSingleton().Log("FileNameLoader", "loading xyz");
};
virtual ~FileNameLoader(){}
};
You can have an inherently complex Log Manager with different sinks, different log-levels different outputs. Your Log() method on the log manager should support simple logging as described above, and then you can allow for more complex examples. For debugging purposes, for example, you could define different outputs for different sinks as well as having a combined log.
The approach to logging that I like best is to have a member of type Logger in my class (not a reference or pointer, but an actual object).
Depending on the logging infrastructure, that makes it possible to decide, on a per-class basis, where the output should go or which prefix to use.
This has the advantage over your second approach that you can't (accidentally) create a situation where members of the same class can not be easily identified as such in the logfiles.
One of the ways to implement Dependency Injection correctly is to separate object creation from business logic. Typically, this involves using a Factory for object creation.
Up until this point, I've never seriously considered using a Factory so I apologize if this question seems a little simplistic:
In all the examples of the Factory Pattern that I've run across, I always see very simple examples that have no parameterization. For example, here's a Factory stolen from Misko Hevery's excellent How To Think About the "new" Operator article.
class ApplicationBuilder {
House build() {
return new House(new Kitchen(
new Sink(),
new Dishwasher(),
new Refrigerator())
);
}
}
However, what happens if I want each house that I build to have a name? Am I still using the Factory pattern if I re-write this code as follows?
class ApplicationBuilder {
House build( const std::string & house_name) {
return new House( house_name,
new Kitchen(new Sink(),
new Dishwasher(),
new Refrigerator())
);
}
}
Note that my Factory method call has changed from this:
ApplicationBuilder builder;
House * my_house = builder.build();
To this:
ApplicationBuilder builder;
House * my_house = builder.build("Michaels-Treehouse");
By the way: I think the concept of separating object instantiation from business logic is great, I'm just trying to figure out how I can apply it to my own situation. What confuses me is that all the examples I've seen of the Factory pattern never pass any parameters into the build() function.
To be clear: I don't know the name of the house until the moment before I need to instantiate it.
I've seen quite a lot of examples that use a fixed set of arguments, like in your name example, and have used them myself too and i can't see anything wrong with it.
However there is a good reason that many tutorials or small articles avoid showing factories that forward parameters to the constructed objects: It is practically impossible to forward arbitrary number of arguments (even for a sane limit like 6 arguments). Each parameter you forward has to be accepted as const T& and T& if you want to do it generic.
For more complicated examples, however, you need an exponentially growing set of overloads (for each parameter, a const and a nonconst version) and perfect forwarding is not possible at all (so that temporaries are forwarded as temporaries, for example). For the next C++ Standard that issue is solved:
class ApplicationBuilder {
template<typename... T>
House *build( T&&... t ) {
return new House( std::forward<T>(t)...,
new Kitchen(new Sink(),
new Dishwasher(),
new Refrigerator())
);
}
};
That way, you can call
builder.build("Hello", 13);
And it will return
new House("Hello", 13, new Kitchen(new Sink(...
Read the article i linked above.
Not only is is acceptable, but it's common to pass parameters to a factory method. Check out some examples. Normally the parameter is a type telling the factory what to make, but there's no reason you can't add other information you need to build an object. I think what you're doing is fine.
I can't see why it would be wrong to add this parameter to your factory. But be aware that you shouldn't end up adding many parameters which might not be useful to all objects created by the factory. If you do, you'll have lost quite a lot of the advantages of a factory !
The idea of a factory is that it gives you an instance of a class/interface, so there is nothing wrong with passing parameters. If there were, it would be bad to pass parameters to a new() as well.
I agree with Benoit. Think of a factory for creating something like sql connections though, in a case like this it would be necessary to pass information about the connection to the factory. The factory will use that information to use the correct server protocol and so on.
Sure, why not..!?
The nice thing about passing parameters is that it allows you to hide the implementation of the concrete object. For example, in the code you posted you pass the parameters to the constructor. However, you may change the implementation so that they get passed via an Initiailze method. By passing parameters to the factory method you hide the nature of constructing and initializing the object from the caller.
Take a look at Loki::Factory, there's an implementation very much like it coming to Boost as well, however. Some example code i regularly use in different flavors:
typedef Loki::SingletonHolder< Loki::Factory< Component, std::string, Loki::Typelist< const DataCollection&, Loki::Typelist< Game*, Loki::NullType > > > > ComponentFactory;
This might seem a bit weird at first sight, however let me explain this beast and how powerful it really is. Basically we create a singleton which holds a factory, the out most parameters are for the singleton, Component is our product, std::string is our creation id type, after this follows a type list of the params which is required for creation of Components ( this can be defined using a macro as well for a less verbose syntax ). After this line one can just do:
ComponentFactory::Instance().CreateObject( "someStringAssociatedWithConcreteType", anDataCollection, aGamePointer );
To create objects, to register one just use ComponentFactory::Instance().Register();. There's a great chapter on the details in the book Modern C++ Design.