What do I name this class whose sole purpose is to report failure? - c++

In our system, we have a number of classes whose construction must happen asynchronously. We wrap the construction process in another class that derives from an IConstructor class:
class IConstructor {
public:
virtual void Update() = 0;
virtual Status GetStatus() = 0;
virtual int GetLastError() = 0;
};
There's an issue with the design of the current system - the functions that create the IConstructor-derived classes are often doing additional work which can also fail. At that point, instead of getting a constructor which can be queried for an error, a NULL pointer is returned.
Restructuring the code to avoid this is possible, but time-consuming. In the meantime, I decided to create a constructor class which we create and return in case of error, instead of a NULL pointer:
class FailedConstructor : public IConstructor
public:
virtual void Update() {}
virtual Status GetStatus() { return STATUS_ERROR; }
virtual int GetLastError() { return m_errorCode; }
private: int m_errorCode;
};
All of the above this the setup for a mundane question: what do I name the FailedConstructor class? In our current system, FailedConstructor would indicate "a class which constructs an instance of Failed", not "a class which represents a failed attempt to construct another class".
I feel like it should be named for one of the design patterns, like Proxy or Adapter, but I'm not sure which.
EDIT: I should make it clear that I'm looking for an answer that adheres to, ideally, one of the GoF design patterns, or some other well-established naming convention for things of this nature.

To answer your literal question, I'd probably go with ConstructorFailure, as it describes the event of failing.
However, I'd probably go one step further and make it an Exception, in which case ConstructorException doesn't sound too shabby. Any reason you want to return this instead of throwing it?

I'd name it NullConstructor in line with the null object pattern, which is the pattern you're using. See http://en.wikipedia.org/wiki/Null_Object_pattern

Throw an exception. That is If I understand your description correctly and the creation of the IConstructor object is not done asynchronously.
Though if you don't have exceptions available to you I would probably call it ConstructorCreationError. Yes it does convey a failure mode but, more accurately, it is communicating the specific error that occurred. Also, having constructor as the last word, to me, seems to give the wrong meaning, but you could put "constructor" at the end as well.
You could also replace the verb "Creation" with something like SpawnConstructorError, ConstructorGenerationError and or if you're a fan of Dr. Chevalier maybe ErroneousConstructor.

I'd go for DummyConstructor because its only purpose is to simulate a valid Constructor instance, but no real functionality is implemented by it.

FailureResponseConstructor?
You're not creating a failure, you're creating the response to the failure. Thus, I would think any synonym to 'response' or 'respond' would work.

If you willing to spend effort checking returned pointer against the "FailureConstructor", I don't see reason why couldn't you check it against NULL ?
Unless your system is designed to mask component failure from each other, it just doesn't make sense to assume every associated parts are working well.

I'm going to go with something based on Niall C.'s comment -- FailedConstructorProxy. The Proxy pattern seems to fit best with what this class is; though rather than it relaying method calls to an object, it's standing in and generating what we wanted the actual constructor to return.
(If someone has a more correct answer, post it and I'll mark that one as accepted. I'm still not 100% convinced this is the right name!)

Why not create a Failed class to represent a class that failed construction and go with FailedConstructor? This way the naming is consistent.

I would suggest calling this class FailedObjectConstructionHandler which describes what the class does.

Related

How to disable a class API when the class cannot operate under some conditions?

Say I have the following:
class Processor
{
public:
void Activate();
/* some more interface functions*/
};
void main()
{
Processor().Activate();
}
class Processor is just an example of any class that provides public interface.
Problem
What if class Processor is only operational iff some conditions are met. Just for example, class Processor is preforming some file system operations on a directory X and if the directory X does not exist it can't operate at all.
Issue
Who is responsible to validate the conditions are met and the class is operational?
Let's encapsulate evaluating those conditions to one logic function called Enabled()
Suggestion 1 - Caller responsibility
void main()
{
if (Enabled() )
Processor().Activate();
}
In this case, initiator of class Processor is responsible to make sure these condition are met before initiating the class.
Cons
Caller may not know what are the condition
This doesn't resolve the bigger issue, what if we have other callers that don't verify the condition?
Suggestion 2 - Class responsibility
class Processor
{
public:
Processor()
{
// init m_bIsEnabled based on conditions
}
void Activate()
{
if (!m_bIsEnabled)
return;
// do something
}
/* some more interface functions*/
private:
bool m_bIsEnabled;
};
in this case, all public interface functions are disabled if class is not enabled.
Cons
What if class Processor has numerous interface function, do we check the value of m_bIsEnabled in the beginning of each function?
What if in the future some developer enhance the interface and forgets to check the value of m_bIsEnabled?
What are the default values returned in each functions in case m_bIsEnabled == false
Suggestion 3 - Factory
using Processor_ptr = shared_ptr < Processor > ;
class ProcessorFactory
{
static Processor_ptr create()
{
Processor_ptr p;
p.reset(new Processor);
if (!p->IsEnabled())
p.reset(nullptr);
return p;
}
};
class Processor
{
public:
void Activate();
bool IsEnabled();
friend class ProcessorFactory;
private:
Processor();
bool m_bIsEnabled;
};
This method is so far my favorite since we prevent class generation if it cannot operate.
Cons
1. Perhaps an overkill?
Question
Which of the suggestions is preferable in terms of best practice? do we have other suggestions?
I'd go for option number #3, as options #2 & #1 are hard to track and enforces the developer to always validate the Active flag prior each function's execution. moreover, you can expand option #3 by return an empty object which implements the interface but actually does nothing.
I am also a fan of #3 like igalk. But it worth mention that this is a typical situation for the RAII pattern (Resource Acquisition Is Initialization).
You throw an exception when the condition of the instance creation is not met in your constructor:
class Processor
{
public:
Processor()
{
// based on conditions
if(!folderexist) // pseudocode
throw(cannotcreate)
}
// void Activate() not needed anymore
/* some more interface functions*/
private:
// bool m_bIsEnabled; not needed anymore
};
This is a common pattern in libs already using exceptions. I myself have no problems with exception as long as they are used in a proper way. Unfortunately I see often exceptions used as longjumps or as shortcuts to save some lines of code.
A fail can be a valid state of an instance. In this case IMHO it is better to create the instance and have a "valid" flag (case #2). But most time, the created object is worthless and the information of fail is only of interest for the creator. In this case RAII may be the better choice. The factory pattern avoid the exception in an elegant way if you do not want or cannot use exceptions.
Actually, any or all of those strategies can be employed, depending on what code is able to detect the problem.
Generally, though, I would not encourage usage of an "enabled" or "valid state" flag in the object. If a problem is detected, such a flag is an opportunity to continue despite the problem (e.g. forget to check the flag, forget to set the flag, inappropriately ignore the value of the flag). Programmers are human and, as code gets more complicated, it becomes easier to make a mistake that is very hard to track down.
If the caller detects a problem then it should not create the object or (if the object already exists) it should destroy the object. It can then give an indication to its caller of the problem.
If the object itself detects a problem, then it should recover as best as possible, and give an indication to the caller.
Either way, this means that, if the object exists, it remains in a valid state until a problem is detected, and detection of a problem will cause the object not to exist.
What indications need to be given depend on severity of the problem, but include various approaches between an error code (which can be ignored by the caller) and an exception (which must be handled, and the problem corrected, if the program is to continue).
BTW: main() returns int, not void.

Is using an empty base class justified in this example?

I'm writing a Window class which propagates different types of events, listed in
enum Event {WINDOW_ClOSE=0x1, WINDOW_REDRAW=0x2, MOUSE_MOVE=0x4, ...};
to objects which have registered for notification with the window. For each type of event, I have an abstract class which any object must extend in order to allow notification. To react to, say, a MOUSE_MOVE event, my object would inherit from MouseMoveListener, which has a process_mouse_move_event() method which is called by Window. Listening to many events can be combined by extending multiple of these classes, which all inherit from the EventListener base class. To register an object, I would call
void Window::register(EventListener* object, int EventTypes)
{
if(EventTypes&WINDOW_CLOSE)
/* dynamic_cast object to WindowCloseListener*, add to internal list of all
WindowCloseListeners if the cast works, else raise error */
if(EventTypes&MOUSE_MOVE)
/* dynamic_cast object to MouseMoveListener*, add to internal list of all
MouseMoveListeners if the cast works, else raise error */
...
}
This works fine, but my gripe is that EventListener is completely empty and that seems code smelly to me. I know I could avoid this by removing EventListener altogether and having a separate Window::register for each type of event, but I feel that this would blow up my interface needlessly (especially since methods other than register might crop up with the same problem). So I guess I am looking for answers that either say:
"You can keep doing it the way you do, because ..." or
"Introduce the separate Window::register methods anyway, because ..." or of course
"You are doing it all wrong, you should ...".
EDIT:
From the link in Igors comment: What I do above only works if there is at least one virtual member in EventListener for example a virtual destructor, so the class is not technically completely empty.
EDIT 2:
I prematurely accepted n.m.'s solution as one of the type "I'm doing it all wrong". However, it is of the second type. Even if I can call EventListener->register(Window&) polymorphically, Window needs to implement a highly redundant interface (in terms of declared methods) that allows EventListeners to register for selective notification. This is equivalent to my alternative solution described above, only with the additional introduction of the EventListener class for no good reason. In conclusion, the canonical answer seems to be:
Don't do dynamic_cast + empty base class just to avoid declaring many similar functions, it will hurt you when maintaining the code later. Write the many functions.
EDIT 3:
I found a solution (using templates) which is satisfactory for me. It does not use an empty base class any more and it does not exhibit the maintenance problem pointed out by n.m.
object->registerWindow (this, EventTypes);
Of course you need to implement registerWindow for all EventListener heirs. Let them check for event types which are relevant to them.
UPDATE
If this means you need to redesign your code, then you need to redesign your code. Why is it so? Because dynamic_cast is not a proper way to do switch-on-types. It is not a proper way because every time you add a class in your hierarchy, you need to go over and possibly update all switches-by-dynamic-cast in your old code. This becomes very messy and unmaintainable very quickly, and this is exactly the reason why virtual functions were invented.
If you do your switch-on-types with virtual functions, every time you change your hierarchy you have to do... nothing. The virtual call mechanism will take care of your changes.
This is what I ended up doing:
template <int EventType> void register_(EventListener<EventType> Listener)
{
// do stuff with Listener, using more templates
};
It turned out that static polymorphism was better suited for my needs - I just wanted to avoid writing
register_mouse_motion_event(...)
register_keyboard_event(...)
and so on. This approach also nicely eliminates the need for an empty base class.

Passing pointer of calling object (this) as argument to method of another instantiated method in C++

I'm reviewing some code and I have stumbled many times on examples as described in title. THen this passed object is referenced in calling outside methods from second object, even changed somewhere else and then again used by reference in another methods.
THe weirdest thing is that the second object calls methods from passed first object that created second anyway.
I haven't done similar stuff yet, but I since I am relatively new to C++ I allow possibility that people feel very free in coding with language with so many options...
However, the main question is: is that common practice? Is there any technical reason for not doing such stuff?
I have added a short example:
TypeReturned *ClassB::GetSomething( ClassA *objectA)   
{
        someMethod(wm);
        ClassC *objectC = new ClassC(objectA->method());
    PCS->method(……, &objectA->someMethod(), objectA);
}
This method is called from objectA.
First call is quite normal. The second and the third would be more readable to solve with simpe passing needing parameters, not the complete classes and callbacks.
I can also say, that those those 2 classes do not really communicate to each other and don't have cross-references.
Perhaps main question should be divided into more: is this usual and practical workaround to pass itself to another object in C++?
It is both usual and practical. Quite often it's the most natural way to achieve something. For example if you want a parent-child navigable from both ends, it's easiest for the parent object to pass itself (this) to the child object after creation so that it stores the reference to parent. Registering self for callback (as in the observer pattern) is another example.
This is useful in general, not something specific to C++.
AFAIK it's perfectly OK technically and happens all the time. Sometimes it's the "best" way and, believe it or not, the clearest way.
pete
I think (Although, I can't tell and am happy to be shown wrong) that what you are describing is a scheme similair to double dispatch (Example in C#). If I am correct you are seeing calls like:
class LivenessPingMessage : public Message {
public:
void accept(Controller& c) {
c.visit(this);
}
}
class Controller {
public:
handleNetworkQueue() {
while (true) {
Messages::Message* m = networkLayer->getNextMessage();
if (m != NULL) {
m->accept(*this);
}
}
}
void visit(Messages::LivenessPingMessage* m) {
//Do something
}
}
class Message {
public:
virtual void accept(Controller& c) = 0;
}
This allows the class Controller to handle messages by calling the virtual accept() method they have. These messages then use the pointer to Controller they have been given to call the overloaded method visit(Message m).
This means that Messages only need to know about Controllers, not any other details about the tasks they are supposed to complete. The Controller contains all the logic needed to deal with the Message appropriately.
It is common amongst people who like double dispatch and is a recognised design model.

Is it better to take object argument or use member object?

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.

What's the proper "C++ way" to do global variables?

I have a main application class, which contains a logger, plus some general app configurations, etc.
Now I will display a lot of GUI windows and so on (that will use the logger and configs), and I don't want to pass the logger and configurations to every single constructor.
I have seen some variants, like declaring the main class extern everywhere, but that doesn't feel very object oriented. What is the "standard" C++ way to make elements in the main class accessible to all (or most) other classes?
Use the singleton design pattern.
Basically you return a static instance of an object and use that for all of your work.
Please see this link about how to use a singleton and also this stackoverflow link about when you should not use it
Warning: The singleton pattern involves promoting global state. Global state is bad for many reasons.
For example: unit testing.
It is not so bad idea to pass the logger and config to all the constructors if your logger and config is abstract enough.
Singleton can be a problem in the future. But it seams like a right choice in the project begin. Your choice. If your project is small enough - go with singleton. If not - dependency injection.
Why not use the system that's already in place? That is, redirect std::clog to output to a file and write to std::clog.
std::fstream *f = new std::fstream("./my_logfile.log")
std::clog.rdbuf(f->rdbuf());
std::clog << "Line of log information" << std::endl;
I'd agree with some kind of singleton approach. You definitely don't want to pass logger objects around all over the place. That will get very boring very quickly, and IMHO is a worse design than just having a plain global object.
A good test of whether you've got a good solution is the steps required to get the logging working in a function that needs it.
If you have to do much more than
#include "Logger.h"
...
void SomeFunction()
{
...
LOGERROR << "SomeFunction is broken";
...
}
...
then you are wasting effort.
Logging falls under the realm of 'separation of concern' as in aspect orient programming
Generally logging is not a function or concern of an object (for example, it does not change the state of the object; it is merely a mechanism for observing/recording the state, and the output is essentially disposable in most contexts)
It is an ephemeral and often optional side function that does not contribute to the operation of a class.
An object's method may perform logging, but the logging may be done there because it is a convenient place to do it or that point in the code execution stream is where one desires the state to be recorded.
Because C++ does not provide facilities for defining aspects, I tend to simply keep essentially external ephemeral objects like loggers global and wrap them in a namespace to sort of contain them. Namespaces are not intended for containment so this is kind of ugly, but for for lack of anything else it is convenient and is far less ugly and inconvienent than passing loggers in formal parameters or referencing them in all the objects you want to log. This also makes it easier to remove the logger if at some point I decide I no longer need the logger (I.e. if it was only used for debugging).
Don't know if this is helpful in your situation or not, but in MFC, there was/is an application class.
I use to throw things like this into that class.
I assume you are not using MFC, but if you have an application class or something similar, this might be helpful.
Why not use log4cxx?
Such problems are solved long ago and widely used by many.
Unless you're building some very special logging system of your own... In such case, I'd use Factory pattern which would create loggers for anyone interested (or giving away existing instance if it's singleton). Other classes would use factory to obtain the logger. Passing loggers in constructor parameters is a bad idea, because it couples your class with logger.
Why has no one thought of heritage and polymorphism? You could also use an abstract factory with that singleton ;)
Simply pass your main class into the constructor of the other classes that you want to have access to "everything"
Then you can provide access to the logger etc. via member properties.
(Forgive my C++ syntax, this is just a made-up language called "C++ confused by VB")
e.g.
Class App {
Private m_logger;
Private m_config;
Public logger() {
return m_logger;
}
Public config() {
return m_config
}
}
Class Window1 {
New( anApp ) {
}
....
}
I guess Service Locator will do. That you'll have to either pass around in constructors, or have a globally accessible static member function in some well-known location. The former option is much more preferable.
I would avoid the singleton pattern.
Too many problems when it comes to testing and all that (see What is so bad about singletons?)
Personally I would pass the logger etc into the constructor. Alternatively you can use a factory to create/pass a reference to the resource.