Should I create multiple classes? - c++

This applies to several cases in my application:
I have 3 or 4 functions that belong together, one is a starting function that creates and frees the required memory structures and calls the other functions as appropriate. The other functions also call themselves repeatedly. Only the starting functions is called from outside, and only once or not at all per application-run.
Currently, I pass pointers to the memory structures from the starting function as function arguments, but the argument list is getting quite long in some cases.
Is there any argument against creating classes for all these cases and making the pointers to the memory structures members?

Definitely go for a class here. That's what objects and classes are designed for.

It seems to be a quite typical use case for classes: Just add the "memory structure" as protected member of the class and initiliaze it in the constructor.
The member functions (aka "method") than can work on the data.
If you have different, but similiar use cases, you may also make use of subclassing, so you create a base class with default implementation and create some derived class that overwrites some of the methods with an own implementation.
But note, that you could also use other members varibales to set the behaviour at runtime (e.g. a bool that is used to toggle on or off a specific behaviour).
Your question is too abstract to see what is the best solution for your case. Remember, often there are a lot of solutions - and so there is more than one good solution.

It sounds to me like these functions belong in a class - with the internal functions private or protected - likewise with the members.

Yes, relate them all within a class.
This will also give you a cleaner code which might help you minimize the functions' arguments lists.
In simple words an object can be anything you decide. Say a person. This is an object which I'll decide to define as a class if I'll write a program that needs to keep information regarding people.
There are much better explanations than this, just google/wikipedia it.

Related

how to properly initialize a class containing many data members?

Suppose a class contains around 10 data members then what would be the proper way to initialize an object of that particular class? Create a constructor with 10 parameters or just provide a default constructor then use setter member functions or something else?
Basically I want to know how it is done in actual real life code?
thanks.
In actual real life code, I would be very reticent to have a class with 10 parameters that need to be set.
But also in real life, I know that this happens much more often than I would like. So here is what I would do:
First, evaluate your design. Do you really need all that stuff?
Second, if you really do need all that stuff, or if there's no way out due to a legacy design, then I would require every parameter in the constructor, and make the default constructor private. Everything should be initialized in an initialization list.
Sometimes when the data members and the class methods are sufficiently decoupled I would prefer to move all the data members to their own struct, and then have a member of that struct in the class. Take that struct by const reference and assign it in the init list. Make the struct member const.
Another [design] problem is that if you use class with that many arguments as a base class and then add more arguments (due to a requirement, for example), you may well forget to initialize them. So, yeah, refactor.
Isn't this really an OOP and design question?
What is the object here? Are all 10 fields attributes of that object? Can some be further grouped under another class?
Do you always have all 10 pieces of data when you need to instantiate the class? You can make constructors for the pieces you have and/or do setters/getters.

inherited friendship

now before you guys start raging, here me out. Yes, i recognize that it is actually intended for friendship to not be inherited, i'm just trying to find some way to get something similar to it. Here is my situation (no real code, just theory). i'm working on a simple abstract game engine framework, and at first, i was just going to do the straightforward object oriented/ inheritance approach of breaking object types down. Now, it sounded really nice on paper, taking entities and breaking them into subcategories of physics, animated, and unmoving scenary and all it's subcategories. This however, became a hazardous, difficult to work with mess of entirely different objects and quite a bit of dangerous casting that could easily cause problems should i miss on something i needed to enforce instead of the compiler, which is always a good sign that there is a better solution.
So, I propose a different method of abstractly representing objects. I wish for there to be one entity class that all entities derive from which contain a vector, or some other dynamically growable array that works best, That will contain objects i'd call behaviors. The behaviors would be updated after a specified amount of time, which will affect the members of the object specified. Here are some examples.
class Force : behavior;
/*this would be a force, added to the behavior list and apply a constant
acceleration vector to the object until removed from the behavior list. (or
it's lifetime is exhausted) */
class attackThought : behavior;
/* For an ai, this would change how it reacts to a scenario by replacing or
even adding actions that it should perform given the change in position
or environment at update.*/
class animation : behavior;
/* You could create an animation, specify the animation that it is to perform,
add it to the behavior list, and during the time update, it will adjust the
vertex buffer accordingly, removing itself from the list when the animation
is done */
The problem is, i want to derive from a base behavior class, that implements some of it's virtual functions in different ways that will mostly change private members of the entity objects, (such as an objects vertex buffer). i don't want to have to manipulate too much of the basic entity code so that it can, (for the most part), be treated similarly to other objects, I only want their behaviors to be entirely manipulable/derivable. can anyone think of a way to make this system work in c++, cause i think it might be really cool :P.
btw, by way of friendship, i mean the base class behavior friending some derived entity class which can effect it's private members. For example, let's say i have a model class that derives from entity, and i want to friend a derived class of behavior called animation, and then later derive a class from model to a more specific type of object for some reason, how can an animation object manipulate the private members of this new model deriving object.
or can it? opinions on how viable this approach might be are also welcome, (as long as they actually contain critcism).
I have seen through the years that there are 2 different points of view on friendship and how it affects encapsulation:
It helps improve encapsulation by not making members public to everybody, and only making them accessible to a controlled subset of entities.
It reduces encapsulation for the obvious classic reasons that the object should be self contained and should be the only entity to modify its internal parts, etc.
I tend to avoid using friendship and try to work around it. I prefer to encapsulate everything, not just to make it private, but to be able to change how its implemented internally without affecting the users of the class. If you want a base class to be able to modify the attributes of a derived class, maybe you could consider using a Template Method design pattern. Whereby the base class orchestrates calling methods on the derived classes, and be sure to have generic, abstract manipulation methods defined in the base class.
As for making all the attributes of a class public "just in case", (sounds very dangerous) I think it would be better to start off making them all private, and consider making individual attributes public as the needs arise.

Should I stop using abstract base classes/interfaces and instead use boost::function/std::function?

I've just learned about what std::function really is about and what it is used for and I have a question: now that we essentially have delegates, where and when should we use Abstract Base Classes and when, instead, we should implement polymorphism via std::function objects fed to a generic class? Did ABC receive a fatal blow in C++11?
Personally my experience so far is that switching delegates is much simpler to code than creating multiple inherited classes each for particular behaviour... so I am a little confused abotu how useful Abstract Bases will be from now on.
Prefer well defined interfaces over callbacks
The problem with std::function (previously boost::function) is that most of the time you need to have a callback to a class method, and therefore need to bind this to the function object. However in the calling code, you have no way to know if this is still around. In fact, you have no idea that there even is a this because bind has molded the signature of the calling function into what the caller requires.
This can naturally cause weird crashes as the callback attempts to fire into methods for classes that no longer exist.
You can, of course use shared_from_this and bind a shared_ptr to a callback, but then your instance may never go away. The person that has a callback to you now participates in your ownership without them even knowing about it. You probably want more predictable ownership and destruction.
Another problem, even if you can get the callback to work fine, is with callbacks, the code can be too decoupled. The relationships between objects can be so difficult to ascertain that the code readability becomes decreased. Interfaces, however, provide a good compromise between an appropriate level of decoupling with a clearly specified relationship as defined be the interface's contract. You can also more clearly specify, in this relationship, issues like who owns whom, destrcution order, etc.
An additional problem with std::function is that many debuggers do not support them well. In VS2008 and boost functions, you have to step through about 7 layers to get to your function. Even if all other things being equal a callback was the best choice, the sheer annoyance and time wasted accidentally stepping over the target of std::function is reason enough to avoid it. Inheritance is a core feature of the language, and stepping into an overridden method of an interface is instantaneous.
Lastly I'll just add we don't have delegates in C++. Delegates in C# are a core part of the language, just like inheritance is in C++ and C#. We have a std library feature which IMO is one layer removed from a core language functionality. So its not going to be as tightly integrated with other core features of the language. It instead helps formalize the idea of function objects that have been a C++ idiom for a good while now.
I do not see how one can come to the conclusion that function pointers make abstract base classes obsolete.
A class, encapsulates methods and data that pertains to it.
A function pointer, is a function pointer. It has no notion of an encapsulating object, it merely knows about the parameters passed to it.
When we write classes, we are describing well-defined objects.
Function pointers are great for a good number of things, but changing the behaviour of an object isn't necessarily the target-audience (though I admit there may be times when you would want to do so, e.g. callbacks, as Doug.T mentions).
Please don't confuse the two.

Should I use virtual 'Initialize()' functions to initialize an object of my class?

I'm currently having a discussion with my teacher about class design and we came to the point of Initialize() functions, which he heavily promotes. Example:
class Foo{
public:
Foo()
{ // acquire light-weight resources only / default initialize
}
virtual void Initialize()
{ // do allocation, acquire heavy-weight resources, load data from disk
}
// optionally provide a Destroy() function
// virtual void Destroy(){ /*...*/ }
};
Everything with optional parameters of course.
Now, he also puts emphasis on extendability and usage in class hierarchies (he's a game developer and his company sells a game engine), with the following arguments (taken verbatim, only translated):
Arguments against constructors:
can't be overridden by derived classes
can't call virtual functions
Arguments for Initialize() functions:
derived class can completely replace initialization code
derived class can do the base class initialization at any time during its own initialization
I have always been taught to do the real initialization directly in the constructor and to not provide such Initialize() functions. That said, I for sure don't have as much experience as he does when it comes to deploying a library / engine, so I thought I'd ask at good ol' SO.
So, what exactly are the arguments for and against such Initialize() functions? Does it depend on the environment where it should be used? If yes, please provide reasonings for library / engine developers or, if you can, even game developer in general.
Edit: I should have mentioned, that such classes will be used as member variables in other classes only, as anything else wouldn't make sense for them. Sorry.
For Initialize: exactly what your teacher says, but in well-designed code you'll probably never need it.
Against: non-standard, may defeat the purpose of a constructor if used spuriously. More importantly: client needs to remember to call Initialize. So, either instances will be in an inconsistent state upon construction, or they need lots of extra bookkeeping to prevent client code from calling anything else:
void Foo::im_a_method()
{
if (!fully_initialized)
throw Unitialized("Foo::im_a_method called before Initialize");
// do actual work
}
The only way to prevent this kind of code is to start using factory functions. So, if you use Initialize in every class, you'll need a factory for every hierarchy.
In other words: don't do this if it's not necessary; always check if the code can be redesigned in terms of standard constructs. And certainly don't add a public Destroy member, that's the destructor's task. Destructors can (and in inheritance situations, must) be virtual anyway.
I"m against 'double initialization' in C++ whatsoever.
Arguments against constructors:
can't be overridden by derived classes
can't call virtual functions
If you have to write such code, it means your design is wrong (e.g. MFC). Design your base class so all the necessary information that can be overridden is passed through the parameters of its constructor, so the derived class can override it like this:
Derived::Derived() : Base(GetSomeParameter())
{
}
This is a terrible, terrible idea. Ask yourself- what's the point of the constructor if you just have to call Initialize() later? If the derived class wants to override the base class, then don't derive.
When the constructor finishes, it should make sense to use the object. If it doesn't, you've done it wrong.
One argument for preferring initialization in the constructor: it makes it easier to ensure that every object has a valid state. Using two-phase initialization, there's a window where the object is ill-formed.
One argument against using the constructor is that the only way of signalling a problem is through throwing an exception; there's no ability to return anything from a constructor.
Another plus for a separate initialization function is that it makes it easier to support multiple constructors with different parameter lists.
As with everything this is really a design decision that should be made with the specific requirements of the problem at hand, rather than making a blanket generalization.
A voice of dissension is in order here.
You might be working in an environment where you have no choice but to separate construction and initialization. Welcome to my world. Don't tell me to find a different environment; I have no choice. The preferred embodiment of the products I create is not in my hands.
Tell me how to initialize some aspects of object B with respect to object C, other aspects with respect to object A; some aspects of object C with respect to object B, other aspects with respect to object A. The next time around the situation may well be reversed. I won't even get into how to initialize object A. The apparently circular initialization dependencies can be resolved, but not by the constructors.
Similar concerns goes for destruction versus shutdown. The object may need to live past shutdown, it may need to be reused for Monte Carlo purposes, and it might need to be restarted from a checkpoint dumped three months ago. Putting all of the deallocation code directly in the destructor is a very bad idea because it leaks.
Forget about the Initialize() function - that is the job of the constructor.
When an object is created, if the construction passed successfully (no exception thrown), the object should be fully initialized.
While I agree with the downsides of doing initialization exclusively in the constructor, I do think that those are actually signs of bad design.
A deriving class should not need to override base class initialization behaviour entirely. This is a design flaw which should be cured, rather than introducing Initialize()-functions as a workaround.
Not calling Initialize may be easy to do accidentally and won't give you a properly constructed object. It also doesn't follow the RAII principle since there are separate steps in constructing/destructing the object: What happens if Initialize fails (how do you deal with the invalid object)?
By forcing default initialization you may end up doing more work than doing initialization in the constructor proper.
Ignoring the RAII implications, which others have adequately covered, a virtual initialization method greatly complicates your design. You can't have any private data, because for the ability to override the initialization routine to be at all useful, the derived object needs access to it. So now the class's invariants are required to be maintained not only by the class, but by every class that inherits from it. Avoiding that sort of burden is part of the point behind inheritance in the first place, and the reason constructors work the way they do with regard to subobject creation.
Others have argued at length against the use of Initialize, I myself see one use: laziness.
For example:
File file("/tmp/xxx");
foo(file);
Now, if foo never uses file (after all), then it's completely unnecessary to try and read it (and would indeed be a waste of resources).
In this situation, I support Lazy Initialization, however it should not rely on the client calling the function, but rather each member function should check if it is necessary to initialize or not. In this example name() does not require it, but encoding() does.
Only use initialize function if you don't have the data available at point of creation.
For example, you're dynamically building a model of data, and the data that determines the object hierarchy must be consumed before the data that describes object parameters.
If you use it, then you should make the constructor private and use factory methods instead that call the initialize() method for you. For example:
class MyClass
{
public:
static std::unique_ptr<MyClass> Create()
{
std::unique_ptr<MyClass> result(new MyClass);
result->initialize();
return result;
}
private:
MyClass();
void initialize();
};
That said, initializer methods are not very elegant, but they can be useful for the exact reasons your teacher said. I would not consider them 'wrong' per se. If your design is good then you probably will never need them. However, real-life code sometimes forces you to make compromises.
Some members simply must have values at construction (e.g. references, const values, objects designed for RAII without default constructors)... they can't be constructed in the initialise() function, and some can't be reassigned then.
So, in general it's not a choice of constructor vs. initialise(), it's a question of whether you'll end up having code split between the two.
Of bases and members that could be initialised later, for the derived class to do it implies they're not private; if you go so far as to make bases/members non-private for the sake of delaying initialisaton you break encapsulation - one of the core principles of OOP. Breaking encapsulation prevents base class developer(s) from reasoning about the invariants the class should protect; they can't develop their code without risking breaking derived classes - which they might not have visibility into.
Other times it's possible but sometimes inefficient if you must default construct a base or member with a value you'll never use, then assign it a different value soon after. The optimiser may help - particularly if both functions are inlined and called in quick succession - but may not.
[constructors] can't be overridden by derived classes
...so you can actually rely on them doing what the base class needs...
[constructors] can't call virtual functions
The CRTP allows derived classes to inject functionality - that's typically a better option than a separate initialise() routine, being faster.
Arguments for Initialize() functions:
derived class can completely replace initialization code
I'd say that's an argument against, as above.
derived class can do the base class initialization at any time during its own initialization
That's flexible but risky - if the base class isn't initialised the derived class could easily end up (due to oversight during the evolution of the code) calling something that relies on that base being initialised and consequently fails at run time.
More generally, there's the question of reliable invocation, usage and error handling. With initialise, client code has to remember to call it with failures evident at runtime not compile time. Issues may be reported using return types instead of exceptions or state, which can sometimes be better.
If initialise() needs to be called to set say a pointer to nullptr or a value safe for the destructor to delete, but some other data member or code throws first, all hell breaks loose.
initialise() also forces the entire class to be non-const in the client code, even if the client just wants to create an initial state and ensure it won't be further modified - basically you've thrown const-correctness out the window.
Code doing things like p_x = new X(values, for, initialisation);, f(X(values, for initialisation), v.push_back(X(values, for initialisation)) won't be possible - forcing verbose and clumsy alternatives.
If a destroy() function is also used, many of the above problems are exacerbated.

Converting all functions into classes

I was reading the book Refactoring: Improving the Design of Existing Code by Fowler, where it says to replace function calls with same names classes and call constructors of that class in place of original function call.
My question is is it a good idea to convert all the functions(more or less, except very trivial ones) into objects so that the code becomes more modular?
Thanks,
Expanding a bit on my earlier comment:
In C++ there is absolutely no reason to turn all functions into classes, some kind of processing objects. Functions work well when you just have to compute and return a value.
However, if you have a large function that creates an internal state and uses that in several places during its processing, or (gasp!) stores some state in global variables, that function might be a class in disguise. In that case it can be a good idea to store the state in a class object with several smaller member functions doing their work on that common state.
On the other hand, a function that only computes a value from its parameters is not improved by putting it into a class.
No, why would it? If you have functionality that is logically a function (stateless computation), and there's no compelling reason to implement it as a class, then just implement it as a function.
The advice to "replace function calls with same names classes and call constructors of that class in place of original function call" is plain wrong: how can you replace
int y = f(x);
by a class f and a call to its constructor? A constructor doesn't have a return value! The only way to get this to work is to overload operator() on the class f so you can use one of
int y = f(x)();
int y = f()(x);
both of which are pointless. (Also, you'd have to remember which one of these you need for every function object you define.)
There must be something you're not telling us.
In my opinion, converting functions into classes is absolutely pointless. Why would you want to do that?
When you convert your functions to objects, you're not gaining anything. A method call is in fact the same plain function call, only with a hidden argument, this. In your case, that argument would be redundant because your object is not bearing any state.
The only reason I can think of for converting functions to objects is passing functions as objects to other functions, but for that purpose we have function pointers or boost::function or c++ 0x lambdas.
Definitively no!
It is no point to convert any function to class.
Class is about to manage some state of object and hide information, functions are to global and mostly stateless. A lot of lose classes make software inefficient and unmaintainable.