私は最近、関数または関数のセットを別の関数で「ラップ」するという、単純ですが非常に効果的な関数のトリックを見せられました。
以下は、このトリックを示すために私が書いたコードの例です。私の例では、1 つのコマンドに対して 1 つの関数しか提供していませんが、必要に応じて一連の関数が返されるように簡単に拡張できます (したがって、使用できる Guava Mutlimap タイプが含まれています)... Optional を返すので、コマンドが一致しない場合、「安全に」null を返します。Contact と ContacUnit はすべて組織タイプを拡張するドメイン タイプです...これにより、以下のコードが意味を持つようになります。
package com.xxx.component;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.xxx.domain.Contact;
import com.xxx.domain.ContactUnit;
import com.xxx.domain.Organization;
import java.util.Optional;
import java.util.function.Function;
/**
* This serves up the functions used for the domain
* to validate itself.
* Created by beezerbutt on 06/04/2017.
*/
public class MapSetDomainFunctionFactory {
public static final Function<String, Optional<Organization>> toContactFromCwid = s-> Optional.ofNullable(s).map(Contact::new);
public static final Function<String, Optional<Organization>> toContactUnitFromKey = s-> Optional.ofNullable(s).map(ContactUnit::new);
public static final Function<String, Function<String, Optional<Organization>>> commandToFunctions = command -> {
if (command.equalsIgnoreCase("toContactFromCwid")) {
return MapSetDomainFunctionFactory.toContactFromCwid;
} else {
return null;
}
};
}
}
作業を楽にするために、Domain クラス コードを含めます。
/**
* Created by beezerbutt on 06/04/2017.
*/
public class Contact implements Organization {
}
public class ContactUnit implements Organization {
}
public interface Organization {
}
以下は、コードが機能することを証明するために実行した Spock テストのスナップショットです。
