What is the ideal way to return a status code or complex object in C #?

I am trying to figure out how best to deal with the following scenario. I have a server that receives messages, processes them, and then sends responses to the client. I want the step to processingreturn detailed information about the processing results and about the object in some cases.

I have code like the following:

public void HandleMessage(Connection conn, Packet packet) {
    var somedata = packet.Read();
    var result = Process(somedata);

    if (result == typeof(Message))
        SendA(result);

    if (result == typeof(MyObject))
        SendB(result, extraInfo);
}

public [what goes here] Process(object data) {
    if (validated)
        return data;
    else
        return Message.Failed;
}

I want to do a separation of duties.

  • Receiver: analyzes data in significant objects
  • Processor: acts on the analyzed data and returns a status code or object.
  • Sender: interprets the returned data from the processor (s), creates a packet and sends it to the client.

What design should be attempted to achieve something similar?

+4
1

typeof() is:

if (result is Message)

, packet.Read() :

public StateResult
{
     public StateResultEnum Result;
     public IDataObject Data;
}

IDataObject , , .

:

public interface IDataObject
{
    string GetData();
}

public Message : IDataObject
{
     public string Contents;

     public Message(string contents)
     {
         Contents = contents;
     }
     public string GetData()
     {
         //Convert the string to json
         return json;
     }
}

public MyObject : IDataObject
{
     public string Contents;
     public string ExtraInfo;

     public MyObject(string contents, string extraInfo)
     {
         Contents = contents;
         ExtraInfo = extraInfo;
     }
     public string GetData()
     {
         //Convert the string to json (And include extraInfo)
         return json;
     }
}

: object . , IValidatable, Validate(). IValidatable , , ( MyObject, Message), , . , obj.ExtraInfo - , obj.Validate().

+4

Source: https://habr.com/ru/post/1679765/


All Articles