Kaynağa Gözat

Got rid of the switch/case in JsonValue

Benoît Blanchon 11 yıl önce
ebeveyn
işleme
81f7849c26
2 değiştirilmiş dosya ile 37 ekleme ve 38 silme
  1. 17 19
      JsonGeneratorTests/JsonValue.cpp
  2. 20 19
      JsonGeneratorTests/JsonValue.h

+ 17 - 19
JsonGeneratorTests/JsonValue.cpp

@@ -6,27 +6,25 @@
 #include "JsonValue.h"
 #include "JsonObjectBase.h"
 
-void JsonValue::writeTo(StringBuilder& sb)
+void JsonValue::writeBooleanTo(StringBuilder& sb)
 {
-    switch (type)
-    {
-    case JSON_STRING:
-        sb.appendEscaped(content.string);
-        break;
+    sb.append(content.boolean ? "true" : "false");
+}
 
-    case JSON_NUMBER:
-        sb.append(content.number);
-        break;
+void JsonValue::writeNumberTo(StringBuilder& sb)
+{
+    sb.append(content.number);
+}
 
-    case JSON_BOOLEAN:
-        sb.append(content.boolean ? "true" : "false");
-        break;
+void JsonValue::writeObjectTo(StringBuilder& sb)
+{
+    if (content.object)
+        ((JsonObjectBase*) content.object)->writeTo(sb);
+    else
+        sb.append("null");
+}
 
-    case JSON_OBJECT:
-        if (content.object)
-            ((JsonObjectBase*)content.object)->writeTo(sb);
-        else
-            sb.append("null");
-        break;
-    }
+void JsonValue::writeStringTo(StringBuilder& sb)
+{
+    sb.appendEscaped(content.string);
 }

+ 20 - 19
JsonGeneratorTests/JsonValue.h

@@ -18,50 +18,51 @@ public:
     }
 
     JsonValue(const char* value)
-        : type(JSON_STRING)
+        : implementation(&JsonValue::writeStringTo)
     {
         content.string = value;
     }
 
     JsonValue(double value)
-        : type(JSON_NUMBER)
+        : implementation(&JsonValue::writeNumberTo)
     {
         content.number = value;
     }
 
     JsonValue(bool value)
-        : type(JSON_BOOLEAN)
+        : implementation(&JsonValue::writeBooleanTo)
     {
         content.boolean = value;
     }
 
     JsonValue(JsonObjectBase& value)
-        : type(JSON_OBJECT)
+        : implementation(&JsonValue::writeObjectTo)
     {
         content.object = &value;
     }
 
-    void writeTo(StringBuilder& sb);
-
-private:
-
-    enum Type
+    void writeTo(StringBuilder& sb)
     {
-        JSON_STRING,
-        JSON_NUMBER,
-        JSON_BOOLEAN,
-        JSON_OBJECT,
-    };
-
+        // handmade polymorphism
+       (this->*implementation)(sb);
+    }
+    
+private:
+    
     union Content
     {
-        const char*     string;
-        double          number;
         bool            boolean;
+        double          number;
         JsonObjectBase* object;
+        const char*     string;
     };
 
-    Type    type;
     Content content;
-};
 
+    void (JsonValue::*implementation)(StringBuilder& sb);
+
+    void writeBooleanTo(StringBuilder& sb);
+    void writeNumberTo(StringBuilder& sb);
+    void writeObjectTo(StringBuilder& sb);
+    void writeStringTo(StringBuilder& sb);
+};