Code Poetry
and Text Adventures

by catid posted (>30 days ago) 9:23pm Sat. Oct 1st 2016 PDT
I've been building helper classes with a certain structure these days and it's paid off:

(1) Encapsulate all the class state in a separate struct with default values for all the state members
(2) Give the state object a Json serializer
(3) Reset the state with MyState = StateT(); in the class
(4) Return the state with a getter instead of providing lots of accessors

The wins are that it's really hard to forget to initialize or re-initialize something and for debugging it's really easy to dump the whole object state to a log file or telemetry

Rough example:

struct EGLState
{
   EGLDisplay Display      = EGL_NO_DISPLAY;
   EGLContext Context      = EGL_NO_CONTEXT;

   std::string ToJson() const
   {
      std::ostringstream ss;
      ss << "{\"Display\":" << (int)Display;
      ss << ",\"Context\":" << (int)Context << "}";
      return ss.str();
   }
};

class EGLContext
{
public:
   EGLContext() {}
   ~EGLContext()
   {
      Destroy();
   }

   void Create(EGLContext* from = nullptr);
   void Destroy();

   EGLState GetState() const { return State; }

protected:
   EGLState State;
};

bool EGLContext::Create(EGLContext* fromContext)
{
   Destroy();
...
   EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
   if (EGL_NO_DISPLAY == display)
   {
      Logger.LogError("Create::eglGetDisplay failed: ", GetLastEGLErrorString(), " State:", State.ToJson());  <== can easily serialize the state
      DEBUG_BREAK; /* Should never happen */ return false;
   }
   State.Display = display;
...
}

void EGLContext::Destroy()
{
...

   State = StateT();
}