Home > Software design >  How can I create a variable / property to pass in the same arguments to every method?
How can I create a variable / property to pass in the same arguments to every method?

Time:06-10

I'm creating a switch statement that calls different methods for each case. The caveat is, the methods all take in the exact same arguments, so I find myself duplicating code. It isn't possible to combine these methods either - as they all instantiate unique xml backing instances.


switch(account){

          case "25":
            getAccount25(name, address, location, accountID, business)
            break
          case "26":
            getAccount26(name, address, location, accountID, business)
            break
          case "27":
            getAccount27(name, address, location, accountID, business)
            break
          case "28":
            getAccount28(name, address, location, accountID, business)
            break
          case "29":
            getAccount29(name, address, location, accountID, business)
            break

Is there a way to avoid duplicating (name, address, location, accountID, business) for each method call?

CodePudding user response:

why don't you just go like this :

getAccount(account, name, address, location, accountID, business);

and then handle it inside your method ?

CodePudding user response:

why don't you just declare the variables (name, address, location, accountID, business) inside the class (as an instance variable) but outside the method. Then just call the methods with no entry argument.

switch(account){

      case "25":
        getAccount25();
        break;
      case "26":
        getAccount26();
        break;
      case "27":
        getAccount27();
        break;
      case "28":
        getAccount28();
        break;
      case "29":
        getAccount29();
        break;
}

The methods can use the variables as long as they are in the same class. If you are declaring the methods in another class, make the variables "public static".

  • Related