Send Method As Parameter Java Vs C#

Introduction

This is a widely used concept in software design. This article will have a look at the concept from different points of view in two major languages, C# and Java. This article will cover the command design pattern and generic delegates in C#, and it will guide you towards the alternatives in Java with some ways to overcome challenges you may face.

In C# you have delegates, which is pretty straightforward as far as sending a method as parameter in C#. This has not been the case with Java. Since Java does not have the concept of delegates we have to use interfaces to obtain a similar functionality in Java. Basically the command pattern explains this scenario in Java.

Delegates in C#

We define the delegate:

  1. public delegate int Operation(int i, int j); 

We assign method to the delegate:

  1. Operation operation = (i, i1) => i + i1;   

We can execute method like this:

  1. int result = operation(1, 2);  

Command Pattern

Command pattern falls under behavioural patterns. Command can be sent from client to an invoker and once invoker invokes the command the receiver receives the notification.

Here's how we do a similar thing in Java:

  1. // We declare the interface  
  2. public interface Command {  
  3.    void execute();  
  4. }  
  5.   
  6. // We declare the command  
  7. public class EmployeeToStringCommand implements Command {  
  8.    private Employee employee;  
  9.    public EmployeeToStringCommand(Employee employee) {  
  10.        this.employee = employee;  
  11.    }  
  12.   
  13.    @Override  
  14.    public void execute() {  
  15.        System.out.printf(employee.toString());  
  16.    }  
  17. }  
  18.   
  19. // We have the command Executor finally  
  20. public class CommandExecutor {  
  21.    public void invoke(Command command){  
  22.        command.execute();  
  23.    }  
  24. }  
  25.   
  26. // Here how we execute   
  27. EmployeeToStringCommand employeeToStringCommand = new EmployeeToStringCommand(employee1);  
  28. new CommandExecutor().invoke(employeeToStringCommand);  

Command always wraps with the following information

  1. Method to invoke
  2. Owner of the method (Client instance created the command)
  3. And optionally any arguments required to complete execution of the command.

Note: As you are already aware, you can always use command pattern in C#, there are no any restrictions to doing so since it's based purely with interfaces. But it's highly unlikely to be used with C# since we have the concept of delegates there, which is straightforward and less work for the developers.

Generic Delegates

Func in C#

If you are a C# developer you should probably be familiar with the Func and Action delegates in C#. These two have been added to C# 3.0 as built in generic delegate types, so that you don’t have to define custom delegates every time.

Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter. So let's see same above example with Func in C#.

  1. Func<intintint> func = (i, i1) => i + i1;  

And we have overload versions of Func declared internally in C#. As follows,

  1. public delegate TResult Func<out TResult>();  
  2. public delegate TResult Func<in T, out TResult>(T arg);  
  3. public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);  
  4. public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3);  
  5. …..  

Func functionality in Java

Since Java 1.8 we have the Java.util.Function interface (remember Java uses interfaces to send methods as parameters). We can use it like this

  1. Function<Employee, String> f0 = (e) -> e.toString();  

This means function takes an employee instance as argument and returns string value of it

And here is how we going to execute it

  1. String result = f0.apply(e1);  

Now the challenge is if we want to use this with multiple arguments as we do with C# Func. Unfortunately there is no similar implementation of Java.util.Function interface (I really hope it will do so in future!). So what is the solution/alternative?

Here is a way we can redeclare our own instance of Function interface with multiple arguments,

  1. @FunctionalInterface  
  2. public interface Func<T, R> {  
  3.    R apply(T t);  
  4. }  

Likewise we can declare other instances of interface with a variable number of arguments.

  1. @FunctionalInterface  
  2. public interface Func2Args<T, T1, R> {  
  3.    R apply(T t, T1 t1);  
  4. }  
  5.   
  6. @FunctionalInterface  
  7. public interface Func3Args<T,T1,T2,R> {  
  8.    R apply(T t, T1 t1, T2 t2);  
  9. }  

You may find all the relevant source code for both Java and C# in respective zip files attached to the article.

Cheers!