if (startDate.isAfter(endDate)) { throw IllegalStateException() } contractRepository.save(startDate, endDate)
よりも、
val contractPeriod = ContractPeriod(startDate, endDate) contractRepository.save(contractPeriod) data class ContractPeriod( val startDate: LocalDate, val endDate: LocalDate, ) { init { if (startDate.isAfter(endDate)) { // ここは専用の例外でもいい throw IllegalStateException() } } }
さらに、例えば契約の履歴をコレクションにまとめることで、契約期間の整合性をとることもひとつの専用の型で表現できる。
data class ContractHistory( val history: List<ContractPeriod>, ) { fun addContract(contract: ContractPeriod): ContractHistory { if (history.isEmpty()) { return ContractHistory(listOf(contract)) } if (!validateContractPeriod(contract)) { throw IllegalStateException() } return ContractHistory(history + contract) } private fun validateContractPeriod(newContract: ContractPeriod): Boolean { if (history.isEmpty()) return true val lastContract = history.last() // ここらへんは、period.isOverlap(otherPeriod)とかしたほうが良いよいかもしれない return !lastContract.endDate.isBefore(newContract.startDate) } }


