如何在没有if语句的情况下区分重载方法

时间:2018-03-12 10:05:28

标签: java overloading

在我的程序中,我收到来自调用的消息,该消息具有可选类型的变量,并且取决于是否在此变量内部,我将调用带有参数或调用方法的方法。没有参数,标准重载的相同方法。

我遇到的问题是生成的代码变得丑陋,特别是我收到的选项越多,方法调用就越有区别。目前,下一个方法调用是通过if-else确定的。

以下是此问题的简化代码,首先是消息类:

public class FooMessage {

  public Optional<String> receivedMessage;

  public FooMessage(String message) {
      this.receivedMessage = Optional.ofNullable(message);
  }
}

然后是Main类:

public class Main {

  public static FooMessage receiveMessageWithNull(){
      return new FooMessage(null);
  }

  public static FooMessage receiveMessage(String s){
      return new FooMessage(s);
  }

  public static void fooMethod() {
      System.out.println("Message == null");
  }

  public static void fooMethod(String message) {
      System.out.println("Message != null");
  }

  public static void main(String[] args) {
      //Calls that return a Message either with content or without
      FooMessage message = receiveMessage("foo");
      FooMessage messageWithNull = receiveMessageWithNull();
      //Resolving which version of the overloaded method to call
      if (message.receivedMessage.isPresent()) {
          fooMethod(message.receivedMessage.get());
      } else {
          fooMethod();
      }

      if (messageWithNull.receivedMessage.isPresent()) {
          fooMethod(messageWithNull.receivedMessage.get());
      } else {
          fooMethod();
      }
  }
}

我的问题是,是否有可能以编写方法调用本身的方式清理代码,以解决当前在if语句中执行的检查。我在考虑类似的事情:

fooMethod(message.receivedMessage.isPresent() ? message.receivedMessage.get() : ... );

而不是...会有一些东西告诉方法忽略参数。

注意:我无法更改fooMethod。我必须解决在调用方法中必须调用哪个版本的fooMethod

1 个答案:

答案 0 :(得分:1)

如果您需要执行方法仅当存在Optional值且您不关心缺席值时,您可以使用

message.receivedMessage.ifPresent(Main::fooMethod);

我会避免将Optional传递给一个方法,该方法可以区分值是否存在,但是您可以实现一个支持函数隐藏实现细节

private static void distinguish(String s) {
    if (s == null) fooMethod();
    else fooMethod(s);
}

并通过

进行调整
distinguish(message.receivedMessage.orElse(null));

这是使用Òptional::orElse的可接受方式。

来自文档:

 /**
 * Return the value if present, otherwise return {@code other}.
 *
 * @param other the value to be returned if there is no value present, may
 * be null
 * @return the value, if present, otherwise {@code other}
 */
public T orElse(T other) {
    return value != null ? value : other;
}

我个人只会坚持使用if (optional.isPresent()),因为这是选项的目的,所以我不会太担心。