Quote:Original post by Mybowlcut
Should an assert or exception be used? I've only used exceptions. Could you please explain why you'd prefer an assert?
Exceptions are a tool for error handling. Having two "Singletons" is not really a recoverable error - it is a programming logic error.
Logic errors should never happen in release code, so assert() is usually used to detect them.
Quote:You say when my design changes, but I'm pretty sure it won't. There should only ever need to be one of this object.
I deliberately chose the word "when" to make a point. Design changes. Maybe not this small bit, but in general. My game had only one "World" object in its inception. I could have made it a Singleton and avoided a little parameter passing. Now, I have a situation where two world objects are in memory at the same time. With hindisght, making this a Singleton would have been painting myself into a corner and would have resulted in either a *lot* of refactoring or a much more complicated design to get myself out of it.
I would agree that most of the time you will never need two surface caches. I implement a similar class myself as a global. More precisely, a global pointer to an instance in main(), returned by reference from a function. This gives me the advantage that no extra code runs before main().
IMO, a few well chosen globals can often strike a nice balance between idealistic and pragmatic design. Any more than that and programs tend to suffer as the design can become very inflexible.
Another option might be to try completely hide this behind the surface interface. Caching is an optimisation really, you might be able to come up with a nice interface that doesn't expose the fact that surface pointers are being shared under the hood. Some ideas in his direction would be to either make surfaces immutable or copy on write.
Quote:Also, since this is a global now, how would I go about declaring it in other files? I've never had to use a global across files before haha.. :s
Relevant reading.