Sign in to follow this  
iLoveGameProgramming

Structure of classes in good Game Engine?

Recommended Posts

metsfan    679
[quote name='Hodgman' timestamp='1340081228' post='4950487']
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).
[/quote]

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 [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]

Share this post


Link to post
Share on other sites
Hodgman    51234
[quote name='krippy2k8' timestamp='1340090513' post='4950505']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[/quote]Do you need an object to do that? That's where the free-function comes in for me.[quote]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:[code]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) //[/code] Edited by Hodgman

Share this post


Link to post
Share on other sites
Madhed    4095
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 this post


Link to post
Share on other sites
MichaBen    481
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 this post


Link to post
Share on other sites
sss_abaker    132
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 this post


Link to post
Share on other sites
sss_abaker    132
[quote name='Cygon' timestamp='1340101692' post='4950531'][list]
[*]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.
[/list]
[/quote]
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 this post


Link to post
Share on other sites
alvaro    21246
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 [url="http://www.youtube.com/watch?v=4F72VULWFvc"]this video[/url].

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:[list=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).
[*]The initialization code, which hooks together the core objects.
[/list]
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 this post


Link to post
Share on other sites
krippy2k8    646
[quote name='Hodgman' timestamp='1340117183' post='4950589']
Do you need an object to do that? That's where the free-function comes in for me.
[/quote]

No, not necessarily.

[quote name='Hodgman' timestamp='1340117183' post='4950589']
I'd prefer to avoid the uneccesary inheritance here and keep your different log back-ends decoupled:
[/quote]

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 this post


Link to post
Share on other sites
web383    804
I found this to be a good read: [url="http://accu.org/index.php/journals/246"]http://accu.org/index.php/journals/246[/url]

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

Share this post


Link to post
Share on other sites
Khatharr    8812
Why the hell are people so terrified of namespaces?

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

[CODE]
//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;
}
[/CODE] Edited by Khatharr

Share this post


Link to post
Share on other sites
krippy2k8    646
[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.
[/quote]

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 this post


Link to post
Share on other sites
Madhed    4095
[quote name='krippy2k8' timestamp='1340249621' post='4951200']
[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.
[/quote]

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 this post


Link to post
Share on other sites
NEXUSKill    475
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 this post


Link to post
Share on other sites
mancubit    536
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 this post


Link to post
Share on other sites
addy914    158
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 :P

Share this post


Link to post
Share on other sites
Narf the Mouse    322
[quote name='mancubit' timestamp='1340288607' post='4951351']
I found the service locator pattern (as described here [url="http://gameprogrammingpatterns.com/service-locator.html"]http://gameprogrammi...ce-locator.html[/url]) a good alternative to the singleton. Its still very global but not that restrictive anymore.
[/quote]
Looks rather useful, and not just as a static variable.

Share this post


Link to post
Share on other sites
Nanook    537
Cygon mentioned it as a anti-pattern though..

[quote name='Cygon' timestamp='1340101692' post='4950531']
[list]
[*]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).
[/list]
[/quote]

Share this post


Link to post
Share on other sites
alnite    3436
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.

[code]MyLogger::log(std::ostream& stream, const std::string& what);[/code]

Done.

Share this post


Link to post
Share on other sites
web383    804
For higher level objects or systems, dependency injection is always an option.

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

Share this post


Link to post
Share on other sites
Cygon    1219
[quote name='mancubit' timestamp='1340288607' post='4951351']
I found the service locator pattern (as described here [url="http://gameprogrammingpatterns.com/service-locator.html"]http://gameprogrammi...ce-locator.html[/url]) a good alternative to the singleton. Its still very global but not that restrictive anymore.
[/quote]

[quote name='Nanook' timestamp='1340319700' post='4951534']
Cygon mentioned it as a anti-pattern though..

[quote name='Cygon' timestamp='1340101692' post='4950531'][list]
[*]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).
[/list]
[/quote]
[/quote]

I had to laugh :)

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 [url="https://github.com/phs/sauce"]sauce[/url] for an example).

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this