'idiomatic' porting of c and or c++ code that does NULL checking

bearophile via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 23 03:46:43 PDT 2014


nikki:

> How would you write it?

I don't know how much idiomatic this is, but you can start 
cleaning up the code:
- Renaming the function with something more clear;
- using a D enumeration for the various constants.
- I have used a "." before the module-level variables to denote 
better they are not local;
- I have used an alias and stderror.
- All the code below is untested.


bool initializeSDL()
out {
     assert(.gWindow != null);
     assert(.gScreenSurface != null);
} body {
     alias success = bool;

     if (SDL_Init(SDL.init_video) < 0) {
         stderr.writeln("SDL could not initialize! SDL_Error: ",
                        SDL_GetError);
         return success(false);
     } else {
         .gWindow = SDL_CreateWindow("SDL Tutorial",
                                     SDL.qindowpos_undefined,
                                     SDL.windowpos_undefined,
                                     screen_width,
                                     screen_height,
                                     SDL.window_shown);

         if (.gWindow == null) {
             stderr.writeln("Window could not be created! 
SDL_Error: ",
                            SDL_GetError);
             return success(false);
         } else {
             .gScreenSurface = SDL_GetWindowSurface(.gWindow);
         }
     }

     return success(true);
}



In D error messages are often given by throwing errors, so this 
looks a little more idiomatic:


bool initializeSDL() nothrow
out {
     assert(.gWindow != null);
     assert(.gScreenSurface != null);
} body {
     if (SDL_Init(SDL.init_video) < 0) {
         throw new text("SDL could not initialize: ", 
SDL_GetError).SDL_Error;
     } else {
         .gWindow = SDL_CreateWindow("SDL Tutorial",
                                     SDL.qindowpos_undefined,
                                     SDL.windowpos_undefined,
                                     screen_width,
                                     screen_height,
                                     SDL.window_shown);

         if (.gWindow == null) {
             throw new text("Window could not be created: ", 
SDL_GetError).SDL_Error;
         } else {
             gScreenSurface = SDL_GetWindowSurface(gWindow);
         }
     }
}


If you can add some more function attributes, like @safe.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list