6
submitted 1 year ago* (last edited 1 year ago) by Renderwahn@lemmy.world to c/cpp@programming.dev

Recently I end up using structs everywhere as functions parameters to basically get named function parameters and better default arguments. Are there any downsides to this? So far the only annoying thing is to have to define those structs.

struct FunParams{
    int i = 5;
    float f = 3.14f;
    std::string s = "hello";
};

void Fun(const FunParams& params){}

int main(){
    Fun({.s = "hi there"});
}
you are viewing a single comment's thread
view the rest of the comments
[-] lysdexic@programming.dev 2 points 1 year ago* (last edited 1 year ago)

There's a design pattern aptly called Parameter Object.

https://wiki.c2.com/?ParameterObject

Parameter Object is a popular solution for problems such as:

  • Exploding number of function arguments. As a general rule of thumb, if you need to pass more than 3 arguments, you just extract them into a Parameter Object to handle as a single parameter.
  • Combinatorial explosion of test cases. If your function supports multiple input parameters but some combinations of values are invalid/impossible/unsupported (i.e., show/hide window, full screen or windowed or minimized, etc) then instead of wasting time with branch coverage you simply extract a Parameter Object and add validation to it.
this post was submitted on 04 Aug 2023
6 points (100.0% liked)

C++

1732 readers
1 users here now

The center for all discussion and news regarding C++.

Rules

founded 1 year ago
MODERATORS