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

DDDでIDに型をつける

Posted at

はじめに

DDDでIDに型をつける事に関して学んでいきます。一言で言うと値の取り違えを型で防止するのが目的です。
例えば、UserのIDの1とOrganizationのIDの1は同じ1でも、意味合いとしては異なります。SQLのWhere区に設定するのはUserIDで絞り込みを行うところを、OrganizationのIDで設定しまったって事ありませんか?
上記の例だとどちらも同じ1なので問題でないのですが、値が異なった時に問題が発生してきます。
 この時にIDをプリミティブ型で定義しておくのでなく、独自の型を定義してコンパイル時に気付くことができます。
今回はあらためて学んでいこうと思います。

取り違えの防止

まずはよくプリミティブ型で定義しています。
GetUserInOrgの引数はuserIDorgIDの順で引数を受ける想定です。
ただ、どちらもstring型なので、コンパイルも実行も問題なく実行できます。

package main

import "fmt"

// 事故りやすい
func GetUserInOrg(userID string, orgID string) {
	fmt.Println(userID, orgID)
}

func main() {
	GetUserInOrg("org_123", "user_999") // ←引数の順番を間違えてもコンパイルは通る
}

取り違えが発生していますね💦型定義していきましょう

main.go

package main

import "fmt"

func main() {
	var u UserID = "user_1"
	var o OrgID = "org_1"
	// これはコンパイルエラーにならない。
	GetUserInOrg(u, o)
	// これはコンパイルエラーになる。
	GetUserInOrg(o, u)
}

type UserID string
type OrgID string

func GetUserInOrg(userID UserID, orgID OrgID) {
	fmt.Println(userID, orgID)
}

GetUserInOrg(o, u)の時はエラーが起きています。ちょっと分かりづらいので、VSCodeのコンパイルエラーのスクショを貼っておきます。

image.png

さいごに

型付けは些末なミスを事前につけられるので、使っていきましょう!

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