Last active
August 22, 2023 16:45
-
-
Save mbrowne/50fa4a7466a364d9bc43 to your computer and use it in GitHub Desktop.
Alternative TypeScript-DCI money transfer example
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
/** | |
* Transfer Money use case | |
*/ | |
function TransferMoney(sourceAcct: Account, destinationAcct: Account, amount: number) { | |
//bind the objects to their roles | |
SourceAccount <- sourceAcct; | |
DestinationAccount <- destinationAcct; | |
Amount <- amount; | |
//do the transfer | |
SourceAccount.transferOut(); | |
role SourceAccount { | |
transferOut() { | |
if (self.getBalance() < Amount) { | |
throw new Error('Insufficient funds'); | |
} | |
DestinationAccount.transferIn(); | |
} | |
} | |
role DestinationAccount { | |
transferIn() { | |
self.increaseBalance(Amount); | |
} | |
} | |
role Amount {} | |
} | |
/** | |
* Bank account class | |
*/ | |
class Account | |
{ | |
private balance: number = 0; | |
increaseBalance(amount: number) { | |
this.balance += amount; | |
} | |
decreaseBalance(amount: number) { | |
this.balance -= amount; | |
} | |
getBalance(): number { | |
return this.balance; | |
} | |
} | |
//Run the use case | |
var sourceAccount = new Account(); | |
sourceAccount.increaseBalance(20); | |
var destinationAccount = new Account(); | |
destinationAccount.increaseBalance(10); | |
//Transfer 10 dollars (or whatever the currency is) from the source account to the destination account | |
TransferMoney(sourceAccount, destinationAccount, 10); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment