# Structure of classes in good Game Engine?

This topic is 2040 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

That's fine, each style to it's own, but this is still an arbitrary choice by the API designer to use a singleton as a restriction on the end-user developers usage. You could replace the UIApplication singleton by, inside main, making local variables for a window, an event queue, a URL fetcher, etc... and then having the choice weather to make them global variables (e.g. via a singleton) or not, ourselves (i.e. the end-user of the API).

I suppose your right that it's not a requirement that a singleton be used, but at the end of the day, it makes the API easier to use. I'm not saying singletons are the solution to every problem when it comes to needing dependencies throughout your application, but it does make sense from time to time. I am also of the belief that if you are trying so damn hard to not use a particular design pattern that you end up bending over backwards, you should probably take a step back and wonder if you aren't just being a bit evangelical and maybe just maybe that design pattern exists for a reason, and you should stop trying to fight its use in a legitimate use case. I doubt we will ever see eye to eye on this though, so I'm going to gracefully walk away and say, let's agree to disagree

##### Share on other sites
The main logging object handles adding file, line, function info, process and thread IDs, timestamps, possibly even call stacks when logging exceptions/errors, etc, to the message object
Do you need an object to do that? That's where the free-function comes in for me.
I prefer a single logging object with multiple logging channels, where each channel can be of a different type. i.e. a FileLoggingChannel for writing to file, a ConsoleLoggingChannel for writing to the console, a SocketLoggingChannel for sending the logs over the network to an external logging application/server. Each channel type just implements a simple interface[/quote]I'd prefer to avoid the uneccesary inheritance here and keep your different log back-ends decoupled:class SocketLoggingChannel : NonCopyable { public: SocketLoggingChannel(...); ~SocketLoggingChannel(); void log( const char* msg ); }; class ConsoleLoggingChannel: NonCopyable { public: ConsoleLoggingChannel(...); ~ConsoleLoggingChannel(); void log( const char* msg ); }; cosnt char* FormatLogMessage(const char* fmt, ...); typedef std::vector<std::function<void(const char*)>> ChannelVec; #define Log(channels, fmt, ...) do { \ cosnt char* msg = FormatLogMessage(fmt, __VA_ARGS__); \ for (auto &c : channels){ \ c(msg); \ } \ } while(0) // Edited by Hodgman

##### Share on other sites
I am also in the no-need-for-classes camp.
You already have std::cout, std::cerr and std::clog. Why not use them for what they exist?

EDIT: well they are classes... Generally I meant don't overengineer something like that Edited by Madhed

##### Share on other sites
Whether your logger needs to be a separate class or not really depends on if it needs to keep any data. For example a logging system I worked with had the ability to work in combination with the scripting language by capturing all log messages send during the execution of a certain function, making debugging scripts a lot faster as you could visualize where something went wrong. While this did really improve debugging (specially for scripting languages where you can't put breakpoints), in your case I don't think you will need things like that yet. Specially for simple applicatins, simple error output works fine. And if your functions don't need to touch member variables you should make them static, and if your class only has statics they don't need to be in a class.

As for singletons: I have been them being used to death in engines. It's really fun to see the engine being initialized before you even loaded the application because someone is calling the singleton from a static initializer. Even nicer is to clean up the memory on shutdown, you have to explicitly destroy the singleton, only to have somebody still requesting it again, crashing the whole thing to the desktop. But even without these extreme cases, it still is confusing as you don't really know when something is initialized, the flow of your application becomes hidden, which can introduce all kind of hard to debug bugs. Anyway, after having seen this abuse, I kind of decided to avoid them wherever I could. Yeah, you might need to pass some objects around through the constructor more then you want, specially for people with an alergic reaction to constructors. But it does make the flow of your application more clear and helps to reduce bugs because you are forced to initialize things in order or you will not be able to pass a reference to the depending class.

##### Share on other sites
I guess hating on globals is the cool thing to do here. LOL

Standard function call is the way to go. Hell you can even use your Logger class if you want. Except you keep that hidden.

[source lang="cpp"]//basic example yo.
void logMessage(string message) {
static Logger log;

//post log message here using log object.
log.log(message);

}[/source]

This is only really required if Logger keeps any state, such as the file its logging to among other things. Edited by sss_abaker

##### Share on other sites

• Forfeit logging altogether. I've done this in my code. I'm going all-out with assertions for pedantically checking internal states and exceptions for any usage error. Since the point of logging is to help you find the cause of errors quickly, by not letting any inconsistency, bad return code or missing capability slip under the carpet you remove the need for logging.

This is what I do. It's easier to find bugs in the debugger, go figure. And Asserts make your program stop and tell you why IMMEDIATELY. There's no combing through log files to find out why your geometry isn't showing up. Simply add an Assert. You can easily remove asserts from release code when you know your stuff works, by using #define.

##### Share on other sites
Logging is one of the few singletons I have in my game engine, for the simple reason I haven't figured out a sane way to replace it with a non-singleton.

##### Share on other sites
I usually have a function for logging, but I can see the appeal of passing a pointer/reference to a logger to a constructor, because it allows the user of the class to provide any logger they want (a null logger, a logger that prints out to a file, a logger that prints out to stdout, a logger that verifies that the log agrees with some expected text...). This is particularly useful for regression testing.

If you have 38 minutes to burn, consider watching this video.

What I remember from watching it many months ago is that he proposes using polymorphism instead of if statements. The idea is to have two types of code:

1. The core objects, which make use of pointers to base classes for anything they need (the talk uses Java, so the language is a bit different).
2. The initialization code, which hooks together the core objects.

His point is that most if statements in code of type 1 can be beneficially replaced with a polymorphic call, the main benefit being ease of testing.

I am not sure how much I buy this method of development, but I would love to try it sometime. Edited by alvaro

##### Share on other sites

Do you need an object to do that? That's where the free-function comes in for me.

No, not necessarily.

I'd prefer to avoid the uneccesary inheritance here and keep your different log back-ends decoupled:

That's actually very similar to how I used to do it, until I discovered that it's useful to be able to do more than just call "log" from user code. In particular invoking the open and close methods (more importantly the close method) on my logging channels from the logger object, using named channels, dynamically setting named properties on logging channels from configuration dialogs, enumerating channels, dynamically remove channles, etc. The interface that I use isn't exactly as simple as what I posted, but basically all that is necessary to implement is the log method unless the channel wants to expose properties, open/close, or a handful of other functionality. A series of function objects could do the same thing, but that gets quickly gets messy and harder to maintain.

##### Share on other sites
I found this to be a good read: http://accu.org/index.php/journals/246

I haven't personally implemented it, but he addresses several pros/cons in detail.

##### Share on other sites
Why the hell are people so terrified of namespaces?

 //SysLogger.h namespace SysLogger { extern int loggedItems; int initialize(char* somedata, int someother); void logSomething(char* herpderp); }; 

 //SysLogger.cpp #include "SysLogger.h" int SysLogger::loggedItems = 0; static int fd = -1; static int miscHelperFunction() { return foo; } int SysLogger::initialize(char* somedata, int someother) { herpderpSystem = new Foo; fd = herpderpSystem->makeLogFile(); return 4; } void SysLogger::logSomething(char* herpderp) { loggit(fd, herpderp); ++loggedItems; }  Edited by Khatharr

##### Share on other sites

This is what I do. It's easier to find bugs in the debugger, go figure. And Asserts make your program stop and tell you why IMMEDIATELY.

No they don't. They may stop and tell you that you have a bug, but unless your bugs are extremely well behaved and occur directly at the assert site, they can't tell you anything about why you have a bug or where it's at.

##### Share on other sites

[quote name='sss_abaker' timestamp='1340134846' post='4950694']
This is what I do. It's easier to find bugs in the debugger, go figure. And Asserts make your program stop and tell you why IMMEDIATELY.

No they don't. They may stop and tell you that you have a bug, but unless your bugs are extremely well behaved and occur directly at the assert site, they can't tell you anything about why you have a bug or where it's at.
[/quote]

This is partially true. Asserts make sense and should be used extensively. The reason that an assertion fails however can be hidden somewhere else in the code, it could even have happened several frames ago. Also asserts are usually removed from release code which simply crashes the program for your customers without any information. IMHO log files are invaluable tools for bug fixing after release.

##### Share on other sites
Boy am I gonna be yelled at...

Are you adamant you will only have one logger?
Being so it should be available from pretty much everywhere?
Passing around references seems pointless?

So... why not static?

I think you should avoid to overdesign, the simplest solution is usually the best one, if it gets the job done and doesn't impact your development speed, go for it.

##### Share on other sites
I found the service locator pattern (as described here http://gameprogrammingpatterns.com/service-locator.html) a good alternative to the singleton. Its still very global but not that restrictive anymore.

##### Share on other sites
I am not a huge fan of globals but when I am forced to use them, I usually do. The way I indicate if I should use them or not, is if they are used by the whole application and if they are dependencies. If they depend on a class, or a class depends on it, then I will not use it. A good example would be a logger. It does not require anything from other classes, it just holds a few functions and outputs information to a file/console. I most likely wouldn't even make it a class, it would just be a few static functions that I would call. At most, it would probably be two or three global variables.
There is a time where using globals too much can make it a pain to debug, but for a simple logger, it won't be too difficult to debug, especially when it's purpose is to help you debug

##### Share on other sites

I found the service locator pattern (as described here http://gameprogrammi...ce-locator.html) a good alternative to the singleton. Its still very global but not that restrictive anymore.

Looks rather useful, and not just as a static variable.

##### Share on other sites
Cygon mentioned it as a anti-pattern though..

• Passing some semi-global application class around is just hugely increasing dependencies since now you don't know which objects a class will look up through the application class (the service locator anti-pattern).

##### Share on other sites
Seriously, it's just for logging. Don't overengineer and overthink the solution. A thread-safe and simple function is generally sufficient. If you want to log to different outputs (file, network), use FILE structure or std::ostream.

MyLogger::log(std::ostream& stream, const std::string& what);

Done.

##### Share on other sites
yes logging is one thing, but the discussion is also valid for other stuff..

##### Share on other sites
For higher level objects or systems, dependency injection is always an option.

http://martinfowler.com/articles/injection.html

##### Share on other sites

I found the service locator pattern (as described here http://gameprogrammi...ce-locator.html) a good alternative to the singleton. Its still very global but not that restrictive anymore.

Cygon mentioned it as a anti-pattern though..

[quote name='Cygon' timestamp='1340101692' post='4950531']

• Passing some semi-global application class around is just hugely increasing dependencies since now you don't know which objects a class will look up through the application class (the service locator anti-pattern).

[/quote]

Yep, it's widely considered an anti-pattern because the service locator is the equivalent of handing your classes a big box of other objects and letting them go shopping in it.

The dependencies are turned completely opaque since all you see from the outside is a constructor taking a [font=courier new,courier,monospace](ServiceLocator &)[/font] -- you have to rely on the documentation or consult the code to find out what dependencies a class really has. And those may change at any time. Missing dependencies (common scenario: component X adds a new dependency) result in an error at runtime if and when the code consuming the dependency is reached because the compiler can't determine if the service locator will have the required service when it is looked up. Such classes also become dependent on the service locator implementation (whereas dependency injection can happen without the knowledge of the partaking classes, see sauce for an example).