### GameDev Marketplace

#### Women's i.make.games T-shirt

$20$15

### Image of the Day Submit

IOTD | Top Screenshots

## Structure of classes in good Game Engine?

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

46 replies to this topic

### #21krippy2k8  Members

Posted 19 June 2012 - 01:21 AM

They have to use a different logger implementation for retail builds. It could just swallow/ignore log entries (and probably would ignore/disable a lot of logging channels), or pipe them to the game's console (maybe colouring channels), or a text file inside %appdata%, etc... You don't need to inherit an interface or anything to do this, a simple ifdef to select different implementations is often good enough.

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 like:

class ILogChannel
{
public:
virtual void open(){}
virtual void close(){}
virtual void log( const LogMessage& msg ) = 0;
};

and is responsible only for outputting the log message object. 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. All about flexibility. If you want to use an external debugging tool, the game/application can even detect the presence of the tool when it starts up and add a SocketLoggingChannel if the tool is running, or a FileLoggingChannel if it's not. Then you can pass the same build around to different machines without having to recompile or distribute the debugging tool (or just use a config file).

I would also like to point out that opening/closing files on every log entry as a way of flushing the buffers is a little silly. Unless you're using something like std::fstream that uses it's own internal stream buffer, you usually don't need to worry about a process crash; OS disk buffering is typically done via a system write-through cache that exists outside of the process space, so only a hard system crash/power failure would compromise the buffered data (and opening/closing a file does not force the data from the cache to the device anyway.) Even in cases where there is no system write-through cache, you can typically flush a buffer with much less overhead than open/close on every write.

Edited by krippy2k8, 19 June 2012 - 01:28 AM.

### #22ChristerSwahn  Members

Posted 19 June 2012 - 01:33 AM

Interesting discussion to follow as a Java developer. Are the logging conventions in C++ really that diverse? For Java there is almost a de-facto standard for logging, and in all the cases I've seen it used it's simply through a static member in each class, e.g.:

public class StdPlayerCreator implements PlayerCreator {
public static final Logger LOG = Logger.getLogger(StdPlayerCreator.class);
...

LOG.error("Internal error, failed to find a settlement");

The parameter to getLogger() is effectively just a hierarchical label. It allows you to configure the logging output threshold on a class or package hierarchy. (This configuration is in a separate XML.)

Yes the above would break if multiple "runs" which should have distinct logs are run in the same JVM (java process). However that is rare and the logger can be instantiated differently for such use cases.

(Sorry for the tangential comment... ;-) )

### #23LorenzoGatti  Members

Posted 19 June 2012 - 01:33 AM

That still raises the obvious question: why is your logger an object/class to begin with?

Specifically, client code wants to log a message, not to "Get" a Log instance, worry about Log references, and still have to call Log methods to do something useful. Free functions are clearly the best fitting API for logging; static variables can also be used with functions and classes can be used behind the scenes, so nothing is lost from a technological standpoint.

Omae Wa Mou Shindeiru

### #24krippy2k8  Members

Posted 19 June 2012 - 02:38 AM

Specifically, client code wants to log a message, not to "Get" a Log instance, worry about Log references, and still have to call Log methods to do something useful. Free functions are clearly the best fitting API for logging; static variables can also be used with functions and classes can be used behind the scenes, so nothing is lost from a technological standpoint.

Unless you want to log something other than simple strings. What if you want to log other values as well? You could use a printf-style log function, but then you lose type safety and must spend time generating an appropriate format string, and hope that the type of a variable never changes... with the possibility that your logging will itself cause a crash or bug! Or you would need to generate the string some other way before calling your log function.

Or you could do something like:

Logger::warning(__FILE__,__LINE__) << "foo is out of expected range: " << foo << endlog;

or use a macro to eliminate some of the dirty work, and just do something like this:
WARNING << "foo is out of expected range: " << foo << endlog;

or even (my preference):
cs_warn( "foo is out of expected range: ", foo );

which makes adding logging much more pleasant, while maintaining type safety.

You could also generate a whole crapload of templated free functions to accomplish something similar, but that makes things a little more difficult when you need to mix integral types with user-defined types, and is generally quite a bit less flexible overall.

Edited by krippy2k8, 19 June 2012 - 02:52 AM.

### #25Cygon  Members

Posted 19 June 2012 - 04:28 AM

My opinion:
• Using globals is always wrong. They create a mess with initialization ordering, threading and dependencies.
• A free function would open the door for dozens of globals. Enable/Disable logging to OutputDebugString() - you need a global flag. Write log to a file? You need another global flag and a global variable storing the file handle.
• Singletons, global variables in disguise, rob you of all flexibility (like logging networking related stuff in file 1 and graphics related stuff in file 2) and gets in the way of unit testing.
• 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).

The way you're doing it (constructor injection) is quite alright, though I agree that having to pass your logger everywhere you want to create an instance of class X tends to have a negative impact on usability and adds complexity to the interface.

Some other options:
• Equip your classes with a SetLogger() method. By default, the logger is NULL, therefore no logging is performed. If you want to log something, you simply assign the logger to the class post construction.
• Do not add logging to your classes directly, wrap them in a logging wrapper (eg. a LoggedRenderer around your Renderer). Obviously can only log calls and results and with some effort exceptions leaving the renderer.
• Add a Log event (as in signals/slots) to your class. This is just another variant of the SetLogger() idea, of course.
• 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.

Edited by Cygon, 19 June 2012 - 04:35 AM.

Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.

### #26metsfan  Members

Posted 19 June 2012 - 08:28 AM

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

### #27Hodgman  Moderators

Posted 19 June 2012 - 08:46 AM

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

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, 19 June 2012 - 08:49 AM.

Posted 19 June 2012 - 08:55 AM

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, 19 June 2012 - 08:58 AM.

### #29MichaBen  Members

Posted 19 June 2012 - 11:59 AM

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.

### #30sss_abaker  Members

Posted 19 June 2012 - 01:30 PM

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, 19 June 2012 - 01:33 PM.

### #31sss_abaker  Members

Posted 19 June 2012 - 01:40 PM

• 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.

### #32Narf the Mouse  Members

Posted 19 June 2012 - 07:20 PM

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.

### #33Álvaro  Members

Posted 19 June 2012 - 08:01 PM

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:
• 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).
• 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, 19 June 2012 - 08:02 PM.

### #34krippy2k8  Members

Posted 19 June 2012 - 11:04 PM

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.

### #35web383  Members

Posted 20 June 2012 - 12:40 PM

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.

### #36Khatharr  Members

Posted 20 June 2012 - 01:44 PM

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, 20 June 2012 - 01:56 PM.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

### #37krippy2k8  Members

Posted 20 June 2012 - 09:33 PM

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.

Posted 21 June 2012 - 07:05 AM

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.

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.

### #39NEXUSKill  Members

Posted 21 June 2012 - 07:18 AM

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.
Game making is godlike

### #40mancubit  Members

Posted 21 June 2012 - 08:23 AM

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.

Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.