4 ms·
How does { "type": "huge union of types" } help you here? You still have to read the whole thing as a generic Map just to find the type key and then dynamically
by Spivak 5y ago
How does { "type": "huge union of types" } help you here? You still have to read the whole thing as a generic Map just to find the type key and then dynamically unmarshall to your real object.
Like what even is the return type for parseJSONBlobToOneOfFiftyMessageTypes(String json)? Guess you could return a generic APIMessage and a type object so the caller can cast it but now you're back to playing dynamic games.
- agency 5y agoComing from TypeScript, having an explicit discriminator field (like "type") is a lot easier to deal with[1] (which to be fair is compatible with the last example given in the OP where they have a "type" field and a generic "data" payload field). [1] https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions https://www.typescriptlang.org/docs/handbook/2/narrowing.htm...
- TheCoelacanth 5y agoI don't think it's any easier. Narrowing works the same way with the in operator. If A, B and C each have a single property with the same name: function f(x: A | B | C) { if ('A' in x) { // x is narrowed to A } else { // x is narrowed to B | C } }
- stickfigure 5y agoIn Javaland, Jackson and GSON both have easy ways of deserializing polymorphically based on a type property.