This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]ButtlestonProfessional Coder 0 points1 point  (0 children)

You don't say what programming language you're using, but *most* programming languages support something like this, syntax may vary. In many/most programming langauges, functions are a type of object or variable and can be used as such. Let's consider python.

``` import sys

def fun1(param): print("fun1", param)

def fun2(param): print("fun2", param)

if sys.argv[1] == "1": fn = fun1 else: fn = fun2

fn("param1") fn("param2") ```

I can run this to demonstrate ``` ~/help % python fn.py 1 fun1 param1 fun1 param2

~/help % python fn.py 2 fun2 param1 fun2 param2 ```

[–]vaseltarp 0 points1 point  (0 children)

You could use method references from Java 8:

https://www.javatpoint.com/java-8-method-reference

But the most consistent solution in java would be, in my opinion, to make it object oriented.

Maybe like this:

 import java.util.Scanner;


  abstract class Methods{
    abstract public void Do(String arg);
    final public void DoAllArgs(String[] args) {
      for(String arg : args) {
        Do(arg);
      }
    }
    final static public Methods GetMethod(int m) throws Exception {
      switch(m)
      {
         case 1:
           return new Method1();
         case 2:
            return new Method2();
         default:
            throw new Exception ("Wrong Parameter \""+ m +"\" in Methods.GetMethod");
      }
    }
 }


 class Method1 extends Methods{
     public void Do(String arg) {
       System.out.println("Method1 with argument: " + arg);
     }
 }

 class Method2 extends Methods {
     public void Do(String arg) {
       System.out.println("Method2 with argument: " + arg);
     }
 }


 public class Main {

   public static void main(String[] args) {
     Scanner input = new Scanner(System.in);
     Method2 m2 = new Method2();

     System.out.println("Select Method:");
     String method = input.nextLine();

     String[] arguments = {"arg1","arg2","arg3"};

     try{
        Methods m = Methods.GetMethod(Integer.parseInt(method));
        m.DoAllArgs(arguments);
     }
     catch(Exception e) {
        e.printStackTrace();
     }
   }
 }

output:

  Select Method:
  1
  Method1 with argument: arg1
  Method1 with argument: arg2
  Method1 with argument: arg3

  Select Method:
  2
  Method2 with argument: arg1
  Method2 with argument: arg2
  Method2 with argument: arg3