1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

そのif文もっと見やすくしてみません?

Last updated at Posted at 2022-09-04

基本

if($priceA > $price B){
    $message = 'Aの方が高い';
}else{
    #message = 'Bと同じかBの方が高い';
}

というコードがあったら

$price = $price > $price 
    ? 'Aの方が高い'
    : 'Bと同じかBの方が高い';

と書けるよというのがこのお話の基本
(?とか:を先頭にしておくと、三項演算子の処理が続くよ、とわかるのでおすすめ)

循環複雑度が下がるので不具合の発生度が下がるはず

応用

基本があれば応用があるのが世の習い
もっと複雑な処理でもこんなふうに綺麗になる

汚いif文


if ($paymentTotal > $salesTotal) {
            $differenceBetweenPaymentsAndSales = $paymentTotal - $salesTotal;
            if ($price1) {
                $result1 -= $differenceBetweenPaymentsAndSales;
                if ($differenceBetweenPaymentsAndSales > $price1) {
                    $result2 += $differenceBetweenPaymentsAndSales - $price1;
                }
            } else {
                $result2 += $differenceBetweenPaymentsAndSales;
            }
        } elseif ($salesTotal > $paymentTotal) {
            $differenceBetweenSalesAndPayments = $salesTotal - $paymentTotal;
            if ($price2) {
                $result2 -= $differenceBetweenSalesAndPayments;
                if ($differenceBetweenSalesAndPayments > $price2) {
                    $result1 += $differenceBetweenSalesAndPayments - $price2;
                }
            } else {
                $result1 += $differenceBetweenSalesAndPayments;
            }
        }
return [
    'result1' => $result1,
    'result2' => $result2
];

読む気も失せたら、あなたの感覚は正しい
これを引き継いで改修する人は苦労することが明白
このコードを書いた人も、仕様を必死に再現しようとしただけ、きっと誰も悪くない😪

綺麗なternary

return $paymentTotal > $salesTotal 
        ?  [
            'result1' => $price1 
                ? - $differenceBetweenPaymentsAndSales
                : 0,
            'result2' => $price1 
                ? max(0, $differenceBetweenPaymentsAndSales - $price1)
                : $differenceBetweenPaymentsAndSales
        ] 
        : [
            'result1' => $price2 
                ? -$differenceBetweenSalesAndPayments 
                : 0,
            'result2' => $price2 
                ? max(0, $differenceBetweenSalesAndPayments - $price2) 
                : $differenceBetweenSalesAndPayments
        ];

行数も減ってだいぶ良くなったのでは無いでしょうかね
ちなみにmax(), min()を使うとternary自体の個数も減らせるんです。これはまた今度。

(一番いいのは、きちんとモデリングしてクラス切ることだということは忘れないで生きていこ

1
0
3

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?