LoginSignup
2
0

More than 3 years have passed since last update.

ラムダ式でもっと便利になるabstract

Last updated at Posted at 2019-06-16

はじめに

本記事はabstract関連の実装の仕方について便利だと感じたことをまとめたものです。
学習前の理解度は以下の通りでした。

  • abstract自体は知っているけどあまり便利さを感じなかった
  • ラムダ式を知っていてもStream叩くときしか使ってなかった

抽象クラスやラムダ式の解説はいろんな方が記事を書いてくださっているため割愛いたします。

結論だけ知りたい

この記事で言いたいことは、「中間処理はラムダ式で渡そう」ということだけです。

abstractで不便に感じていたところ

abstractを使うと、クラスごとで異なるロジックだけ実装して、共通で用いるロジックは使いまわせるのがいいですよね。

メソッドをoverride例1
@Override 
public void execute(){
 なにか固有でやること
 super.excecute();
}

前処理や後処理を楽々書けちゃいますね。
ですが、中処理のロジックだけ変えたい時はどうしましょうか?
パッと思い浮かんだのはこんなコード。

メソッドをoverride例2
@Override 
public void execute(){
 //前処理
 super.checkParam();

 //中間処理
 中間処理のロジック

 //後処理だけ共通ロジック
 super.excecute();
}

これなら中間処理だけ書き換えられますね。
しかし、これだと前処理や後処理を呼び忘れるかもしれませんし、必ず前処理が行われるのに各実装クラスで毎回定義させるのはナンセンスですね。

ラムダ式で中間処理を書こう

本記事で言いたいことはこれだけです。

以下にサンプルコードを示します。

Main.java
public class Main {
    public static void main(String[] args){
        Hoge hoge = new Hoge();
        hoge.printlnSum(20,10);
        hoge.printlnSum(10,20);
    }
}
Hoge.java
import java.util.function.BiFunction;

public class Hoge extends AbstractHoge {

    //足し算
    public void printlnSum(Integer x, Integer y){
        BiFunction<Integer, Integer, Integer> cal = (a, b) -> a + b;
        super.execute(x, y, cal);
    }

    @Override
    protected void checkParam(Integer x, Integer y) throws FailedCheckException {
        if(x < y){
            throw new FailedCheckException("第一引数は第二引数以上を入力してください。");
        }
    }
}
FailedCheckException.java
public class FailedCheckException extends Exception {
    public FailedCheckException(String message){
        super(message);
    }
}
AbstractHoge.java
import java.util.function.BiFunction;

abstract public class AbstractHoge {
    void execute(Integer x, Integer y, BiFunction<Integer, Integer, Integer> cal){
        try{
            //前処理
            checkParam(x, y);
            //中間処理
            Integer result = cal.apply(x, y);
            //後処理
            System.out.println("計算結果:" + result);
        }
        catch (FailedCheckException e){
            //入力値チェックで例外出たらエラーメッセージ
            System.out.println(e.getMessage());
        }
    }

    abstract protected void checkParam(Integer x, Integer y) throws FailedCheckException;
}

一言で言うと、
「xがy以上のとき、足し算して出力する」です。
この「xがy以上のとき」が前処理(入力チェック)、「足し算して」が中間処理、「出力する」が後処理です。

出力結果は以下の通りです。

計算結果:30
第一引数は第二引数以上を入力してください。

「足し算して」の中間処理は、以下のように定義しています。

Hoge.java
 BiFunction<Integer, Integer, Integer> cal = (a, b) -> a + b;

説明用に一度変数に入れていますが、引数にそのままラムダ式を入れることも可能です。

Hoge.java変更例
public void printlnSum(Integer x, Integer y){
        super.execute(x, y, (a, b) -> a + b);
}

このように、ラムダ式を用いることで中間処理を渡すことが出来ます。

さいごに

コードはGitHubに上げてます。

2
0
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0