Skip to content

Instantly share code, notes, and snippets.

@s0nerik
Created October 21, 2021 09:59
Show Gist options
  • Save s0nerik/c8d2e9c90c5c3017b38a4c6035777fea to your computer and use it in GitHub Desktop.
Save s0nerik/c8d2e9c90c5c3017b38a4c6035777fea to your computer and use it in GitHub Desktop.
UseCase specification comparison (class vs function, explicit vs implicit deps)
void main() {
final di = DIContainer();
final quarterExpenses1 = di.getComputeQuarterExpensesUseCase().perform(100000);
print(quarterExpenses1);
final quarterExpenses2 = di.getComputeQuarterExpensesUseCaseFunction()(100000);
print(quarterExpenses2);
final quarterExpenses3 = di.getExplicitComputeQuarterExpensesUseCaseFunction()(100000);
print(quarterExpenses3);
}
// A very simplified version of DI container
class DIContainer {
TaxCalculator getTaxCalculator() {
return TaxCalculator(
fopTaxPercent: 0.05,
socialTaxPerQuarter: 3960,
);
}
ComputeQuarterExpensesUseCase getComputeQuarterExpensesUseCase() {
return ComputeQuarterExpensesUseCase(getTaxCalculator());
}
ComputeQuarterExpensesUseCaseFunction getComputeQuarterExpensesUseCaseFunction() {
return (income) => computeQuarterExpensesUseCase(getTaxCalculator(), income);
}
ComputeQuarterExpensesUseCaseFunction getExplicitComputeQuarterExpensesUseCaseFunction() {
return (income) => computeQuarterExpensesUseCaseExplicit(getTaxCalculator().quarterTaxes, income);
}
}
// A "dependency"
class TaxCalculator {
const TaxCalculator({
required this.fopTaxPercent,
required this.socialTaxPerQuarter,
});
final double fopTaxPercent;
final double socialTaxPerQuarter;
double quarterTaxes(double income) {
return income * fopTaxPercent + socialTaxPerQuarter;
}
double yearTaxes(double income) {
return income * fopTaxPercent + socialTaxPerQuarter * 4;
}
}
const moviesSpendingPerQuarter = 200.0;
const gamesSpendingPerQuarter = 1000.0;
// Use-case as class
class ComputeQuarterExpensesUseCase {
ComputeQuarterExpensesUseCase(this.taxCalc);
final TaxCalculator taxCalc;
double perform(double income) {
return income - taxCalc.quarterTaxes(income) - moviesSpendingPerQuarter - gamesSpendingPerQuarter;
}
}
// Use-case as function
typedef ComputeQuarterExpensesUseCaseFunction = double Function(double income);
// same explicitness as [ComputeQuarterExpensesUseCase]
double computeQuarterExpensesUseCase(TaxCalculator taxCalc, double income) {
return income - taxCalc.quarterTaxes(income) - moviesSpendingPerQuarter - gamesSpendingPerQuarter;
}
// more explicit
double computeQuarterExpensesUseCaseExplicit(double Function(double income) getQuarterTaxes, double income) {
return income - getQuarterTaxes(income) - moviesSpendingPerQuarter - gamesSpendingPerQuarter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment