Extending a general purpose function - c++

I'm creating a game, and in this game a ball can be caught in various ways, which all result in different behaviour. Initially, I wanted to add an enum to a certain general purpose method when catching to ball, which will then delegate the actions that take place when a ball gets caught in a certain way. An example would be:
void Weapon::Catch(Character Catcher, CatchMethod Method)
{
switch (Method)
{
case Method::PickUp: OnPickup(Catcher); break;
case Method::Pass: OnPass(Catcher); break;
// etc
}
}
This would allow me to call the function as:
MyWeapon->Catch(Catcher, Method::Pickup);
MyWeapon->Catch(Catcher, Method::Pass);
and the likes. I think this would read nicer than
MyWeapon->CatchByPickup(Catcher);
MyWeapon->CatchByPass(Catcher);
My main issue however, is that this is not extendable at all, which is what I was actually hoping to achieve with this general purpose method. If I make the method an enum, I cannot simply extend the enum and override the virtual Catch method in a derived class of Weapon. If I decide to extend the method in some derived class, I'd have to create a new enum which begins at the last value of the Method enum. I do not feel that this is a proper way to deal with the situation, but I do not know what the best practise in this case would be. Does it perhaps involve template specializations? The main problem to me, is that I cannot simply extend enums.

You could make use of std::function.
using CatchMethod = std::function<void(Character)>;
void Weapon::Catch(Character Catcher, CatchMethod Method)
{
Method(Catcher);
}
Calling the function is then pretty straightforward
// If its a regular function you can just use the pointer to the function
weapon.Catch(Player, &OnPickup);
// If its a member function you can use lambda
weapon.Catch(Player, [this](Character Catcher){OnPickup(Catcher);});
// or std::bind (slightly more verbose and less flexible)
weapon.Catch(Player, std::bind(&Weapon::OnPickup, this, std::placeholders::_1));

It's a bit non-obvious since I'm not sure if you have any other code in your Catch method that is relevant to the system, but it sounds to me like you would want to simply not use methods at all and invert the control to have different functions. Like this, for example:
void pickup(Weapon weapon, Character catcher) {
/* Do whatever your OnPickup does */
}
void pass(Weapon weapon, Character catcher) {
/* Do whatever your OnPass does */
}
And then, obviously, just call them like this:
pickup(MyWeapon, Catcher);
pass(MyWeapon, Catcher);
If there is no surrounding code or similar prerequisites that you don't show in the question, I don't think there are any back sides to this, and declaring new functions to do similar things is entirely decentralized and extensible.
If it is that you need to pass the CatchMethod through other functions, you could simply pass a function pointer instead.
As an aside, by the way, unless Weapon and Character here are typedefs to something else, it's generally a bad idea to pass these kinds of things by-value. You probably want to use references or pointers instead.

Related

store list of arbitrary methods in C++

The intention in pseudo code:
T magicContainer;
magicContainer.push(method1);
magicContainer.push(method2);
...
magicContainer.push(methodN);
magicContainer.loop(i) {
magicContainer[i].call(...);
}
Now method1, method2, ... shall have arbitrary signatures - I would then claim, that this is simply not possible in C++. Explanation: whether you use old-school ways like void pointers or fancy boost::any you will always have to keep track of the function signature type somewhere. Still I want to ask: what are the closest, most elegant solutions for this scenario?

Giving a function implementation more than one name in c++

Let say I have a basic 2D vector class something like
class vector2
{
int x, y;
}
these two values could be used to represent a position as well as a width and height. does C++ provide a away for me to impliment a function such as vector2::getXpos() and then also define vector2::getWidth() and have it use the same implementation.
I know that I could just make both of these function inline, but the compiler might decide to not inline these functions. so if getWidth just called getXpos you would end up with two function calls.
A more relistic example of what I would want to use this for is getLength() and erm... getSpan() (thinking of like a screen here for when you say 40" tv)
I would assume that this would be a simple case of something like a special function definition... I did find this page but this sounds like it is a C feature... and a bit of a hack to get working.
EDIT
I am not asking about the mechanics of inline functions... I basicaly want to do something functionally like
class MyClass
{
void ActaullyDoStuff();
public:
void foo(){ActaullyDoStuff();}
void bar(){ActuallyDoStuff();}
}
but where I can just write something like
class MyBetterClass
{
public:
void foo(){ /* BLOCK OF CODE */ }
void bar(){ /* DO WHAT EVER foo() DOES */ }
}
I want bar() to be another way of just doing foo() so that the same functional code can have different, more appropriate names depending on the situation.
but the compiler might decide to not
inline these functions
Then the compiler probably has a good reason to do so.
I think this is a non problem, just have the function with the alternative name call the "real" function, and the compiler will most likely inline it.
EDIT:
If that didn't convince you, it is possible to use __forceinline in visual studio.
Here is the way to force inline in GCC.
EDIT2:
class MyBetterClass
{
public:
void foo(){ /* BLOCK OF CODE */ }
__forceinline void bar(){ foo(); /* DO WHAT EVER foo() DOES */ }
}
Using C++11 you could do:
//works for non-template non-overloaded functions:
const auto& new_fn_name = old_fn_name;
Other solutions:
How do I assign an alias to a function name in C++?
It appears you're not thinking about this in an object oriented way. I have to second mjfgates advice that you really don't want to do this.
What you want to do is abstract the idea of a vector into a class and implement the common methods you might want to use with a vector. In fact, you may want to consider implementing your class example above as a "Point" class and then have a "Vector" class aggregate two point classes.
Using your example, your class would not be well defined if it was used for two different purposes. Let's say you want to make a method on some class to draw vector2. You would have to know which instances of vector2 are representing a starting point and which ones are representing a width/height. You'd probably also need a third representation to represent direction. The easier way is to implement the vector in terms of getStartPoint, getEndPoint, and any other methods that will do calculations appropriate for the vector. Then the consumer doesn't need to know about the internal working of the vector2 class, they just call the methods to get the information they need.
Your referenced link is AFAIK not a C feature either, but something specific to that particular compiler.
C++ provides such a mechanism: it happens to be inlined functions! Worrying about the compiler not optimizing away the redundant call in an inlineable function is definitely premature optimization. Inline, then measure if you're worried about performance.
If you're absolutely insisting on eliminating the merest chance of a redundant call, you might do something with preprocessor #defines... but beware: macros do not respect class boundaries, and your header files will sooner or later stomp on some other, unrelated code. Better not go there.
you could use preprocessor #defines.... if you're into the world's worst bugs. You'll get the equivalent of guaranteed inline if you want, or just aliases if you want that too.
So, you want to have two functions, on the same object, that return exactly the same data, as the same data type.
Don't DO that.
Providing more than one path to the same data is one of those things that sounds like it might be convenient for whoever's going to be using your object-- until you think about it. What happens is that six months down the road, somebody turns up a bug in one of the two functions, and you fix that function but not the other one, so the bug's still there. Or the programmer who's writing clients for your object is driven half-insane wondering what the difference is between getLength() and getSpan().
The one time I'd do this would be when implementing an interface that requires a duplicate of an existing member function. In that case, the interface's function is going to be virtual, so the notion of inlining goes out the window.

C++ design pattern to get rid of if-then-else

I have the following piece of code:
if (book.type == A) do_something();
else if (book.type == B) do_something_else();
....
else do so_some_default_thing.
This code will need to be modified whenever there is a new book type
or when a book type is removed. I know that I can use enums and use a switch
statement. Is there a design pattern that removes thisĀ if-then-else?
What are the advantages of such a pattern over using a switch statement?
You could make a different class for each type of book. Each class could implement the same interface, and overload a method to perform the necessary class-specific logic.
I'm not saying that's necessarily better, but it is an option.
As others have pointed out, a virtual function should probably be your first choice.
If, for some reason, that doesn't make sense/work well for your design, another possibility would be to use an std::map using book.type as a key and a pointer to function (or functor, etc.) as the associated value, so you just lookup the action to take for a particular type (which is pretty much how many OO languages implement their equivalent of virtual functions, under the hood).
Each different type of book is a different sub-class of the parent class, and each class implements a method do_some_action() with the same interface. You invoke the method when you want the action to take place.
Yes, it's called looping:
struct BookType {
char type;
void *do();
};
BookType[] types = {{A, do_something}, {B, do_something_else}, ...};
for (int i = 0; i < types_length; i++) {
if (book.type == types[i].type) types[i].do(book);
}
For a better approach though, it's even more preferrable if do_something, do_something_else, etc is a method of Book, so:
struct Book {
virtual void do() = 0;
};
struct A {
void do() {
// ... do_something
}
};
struct B {
void do() {
// ... do_something_else
}
};
so you only need to do:
book.do();
Those if-then-else-if constructs are one of my most acute pet peeves. I find it difficult to conjure up a less imaginative design choice. But enough of that. On to what can be done about it.
I've used several design approaches depending on the exact nature of the action to be taken.
If the number of possibilities is small and future expansion is unlikely I may just use a switch statement. But I'm sure you didn't come all the way to SOF to hear something that boring.
If the action is the assignment of a value then a table-driven approach allows future growth without actually making code changes. Simply add and remove table entries.
If the action involves complex method invocations then I tend to use the Chain of Responsibility design pattern. I'll build a list of objects that each knows how to handle the actions for a particular case.
You hand the item to be processed to the first handler object. If it knows what to do with the item it performs the action. If it doesn't, it passes the item off to the next handler in the list. This continues until the item is processed or it falls into the default handler that cleans up or prints an error or whatever. Maintenance is simple -- you add or remove handler objects from the list.
You could define a subclass for each book type, and define a virtual function do_something. Each subclass A, B, etc would have its own version of do_something that it calls into, and do_some_default_thing then just becomes the do_something method in the base class.
Anyway, just one possible approach. You would have to evaluate whether it really makes things easier for you...
Strategy Design Pattern is what I think you need.
As an alternative to having a different class for each book, consider having a map from book types to function pointers. Then your code would look like this (sorry for pseudocode, C++ isn't at the tip of my fingers these days):
if book.type in booktypemap:
booktypemap[book.type]();
else
defaultfunc();

runtime type comparison

I need to find the type of object pointed by pointer.
Code is as below.
//pWindow is pointer to either base Window object or derived Window objects like //Window_Derived.
const char* windowName = typeid(*pWindow).name();
if(strcmp(windowName, typeid(Window).name()) == 0)
{
// ...
}
else if(strcmp(windowName, typeid(Window_Derived).name()) == 0)
{
// ...
}
As i can't use switch statement for comparing string, i am forced to use if else chain.
But as the number of window types i have is high, this if else chain is becoming too lengthy.
Can we check the window type using switch or an easier method ?
EDIT: Am working in a logger module. I thought, logger should not call derived class virtual function for logging purpose. It should do on its own. So i dropped virtual function approach.
First of all use a higher level construct for strings like std::string.
Second, if you need to check the type of the window your design is wrong.
Use the Liskov substitution principle to design correctly.
It basically means that any of the derived Window objects can be replaced with it's super class.
This can only happen if both share the same interface and the derived classes don't violate the contract provided by the base class.
If you need some mechanism to apply behavior dynamically use the Visitor Pattern
Here are the things to do in order of preference:
Add a new virtual method to the base class and simply call it. Then put a virtual method of the same name in each derived class that implements the corresponding else if clause inside it. This is the preferred option as your current strategy is a widely recognized symptom of poor design, and this is the suggested remedy.
Use a ::std::map< ::std::string, void (*)(Window *pWindow)>. This will allow you to look up the function to call in a map, which is much faster and easier to add to. This will also require you to split each else if clause into its own function.
Use a ::std::map< ::std::string, int>. This will let you look up an integer for the corresponding string and then you can switch on the integer.
There are other refactoring strategies to use that more closely resemble option 1 here. For example,if you can't add a method to the Window class, you can create an interface class that has the needed method. Then you can make a function that uses dynamic_cast to figure out if the object implements the interface class and call the method in that case, and then handle the few remaining cases with your else if construct.
Create a dictionary (set/hashmap) with the strings as keys and the behaviour as value.
Using behaviour as values can be done in two ways:
Encapsulate each behaviour in it's
own class that inherit from an
interface with"DoAction" method that
execute the behavior
Use function pointers
Update:
I found this article that might be what you're looking for:
http://www.dreamincode.net/forums/topic/38412-the-command-pattern-c/
You might try putting all your typeid(...).name() values in a map, then doing a find() in the map. You could map to an int that can be used in a switch statement, or to a function pointer. Better yet, you might look again at getting a virtual function inside each of the types that does what you need.
What you ask for is possible, it's also unlikely to be a good solution to your problem.
Effectively the if/else if/else chain is ugly, the first solution that comes to mind will therefore to use a construct that will lift this, an associative container comes to mind and the default one is obviously std::unordered_map.
Thinking on the type of this container, you will realize that you need to use the typename as the key and associate it to a functor object...
However there are much more elegant constructs for this. The first of all will be of course the use of a virtual method.
class Base
{
public:
void execute() const { this->executeImpl(); }
private:
virtual void executeImpl() const { /* default impl */ }
};
class Derived: public Base
{
virtual void executeImpl() const { /* another impl */ }
};
It's the OO way of dealing with this type of requirement.
Finally, if you find yourself willing to add many different operations on your hierarchy, I will suggest the use of a well-known design pattern: Visitor. There is a variation called Acyclic Visitor which helps dealing with dependencies.

Which is more appropriate: getters and setters or functions?

Is it ever appropriate to abandon the "getMyValue()" and "setMyValue()" pattern of getters and setters if alternative function names make the API more obvious?
For example, imagine I have this class in C++:
public class SomeClass {
private:
bool mIsVisible;
public:
void draw();
void erase();
}
I could add functions to get/set "mIsVisible" like this:
bool getVisible() { return mIsVisible; };
void setVisible(bool visible) {
if (!mIsVisible && visible) {
draw();
} else if (mIsVisible && !visible) {
erase();
}
mIsVisible = visible;
}
However, it would be equally possible to use the following methods instead:
bool isVisible() { return mIsVisible; };
void show() {
if (!mIsVisible) {
mIsVisible = true;
draw();
}
}
void hide() {
if (mIsVisible) {
mIsVisible = false;
erase();
}
}
In brief, is it better to have a single "setVisible(bool)" method, or a pair of "show()" and "hide()" methods? Is there a convention, or is it purely a subjective thing?
Have a read of the article "Tell, Don't Ask" over at the Pragmatic Programmers web site and I think you'll see that the second example is the way to go.
Basically, you shouldn't be spreading the logic out through your code which is implied with your first example, namely:
get current visibility value,
make decision based on value,
update object.
In the example you gave, show() and hide() make a lot of sense, at least to me.
On the other hand, if you had a property skinPigment and you decided to make functions called tanMe() and makeAlbino() that would be a really poor, non-obvious choice.
It is subjective, you have to try to think the way your users (the people utilizing this class) think. Whichever way you decide, it should be obvious to them, and well-documented.
I would go with the isVisible()/show()/hide() set.
setVisible() implies that all it does it change the internal variable. show() and hide() make the side effects clear.
On the other hand, if all getVisible()/setVisible() did was to change the internal variable, then you've just changed remarkably little from having them as public fields.
setters actually have very little to do with object orientation, which is the programming idiom applied in the example. getters are marginally better, but can be lived without in many cases.
If everything can be gotten and set, what's the point of having an object? Operations should be called on objects to accomplish things, changing the internal state is merely a side-effect of this.
The bad thing about a setter in the presence of polymorphism - one of OO's cornerstones - is that you force every derived class to have a setter. What if the object in question has got no need for an internal state called mIsVisible? Sure he can ignore the call and implement as empty, but then you are left with a meaningless operation. OTOH, operations like show and hide can be easily overridden with different implementations, without revealing anything about the internal state.
In general, I think setters/getters should only set the values of properties. In your example, you are also performing an action based on the value of the isVisible property. In this case, I would argue that using functions to perform the action and update the state is better than having a setter/getter that performs an action as a side-effect of updating the property.
If switching mIsVisible really turns visibility of the object on and off immediately, than use the show/hide scenario. If it will stay in the old state a little longer (e.g. until something else triggers a redraw) then the set/get scenario would be the way to go.
I prefer the show() and hide() methods because they explicitly tell what you are going. The setVisible(boolean) doesn't tell you if the method is going to show/draw right away. Plus show() and hide() are better-named method for an interface (IMHO).
Implicitly, the 'show' and 'hide' functions you list are both setters
For booleans, I'd think that a single tool like you've shown would be good. However, a .show and .hide function also look like commands, not functions that change the state of the object.
In the case you actually have to write code like
if (shouldBeShowingAccordingToBusinessLogic()) w.show();
else w.hide();
all over the place, you might be better off with
w.showIfAndOnlyIf(shouldBeShowingAccordingToBusinessLogic())
Or, for truly bizarre cases, when your logic can't decide whether to dhow or not till the end of some code stretch, you can try
w.setPostponedVisibility(shouldBeShowingAccordingToBusinessLogic());
...
w.realizeVisibility();
(Didn't I say it's bizzare?)
An additional motivation to go for the display/hide solution is that as a setter,
the setVisible method has a 'side effect', in that it also displays or hides SomeClass. The display/hide methods better convey the intent of what happens.