Theoretical Best Practices
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Aug 14 05:40:12 PDT 2015
On 8/14/15 5:21 AM, DarthCthulhu wrote:
> This is more a theoretical exercise than specific code nitty gritty, but...
>
> Let's say I have some code like this:
>
> class World {
>
> // Bunch of members and other functions
>
> void happyDay () {
>
> if (bCthulhuRises) {
>
> debug(logging) {
>
> logger.writeLog(this); // uses the class toString to
> give a dump of interesting parts of the object
> }
>
> throw new Exception("We're doomed! Run you fools!");
>
> }
>
> }
>
> }
>
> I only want to access the logger object when the program is compiled
> with the -debug option, so I don't want to pass it along to the object
> constructor or set a member as a reference to it (which is both tedious
> and pointless if not in -debug mode). The simple solution is to make the
> Logger class a singleton (can D do singletons? I presume it's possible,
> but I haven't really looked into it), but is there a means in D that is
> considered a better way to do this?
I would do it this way:
// at module level
debug(logging) {
Logger logger;
static this() { logger = new Logger;}
}
If you want to have the logger be global, add 'shared' to both the
logger and the static this.
This initializes the data before main() is run, so there is no need for
singletons.
The added bonus here is that you can't accidentally log stuff when
debug(logging) isn't enabled, as the variable will not exist.
-Steve
More information about the Digitalmars-d-learn
mailing list