Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

This is for C++ but should apply to any OO language.

Trying to figure out the correct object oriented apporach to do the following (this is what I do in C).

struct Container {
  enum type;
  union {
     TypeA a;
     TypeB b;
  };
}

The type field determines if it TypeA or TypeB object.

I am using this to handle responses coming back from a connection, they get parsed and get put into this structure and then based on the message type the appropriate fields get filled in.

e.g.

struct Container parseResponse(bufferIn, bufferLength);

Is there an OO approach for doing this?

share|improve this question
When you say "correct object-oriented approach," what do you mean exactly? – Robert Harvey Dec 5 '12 at 16:25
What's wrong with what you already have? – James Dec 5 '12 at 16:33
Absolutely nothing, I just did not know if there was a common design pattern used for packet parsing. Was trying to over-do the OO stuff it seems. Back to basics. – RishiD Dec 5 '12 at 18:42

closed as not a real question by gnat, Robert Harvey, MainMa, Walter, BЈовић Dec 5 '12 at 20:48

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, see the FAQ.

1 Answer

You can have abstract parent class and derived classes for each type, and a factory who creates derived class based on type, but returns parent class. But it very depends on what you are trying to fix. If it's not broken do not fix it.

share|improve this answer
1  
+1 for the inheritance usage suggestion. -1 for the "If it's not broken do not fix it" – Joqus Dec 5 '12 at 18:40
And why would you "fix" if it is working? – Dainius Dec 6 '12 at 5:46
Performance, usability, make it easy to maintain... It is not always the case but I have seen monster codebases be born with this mentality. – Joqus Dec 6 '12 at 12:20
I'm not big fan of refactoring code when no one actually needs that. But if it starts getting hard to maintain (decrease performance etc) then it is "broken" so you need to "fix" it, requirements change over time, so if it was working correctly yesterday, does not mean it will correctly tomorrow. Don't fix if it's not broken means, that no one should rewrite production code just because he/she have nothing to do. – Dainius Dec 6 '12 at 14:51
This is your understanding of this sentence but is not the point of view of many people that I have worked with. – Joqus Dec 6 '12 at 16:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.