Skip to content

Instantly share code, notes, and snippets.

@alvinthen
Created September 11, 2025 13:46
Show Gist options
  • Select an option

  • Save alvinthen/d8a976af84ae83d5e1507f252c40266e to your computer and use it in GitHub Desktop.

Select an option

Save alvinthen/d8a976af84ae83d5e1507f252c40266e to your computer and use it in GitHub Desktop.
Clean Code workshop
// BAD CODE FOR LIVE REFACTORING DEMO (DartPad console)
void main() {
final o1 = Order(id: "A100", amount: 120.0, customerType: "VIP", status: 1);
final o2 = Order(
id: "A101",
amount: 45.0,
customerType: "REGULAR",
status: 1,
);
final o3 = Order(
id: "A102",
amount: -10.0,
customerType: "VIP",
status: 7,
); // invalid
final svc = OrderService();
print("=== BEFORE ===");
print(svc.process(o1));
print(svc.process(o2));
print(svc.process(o3));
// quick 'tests' to validate behavior stays same after refactor
// (use these again after refactor to prove no behavior change)
assert(svc.process(o1) == "OK:A100:VIP:108.0");
assert(svc.process(o2) == "OK:A101:REGULAR:49.5");
assert(svc.process(o3) == "ERR:A102");
}
class Order {
String id;
double amount;
String customerType; // "VIP" | "REGULAR"
int status; // 1 = ACTIVE, 7 = SUSPENDED
Order({
required this.id,
required this.amount,
required this.customerType,
required this.status,
});
}
class OrderService {
String process(Order o) {
if (o.id.isEmpty || o.amount <= 0) {
print("bad order");
return "ERR:${o.id}";
}
if (o.status == 7) {
return "ERR:${o.id}";
}
double p = o.amount;
if (o.customerType == "VIP") {
p = p * 0.9;
} else {
if (p < 50) {
p = p * 1.1;
}
}
final d = DateTime.now().toIso8601String();
final s = "SAVED:$d:${o.id}";
if (s.isEmpty) {
return "ERR:${o.id}";
}
final t = _template(o.customerType);
final u = _send("[email protected]", t);
if (!u) {
return "ERR:${o.id}";
}
final double finalCalcPrice = calc(o.customerType, o.amount);
final finalPrice = (finalCalcPrice > p) ? finalCalcPrice : p;
return "OK:${o.id}:${o.customerType}:${_round2(finalPrice)}";
}
double calc(String type, double amt) {
if (type == "VIP") {
return amt * 0.9;
} else {
if (amt < 50) {
return amt * 1.1;
} else {
return amt;
}
}
}
bool _send(String to, String body) {
return to.isNotEmpty && body.isNotEmpty;
}
String _template(String type) {
if (type == "VIP") return "Thanks VIP!";
return "Thanks!";
}
String _round2(double v) =>
((v * 100).roundToDouble() / 100.0).toStringAsFixed(1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment