Last active
December 10, 2018 18:54
-
-
Save philipschwarz/30525249c00c3893c31699cec26ad94f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.{Date, Calendar} | |
import util.{Try, Success, Failure} | |
type Amount = BigDecimal | |
def today = Calendar.getInstance.getTime | |
case class Balance(amount: Amount = 0) | |
sealed trait Account { | |
def no: String | |
def name: String | |
def dateOfOpen: Option[Date] | |
def dateOfClose: Option[Date] | |
def balance: Balance | |
} | |
final case class CheckingAccount private (no: String, | |
name: String, | |
dateOfOpen: Option[Date], | |
dateOfClose: Option[Date], | |
balance: Balance) | |
extends Account | |
final case class SavingsAccount private (no: String, | |
name: String, | |
rateOfInterest: Amount, | |
dateOfOpen: Option[Date], | |
dateOfClose: Option[Date], | |
balance: Balance) | |
extends Account | |
object Account { | |
def checkingAccount(no: String, | |
name: String, | |
openDate: Option[Date], | |
closeDate: Option[Date], | |
balance: Balance): Try[Account] = { | |
closeDateCheck(openDate, closeDate).map { d => | |
CheckingAccount(no, name, Some(d._1), d._2, balance) | |
} | |
} | |
def savingsAccount(no: String, | |
name: String, | |
rate: BigDecimal, | |
openDate: Option[Date], | |
closeDate: Option[Date], | |
balance: Balance): Try[Account] = { | |
closeDateCheck(openDate, closeDate).map { d => | |
if (rate <= BigDecimal(0)) | |
throw new Exception(s"Interest rate $rate must be > 0") | |
else | |
SavingsAccount(no, name, rate, Some(d._1), d._2, balance) | |
} | |
} | |
private def closeDateCheck( | |
openDate: Option[Date], | |
closeDate: Option[Date]): Try[(Date, Option[Date])] = { | |
val od = openDate.getOrElse(today) | |
closeDate | |
.map { cd => | |
if (cd before od) | |
Failure( | |
new Exception( | |
s"Close date [$cd] cannot be earlier than open date [$od]")) | |
else Success((od, Some(cd))) | |
} | |
.getOrElse { | |
Success((od, closeDate)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment