Skip to content

Instantly share code, notes, and snippets.

@trikitrok
Last active March 20, 2025 22:43
Show Gist options
  • Save trikitrok/71fd7fe6f819ae11fa44936e780442e8 to your computer and use it in GitHub Desktop.
Save trikitrok/71fd7fe6f819ae11fa44936e780442e8 to your computer and use it in GitHub Desktop.
// We'd like to test PaydayTransaction which
// depends on a concrete class: TransactionLog
class TransactionLog {
public saveTransaction(paydayTransaction: PaydayTransaction): void {
// persist the transaction
// ...
}
}
class PaydayTransaction {
private readonly payRollRepository: PayRollRepository;
private readonly transactionLog: TransactionLog;
constructor(payRollRepository: PayRollRepository,
transactionLog: TransactionLog) { // <- injecting a concrete class
this.payRollRepository = payRollRepository;
this.transactionLog = transactionLog;
}
public run(): void {
// does important stuff, like paying the employees :)
// ...
this.transactionLog.saveTransaction(this);
}
}
//////////////////////////////////////////////
// !! we extracted an interface
interface TransactionRecorder {
saveTransaction(paydayTransaction: PaydayTransaction): void;
}
class TransactionLog implements TransactionRecorder {
saveTransaction(paydayTransaction: PaydayTransaction): void {
// persist the transaction
// ...
}
}
// Now PaydayTransaction depends on the interface
class PaydayTransaction {
private readonly payRollRepository: PayRollRepository;
private readonly transactionRecorder: TransactionRecorder;
constructor(payRollRepository: PayRollRepository, transactionRecorder: TransactionRecorder) {
this.payRollRepository = payRollRepository;
this.transactionRecorder = transactionRecorder;
}
run(): void {
// does important stuff, like paying the employees :)
// ...
this.transactionRecorder.saveTransaction(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment