I'm looking for the best way to accomplish the following:
Background
I have a based class with a request() virtual method with different subclasses provide alternate implementations of performing the requests. The idea is I'd like to let the client instantiate one of these subclasses and pass in one of these objects to a subsystem which will call request() when it needs to. The goal is to let the client decide how requests are handled by instantiated the desired subclass.
Problem
However, if a certain subclass implementation is chosen, it needs a piece of information from the subsystem which would most naturally be passed as an argument to request (i.e. request(special_info);). But other subclasses don't need this. Is there a clean way to hide this difference or appropriate design pattern that can be used here?
Thanks
Make the base request() method take the information as argument, and ignore the argument in subclass implementations that don't need it.
Or pass the SubSystem instance itself to the handler, and let the handler get the information it needs from the SubSystem (and ignore it if it doesn't need any information from the SubSystem). That would make the design more extensible: you wouldn't need to pass an additional argument and refactor all the methods each time a new subclass needing additional information is introduced.
JB Nizet's suggestion is one possible solution - it will certainly work.
What worries me a little is the rather vague notion that "some need more information". Where does this information come from, what decides that? The general principle with inheritance is that you have a baseclass that does the right thing for all the objects. If you have to go say "Is it type A object or type B object, then do this, else if it's type C object do something slightly different, and if it's type D object, do a another kind of thing", then you're doing it wrong.
It may be that JB's suggestion is the right one for you, but I would also consider the option that "special_info" can be passed into the constructor, or be fetched via some helper function. The constructor solution is a sane one, because at construction time, obviously, you need to know if something is a A, B, C or D object that you are creating. The helper function is a good solution some other times, but if it's used badly, it can lead to a bit of a messy solution, so use with care.
Generally, when things end up like this, it's because you are splitting the classes up "the wrong way".
Related
Edit: TL;DR
I guess my main problem is I don't know how to store a list of functions that all take one argument, where the argument type is different between each function, but always extends from EventBase, for calling later.
i.e: EventChild extends from EventBase. A function with the signature
<void (EventChild&)>
will not fit into a variable of type
std::function<void(EventBase&)>
How do I store functions like this, knowing that a user shouldn't have to modify the class where they are stored each time they create a new event extending from our EventBase class?
Note: I had previously been told I could use a dynamic_cast to accomplish this. I have been trying to do exactly that, but it hasn't been working. I imagine for that to work I would have to use pointers somehow, but I am new enough to C++ that I'm not sure how to do it. Maybe that should be the starting point?
One of the problems with dynamic casting pointers I have been having is 'I can convert a pointer of type:
(Subbscriber*)(getDemoEvent(EventDemo&)
to type:
void(EventBase&)
or something along those lines. (not at my computer right now to try it)
This is obviously a problem limited to member functions, I assume.
I recently posted a question on here with the intention of solving an issue for a C++ Event system based on a "Publisher->Dispatcher->Subscriber" pattern. I don't know the exact name of this pattern, but I hear that it is a variant on the Observer pattern with an added "middle-man."
I have been trying to get this system to work for a while now and I am completely stuck. It was suggested in the comments of the previous question that for what I was trying to accomplish, my program layout is incorrect. This is very likely the case since I had been researching other event systems that were close to what I am after trying to modify them for use they were unintended for. So I figured I would describe what I am after, and ask the more general question of "How would you go about structuring and creating this?"
So here is my general idea of how the system should be laid out and how it should operate in a basic example:
Starting with the idea of 5 different files (plus headers and maybe some subclasses):
main.cpp
dispatcher.cpp
publisher.cpp
subscriber.cpp
eventbase.cpp
publishers and subscribers could be anything, and they only serve as an example here.
The first order of business would be to create an instance of our Dispatcher class.
Following that, we create instances of our publisher/subscriber classes. These 2 classes could be a part of the same file, different files, multiples of each, or not event be classes at all but simply free functions. For the sake of simplicity and testing, they are 2 separate classes that know nothing about each other.
When these 2 classes are created, they should be passed a reference or pointer to our dispatcher instance.
This is easy enough. Now let's get to how you should use the system.
A user of the system should be able to create a class that inherits from our EventBase class. Ideally, there should be no requirement on variables or functions to override from the base class.
Let's say we have created a new event class called EventDemo, with a public const char* demoString = "I am a Demo Event";.
From our subscriber class, we should be able to tell our dispatcher that we want to listen for and receive some events. The syntax for doing so should be as simple as possible.
Lets create a member function in our subscriber that looks like this:
void Subscriber::getDemoEvent(const EventDemo &ev) {
std::cout << ev.demoString;
}
Now we need a way to bind that member function to our dispatcher. We should probably do that in our constructor. Let's say that the reference to our dispatcher that we passed to our subscriber when we created it is just called 'dispatcher'.
The syntax for subscribing to an event should look something like this:
dispatcher->subscribe("EventToSubTo", &getDemoEvent);
Now since we are in a class trying to pass a member function, this probably isn't possible, but it would work for free functions.
For member functions we will probably need and override that looks like this:
dispatcher->subscribe("EventToSubTo", &Subscriber::getDemoEvent, this);
We use 'this' since we are inside the subscribers constructor. Otherwise, we could use a reference to our subscriber.
Notice that I am simply using a string (or const char* in c++ terms) as my "Event Key". This is on purpose, so that you could use the same event "type" for multiple events. I.E: EventDemo() can be sent to keys "Event1" and "Event2".
Now we need to send an event. This can be done anywhere we have a reference to our dispatcher. In this case, somewhere in our publisher class.
The syntax should look something like this to send our EventDemo:
dispatcher->emit("EventToSubTo", EventDemo());
Super simple. It's worth noting that we should be able to assign data to our event through it's constructor, or even template the event. Both of these cases are only valid if the event created by the user supports it.
In this case, the above code would look something like this:
dispatcher->emit("EventToSubTo", EventDemo(42));
or
dispatcher->emit("EventToSubTo", EventDemo<float>(3.14159f));
It would be up to the user to create a member function to retrieve the data.
OK, so, all of that should seem pretty simple, and in fact, it is, except for one small gotcha. There are already systems out there that store functions in a map with a type of .
And therein lies the problem...
We can store our listener functions, as long as they accept a type of EventBase as their argument. We would then have to type cast that argument to the type of event we are after. That's not overly difficult to do, but that's not really the point. The point is can it be better.
Another solution that was brought up before was the idea of having a separate map, or vector, for each type of event. That's not bad either, but would require the user to either modify the dispatcher class (which would be hard to do when this is a library), or somehow tell the dispatcher to "create this set of maps" at compile time. That would also make event templating a nightmare.
So, the overly generalized question: How do we do that?
That was probably a very long winded explanation for something seemingly simple, but maybe someone will come along not not know about it.
I am very interested to hear thoughts on this. The core idea is that I don't want the 2 communicators (publisher and subscriber) to have to know anything about each other (no pointers or references), but still be able to pass arbitrary data from one to the other. Most implementations I have seen (signals and slots) require that there be some reference to each other. Creating a "middle-man" interface feels much more flexible.
Thank you for your time.
For reference to my last question with code examples of what I have so far:
Store a function with arbitrary arguments and placeholders in a class and call it later
I have more samples I could post, but I think it's highly likely that the structure of the system will have to change. Waiting to hear thoughts!
Lets say I have a Actor type, which can be any placeable object on my Game Level.
I also have Unit which is a child class of Actor. A Unit can be either a player or a AI controlled hero.
And Unit also got 2 child classes: Player (the player) and Hero (AI controlled unit).
In the Unit class, there will be movement info, rotation, and other general settings which will be needed for both Player and Hero. In the child classes AI will have different and more functions than the player.
Right now I'm facing the following problem:
A function only accepts Actor as parameter (e.g. OnOverlap(Actor a*))
but OnOverlap() should only do something if it is a Unit class (hero or player).
Therefore I would need something like instanceof() from Java in C++.
A workaround would be either to use dynamic_cast, but I'm not sure if thats a good idea for performance. Or use virtual, but this won't work when Hero has more functions than Player.
Or should I attempt a whole new OOP design?
I'd say that a dynamic_cast is code smell. Not necessary bad per se, but a sign that something might be going wrong with your design.
One of the important concepts in OOP is polymorphism: the idea that objects behave differently depending on their type, and that this behavior is encapsulated, hidden behind an interface. If you explicitely check the type of an object to change the logic you want to apply to it, then you're violating polymorphism.
Now virtual methods aren't that great either, they indeed incur runtime costs, and can sometimes bring too much complexity to the table. C++ makes virtual methods the exception, not the default, I believe for these very reasons.
One thing you should know is that virtual methods are only one kind of polymorphism, called dynamic polymorphism. There's another way to get different behaviors depending on a type that is less impeding for the runtime: static polymorphism, AKA template metaprogramming. But this isn't really helping on the complexity side.
Now what you really should do in this case is treat separate things separately. You probably want to have this OnOverlap() method on Units for a reason: let's say you're doing collision check on Units only, not all Actors. Then maintain a separate list of Units, and have that OnOverlap() method non-virtual on the Unit class. Thinking this way is often key.
This technique is called Run-Time Type Information (RTTI), and checking if the output of a dynamic_cast is NULL is a valid implementation.
Another method is to #include <typeinfo> and use typeid(*a).name() to get the string name of a's type.
The need to use dynamic_cast is often (though not always) a sign that you have a design flaw. In this case, I think you do.
Without further comment on the overall design of the architecture you've described, I would say using virtual methods is the right approach. Have OnOverlap takes it's actor and call an OnOverlapped method on the actor, perhaps giving it a pointer to the thing executing the initial OnOverlap method (it's not clear from your question what that is(*)).
void X::OnOverlap (Actor * actor) {
actor->OnOverlapped(this);
}
OnOverlapped is itself virtual. This allows you to "do the right thing" in the case of an actor unit, but do nothing or some other default behavior everywhere else. You are correct that in this case that means you can only work with the public API of Actor. You'd have to move anything requiring Player's additional methods into the Player implementation of OnOverlapped. If you really think you cannot do that for some reason, you should perhaps consider an alternative design at a higher level (and may need to edit your question to provide more details about your architecture).
(*) My initial read of your question made me think OnOverlap is not a method of Actor already; that it was part of something unrelated. If it is part of Actor, you may be instead interested in a pattern called double dispatch, which can be used for this sort of "collision handling" type of problem, and is also a technique using dynamic dispatch (virtual)).
These function is predefined by my Engine, where the parameter must
but the parent function "Actor". So if any Actor collides with the
Mesh, the function is called. In this case for me i see no other
solution, than getting the instance of the Actor object to know if its
a player of just something else
A simple virtual function in the Actor base class can be a noop. Override it in Unit class, and specialize it even more in Hero and Player if needed. Non-Unit Actor's will call an empty method. Cleaner than RTTI and the instanceof idiom.
It is ok to have a default base implementation that expects to be overridden by specialized descendants. That is the point of abstract base classes, except in this case you are providing a default implementation that does nothing. The idea is that you are dispatching the "DoCollision" message (a virtual function in C++). You don't care which classes handle it or how. Just that the object has the DoCollision compile-time "interface" and that you dispatched it correctly.
(This question is more for the people who have access to the book, It's hard to put it into context otherwise)
I've been reading through the GoF's 'Design Patterns' book and there's a sentence that confuses me a little, under 'Creational Patterns->Prototype->Sample code' (page 124).
Near the bottom of the page, there is the implemententation for BombedWall, which as I understand is a concrete prototype, as it inherits from Wall, and redefines the Clone() virtual function. BombedWall also defines another method, HasBomb(), unknown to any clients using the regular Wall interface.
The only way that BombedWall is stored in MazePrototypeFactory (the Prototype client) is as a Wall* (returned from BombedWall::Clone), and the only way to get to HasBomb() afterwards, as far as I understand, is to perform a downcast on that Wall* to a BombedWall* (dynamic or static, depending on whether I know the type), and then I can access the HasBomb() method.
This all seemed fine to me; but then later the author says (same page, last sentence, 2nd last paragraph):
"Clients should never have to downcast the return value of Clone to
the desired type"
What? Then how am I supposed to get to HasBomb()?
I must be missing something...
I gave an answer and totally rewrote it now :)
Basically, the MazePrototypeFactory only knows about the base classes it can use. It doesn't know anything about any of the subclasses you are going to make, but it still should be able to put any possible subclass out there into the maze.
The pattern basically ensures MazeFactory will get a pointer of a type that it understands, Wall, than cause the MazeFactory to need to be modified to be able to produce objects of all the subclasses.
MazeFactory is the client referred to on p 124. It doesn't need to know about HasBomb in order to build the maze.
My guess is that this method only exists to indicate that BombedWall is a different class with extended public interface. Hovewer, this interface is not used in the context of the sample: the maze building algorithm does not differentiate types of walls, while other subsystems (for example, rendering engine) may do so.
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.
I'm writing in second-person just because its easy, for you.
You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code.
So you could derive a new class from it with your one new method and put that code in your 'game' source directory, but maybe there's another option?
So this is probably completely illegal in the C++ language, but you thought at first, "perhaps I can add a new method to an existing class via my own header that includes the 'parent' header and some special syntax. This is possible when working with a namespace, for example..."
Assuming you can't declare methods of a class across multiple headers (and you are pretty darn sure you can't), what are the other options that support a clean divide between 'middleware/engine/library' and 'application', you wonder?
My only question to you is, "does your added functionality need to be a member function, or can it be a free function?" If what you want to do can be solved using the class's existing interface, then the only difference is the syntax, and you should use a free function (if you think that's "ugly", then... suck it up and move on, C++ wasn't designed for monkeypatching).
If you're trying to get at the internal guts of the class, it may be a sign that the original class is lacking in flexibility (it doesn't expose enough information for you to do what you want from the public interface). If that's the case, maybe the original class can be "completed", and you're back to putting a free function on top of it.
If absolutely none of that will work, and you just must have a member function (e.g. original class provided protected members you want to get at, and you don't have the freedom to modify the original interface)... only then resort to inheritance and member-function implementation.
For an in-depth discussion (and deconstruction of std::string'), check out this Guru of the Week "Monolith" class article.
Sounds like a 'acts upon' relationship, which would not fit in an inheritance (use sparingly!).
One option would be a composition utility class that acts upon a certain instance of the 'Engine' by being instantiated with a pointer to it.
Inheritance (as you pointed out), or
Use a function instead of a method, or
Alter the engine code itself, but isolate and manage the changes using a patch-manager like quilt or Mercurial/MQ
I don't see what's wrong with inheritance in this context though.
If the new method will be implemented using the existing public interface, then arguably it's more object oriented for it to be a separate function rather than a method. At least, Scott Meyers argues that it is.
Why? Because it gives better encapsulation. IIRC the argument goes that the class interface should define things that the object does. Helper-style functions are things that can be done with/to the object, not things that the object must do itself. So they don't belong in the class. If they are in the class, they can unnecessarily access private members and hence widen the hiding of that member and hence the number of lines of code that need to be touched if the private member changes in any way.
Of course if you want to access protected members then you must inherit. If your desired method requires per-instance state, but not access to protected members, then you can either inherit or composite according to taste - the former is usually more concise, but has certain disadvantages if the relationship isn't really "is a".
Sounds like you want Ruby mixins. Not sure there's anything close in C++. I think you have to do the inheritance.
Edit: You might be able to put a friend method in and use it like a mixin, but I think you'd start to break your encapsulation in a bad way.
You could do something COM-like, where the base class supports a QueryInterface() method which lets you ask for an interface that has that method on it. This is fairly trivial to implement in C++, you don't need COM per se.
You could also "pretend" to be a more dynamic language and have an array of callbacks as "methods" and gin up a way to call them using templates or macros and pushing 'this' onto the stack before the rest of the parameters. But it would be insane :)
Or Categories in Objective C.
There are conceptual approaches to extending class architectures (not single classes) in C++, but it's not a casual act, and requires planning ahead of time. Sorry.
Sounds like a classic inheritance problem to me. Except I would drop the code in an "Engine Enhancements" directory & include that concept in your architecture.