2
1

More than 1 year has passed since last update.

if文とswitch文以外の条件が多いコードの書き方

Last updated at Posted at 2022-12-20

この記事のまとめ

この記事は2分で読めます。

多くの条件分岐が必要なビジネスロジックがあるときに、if文やswitch文で書くとコードが長くなってしまって見づらいときあると思います。
言語によるのですがkey-value構造と無名関数を使ったテーブルプログラミングで書くと、きれいに書けるときがあるというお話です。
サンプルはgolangとtypescriptで記載しています。
省略記法ができるtypescriptはいい感じになったのですがgolangでは微妙だったので、アロー記法ができる言語限定かもしれないです。
完全に同じ処理であればkey-valueを使った配列のみで書けてしまうため、分岐内でちょっと違うことをしているケースを例にしました。

golangの場合

環境

go version go1.18.3 windows/amd64

if文で書いた場合

ifhello.go
package main

import "fmt"

func main() {
	inputstr := 1
	outstr := ""

	// if
	if inputstr == 1 {
		fmt.Println("hello")
		outstr = "hoge"
	} else if inputstr == 2 {
		outstr = "fuga"
	} else if inputstr == 3 {
		outstr = "piyo"
	}

	fmt.Println(outstr)
}

switch文で書いた場合

switchhello.go
package main

import "fmt"

func main() {
	inputstr := 1
	outstr := ""

	// switch
	switch inputstr {
	case 1:
		fmt.Println("hello")
		outstr = "hoge"
	case 2:
		outstr = "fuga"
	case 3:
		outstr = "piyo"
	}

	fmt.Println(outstr)
}

テーブルプログラミングで書いた場合

tablehello.go
package main

import "fmt"

func main() {
	inputstr := 1

	// func
	table := map[int]func() string{
		1: func() string {
			fmt.Println("hello")
			return "hoge"
		}, 2: func() string {
			return "fuga"
		}, 3: func() string {
			return "piyo"
		}}
	fmt.Println(table[inputstr]())
}

typescriptの場合

環境

node -v
v16.5.0
tsc -t es6 hello.ts

if文で書いた場合

ifhello.ts
var inputstr = 1
var outstr = ""

// if
if(inputstr==1){
    console.log("hello")
    outstr = "hoge"
}else if(inputstr==2){
    outstr = "fuga"
}else if(inputstr==3){
    outstr = "piyo"
}

console.log(outstr)

switch文で書いた場合

switchhello.ts
var inputstr = 1
var outstr = ""

// switch
switch (inputstr){
    case 1:
        console.log("hello")
        outstr = "hoge"
        break;
    case 2:
        outstr = "fuga"
        break;
    case 3:
        outstr = "piyo"
        break;
}

console.log(outstr)

テーブルプログラミングで書いた場合

tablehello.ts
var inputstr = 1

// table
const table = new Map<number, ()=>string>([
    [1,()=>{console.log("hello"); return "hoge"}],
    [2,()=>"fuga"],
    [3,()=>"piyo"],
]);

var func = table.get(inputstr);
if(func != undefined)
{
    console.log(func());
}

使えそうな場面があったら使ってみてください。
typescriptの最後の呼び出し部分はきれいに書ける書き方があれば教えてください。

2
1
0

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
1