Is it better to create a library with several functions or create classes?

I am developing software to communicate with the device.

The software will send commands to the device. The device should respond using the protocol below:

<STX><STX><COMMAND>[<DATA_1><DATA_2>...<DATA_N>]<CHKSUM><ETX>

Where:

<STX> is the Start of TeXt (0x55);
<COMMAND> can be 0x01 for read, 0x02 for write, etc;
<DATA> is any value;
<CHKSUM> is the checksum;
<ETX> is the End of TeXt (0x04).

So, I have to check the received data.

Then the received data:

  • cannot be empty;
  • must have 3 or more characters;
  • must have a title in the first two characters of the string data;
  • must have a “footer” in the last character of the string data;
  • must have a valid CheckSum.

If the answer is correct, I can process the data. But before I have to extract this data from the received answer.

Well, this is a relatively simple task. I used to do this on a procedural basis, using only one function and putting a lot of if.

, , .

, "ValidateReceivedData", , ? "IsReceivedDataValid", , ?

, , ?

unit test.

, , . , , . , , , , , .

+3
3

, , - . :

ProtocolParser :

  • SerialPort
  • OnByteReceived, ( , Unknown, Stx1Received, Stx2Received,..., CkSumReceived).
  • Packet, . PacketReceived, Packet .
  • , BadDataReceived (, /).

Packet :

  • / Command Data.
  • , .

. , SerialPort (.. ProtocolParser IDataSource SerialPort).

, PacketReceived ProtocolParser.

+2

, .
, , 2 :

, Executer .

Message . , :

STX

DATA
ChkSum
ETX

Executer Message .

+1

, Yochai, :

  • : , Enum, Command.Read .., "", 0x01 0x02.
  • : (POJO/POCO/), . :
    • ( , )
    • : . , , .
  • MessageParser: , . , ( ), .
  • MessageExecutor: Message , .

(Message), , . , , , XML JSON, MessageParser , , .

It also simplifies unit testing because you can test the message analyzer independently of the artist. First check the message parser by calling the parsing function and examining the received message object. Then check the worker by creating the Message object and verify that the appropriate action has been taken.

+1
source

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


All Articles