Add solution (after) files for the three C# demos: seam overloads, extracted tails, pure xUnit stub tests
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
// Example 1 solution — Metaphor-free demo of Slice with Lambda (C#), after
|
||||
//
|
||||
// Lambda extracted (step 1), slid to the top (step 2), method extracted
|
||||
// below the guard (step 3), overload seam added (step 3b), b inlined
|
||||
// (final cleanup).
|
||||
//
|
||||
// Condensed mechanics: https://sammancoaching.org/refactorings/slice.html
|
||||
// (where that page says mock, we use a lambda instead).
|
||||
|
||||
using System;
|
||||
|
||||
public class Calculator
|
||||
{
|
||||
private readonly SomeDependency _someDependency;
|
||||
|
||||
public Calculator(SomeDependency someDependency)
|
||||
{
|
||||
_someDependency = someDependency;
|
||||
}
|
||||
|
||||
public int Calculate(int a) // overload: callers unchanged
|
||||
{
|
||||
return Calculate(a, a =>
|
||||
_someDependency.mightThrowWhenPreconditionNotSatisfied(a));
|
||||
} // the real λ, baked into the head
|
||||
|
||||
public int Calculate(int a, Func<int, int> readB) // the seam: λ is a parameter
|
||||
{
|
||||
if (a < 0) return 0; // guard clause: stays
|
||||
return CalculateTail(a, readB);
|
||||
}
|
||||
|
||||
private int CalculateTail(int a, Func<int, int> readB)
|
||||
{
|
||||
int c = a + readB(a); // b inlined
|
||||
return c * 2;
|
||||
}
|
||||
}
|
||||
|
||||
public class SomeDependency
|
||||
{
|
||||
private readonly Random _rng = new Random(); // stand-in for unpredictable computation
|
||||
|
||||
public int mightThrowWhenPreconditionNotSatisfied(int a)
|
||||
{
|
||||
if (a > 99)
|
||||
{
|
||||
throw new InvalidOperationException("precondition not satisfied");
|
||||
}
|
||||
return _rng.Next(100);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user