Home > Software engineering >  Create an object with specified type after getting special frame in C#
Create an object with specified type after getting special frame in C#

Time:10-09

My preferred language is C# but my question is more abstract and the answer lies in the domain of OOP. I have a user defined protocol over some network. It really does not matter what the protocol or the network are. Just consider that this protocol has a ‘ProtocolRxEventHandler’. When new frame is received, in this handler I interpret what is the contents of the message. Based on the info, I need to create an object from classes ClassA, ClassB or ClassC.

How to choose what kind of object should I instantiate, you might ask. Well... First, in the ProtocolRxEventHandler I call an interpret function which returns an object from ClassBase. Why ClassBase? because received message only contains minimal info which is common between all classes and it is better to convert it to BaseClass. One of the fields in this object defines the type of the final class that needs to be instantiated. So, after interpreting, in a switch statement, based on the type field of the base class I decide which one of the classes A, B or C needs to be created. After creating it, I copy other values from ClassBase and report back to corresponding parts of the code that a new object from A, B or C is created.

I think the switch statement that I used in the ProtocolRxEventHandler smells and can be written in better ways. But I do not know How? Any idea? Maybe there is a way to get rid of the switch statement and let objects construct themselves based on the received frame... I don't know! The main reason I don't like my method is that when a new class is declared, say ClassD, I need to change 2 parts in my code. First declaring the ClassD itself and second, add new actions in the switch statement in ProtocolRxEventHandler.

CodePudding user response:

From what you described, I suspect you can reuse any of existing solutions like ProtoBuf.

However, if you should conjunct with an existing protocol definition (let admit, 80% of them are not perfectly designed), you're perfectly fine with switch statement or any equivalent. Because anyway you need some "criteria X" that can answer to a question "what a type instance should it be".

  • Related