Search code examples
oopapiclass-design

Pass class as argument


I have an api method I need to call. It has 10 parameters. I have attempted to make a class that holds all the information the method requires. Can I then simply pass the object into the method?

myAPIMethod(myClass);

Does it work that easily?


Solution

  • No, it doesn't work that way. If a method has 10 parameters, you will have to pass 10 arguments to it.

    If you have control of the API, you can refactor it to accept a single object instead.

    If you don't have control of the API, you can write a method along the lines of

    public void CallAPI(MyClass args)
    {
       myAPIMethod(args.Arg1, args.Arg2); // whatever args are needed for the method
    }
    

    Then your code can use your class and this method to invoke the API. It could be a cleaner approach than invoking the API method directly with 10 arguments in multiple places in your application. But, this depends on what the method is and how you're using it.