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?

More than 3 years have passed since last update.

TypeScriptを使ったValueObjectの実装例

Posted at

ドメイン駆動開発などで使われるValueObjectの実装例です。

ValueObject概要

値をObjectとして扱う方法で、意図しない値の変更を防いだり、様々な表現ができたりします。
また、値に関する知識をクラスに集約することでテストや保守がしやすくなるため、
値の表現方法がイロイロある場合に使うと便利です。

実装例

C#ではそこそこ有名ですが、TypeScriptだと情報があまりない感じですが、
私が調べた限りでは、TypeScriptでは演算子のオーバーロードができないようなので、
この例ではValueObject同士での演算子は利用できません。

abstract class ValueObject<T> {
	readonly Value: T

	constructor(value: T) {
		this.Value = value
	}
        // ValueObject同士で比較するメソッド
	equals(vo: T): boolean {
		if (vo === null) {
			return false
		}
		return this.EqualsCore(vo)
	}
        // 値によって同じかどうか判断する基準が異なるため abstract で定義
	protected abstract EqualsCore(other: T): boolean
}

export default ValueObject

下記の例では温度を例に取り上げています。
温度は摂氏と華氏の2種類の単位があるため、ValueObjectに向いている種類の値です。

type TemperatureUnit = °C | °F
class Temperature extends ValueObject<Temperature>{
    readonly Unit: TemperatureUnit
    constructor(value: int, unit: TemperatureUnit){
        super(name)
        this.Unit = unit
    }

	get ValueWithUnit(): string {
	    return this.Value.toString() + this.Unit
	}

    equalsCore(vo: Person)=>{
       return this.Value === vo.Value && this.Unit === vo.Unit
    }
}
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?