Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

c++ - What design pattern should I use to reduce the number of method arguments?

I'm developing a networking library in C++. I have a method that sends a network packet. Signature:

void Send(PacketId packet_id,
          const UserPacket& user_packet,
          const std::shared_ptr<RemoteSystem>& remote_system,
          bool broadcast,
          std::function<void(Packet* p)>&& response_callback,
          uint32_t response_timeout,
          std::function<void()>&& response_timeout_callback,
          uint32_t response_to_packet);

Arguments:

  • packet_id - Packet id
  • user_packet - User packet data
  • remote_system - remote system to send a packet
  • broadcast - broadcasting mode. if true - sends to all connected systems excluding remote_system
  • response_callback - waits for the response to the sent packet
  • response_timeout - waiting for the response timeout in milliseconds
  • response_timeout_callback - callback that will be called when response timed out
  • response_to_packet - ID of a received packet to respond to

Have bigger than 3 arguments it's a bad practice. So, how can I design my code better? What design pattern can you advise me? Thanks in advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can group them into a structure or container class. Pass the pointer to this structure or class to function. The class would be more appropriate as it can encapsulate the data within more appropriately and how the values within the class could be updated can be controlled.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...