This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

Reason for union with one member in generic_onoff_client.h?

In the light_switch example of nRF5_SDK_for_Mesh_3.1.0, I noticed that generic_onoff_client.h has a union for holding the current message packet. However, there is only one member of type generic_onoff_set_msg_pkt_t in the union.

What is the reasoning for this? Isn't a union with one member the same as a struct with one member? Why would I use a union over a struct in this situation?

// generic_onoff_client.h:
/** Union for holding current message packet */
typedef union
{
    generic_onoff_set_msg_pkt_t set;
} generic_onoff_client_msg_data_t;


// generic_onoff_messages.h:
/** Message format for the generic_onoff Set message. */
typedef struct __attribute((packed))
{
    uint8_t on_off;                                         /**< State to set */
    uint8_t tid;                                            /**< Transaction number for application */
    uint8_t transition_time;                                /**< Encoded transition time value */
    uint8_t delay;                                          /**< Encoded message execution delay in 5 millisecond steps */
} generic_onoff_set_msg_pkt_t;

Parents
  • Its difficult to say for sure without looking at the code, but in my experience, whenever I have a datatype that could possibly store more than one type of payload, I put it in a union even if the current implementation only has one type. This makes it easier to extend later, and the presence of a union says a decent amount about how the structure is supposed to be used.

    this occurs most often with msg types, since there is often more than one type of message that needs to be sent. You dont want the next developer to have to refactor anything (e.g. create a new union) in order to add a new message type. Extensibility is key. 

Reply
  • Its difficult to say for sure without looking at the code, but in my experience, whenever I have a datatype that could possibly store more than one type of payload, I put it in a union even if the current implementation only has one type. This makes it easier to extend later, and the presence of a union says a decent amount about how the structure is supposed to be used.

    this occurs most often with msg types, since there is often more than one type of message that needs to be sent. You dont want the next developer to have to refactor anything (e.g. create a new union) in order to add a new message type. Extensibility is key. 

Children
No Data
Related