Solutions
Here are the solutions to the exercises in this chapter.
Exercise 1
A pure function should not depend on or modify any state outside its scope. So, instead of relying on the global difficultyModifier
value, we should pass it as a parameter:
[Pure] public double CalculateDamage(Tower tower, Enemy enemy, double difficultyModifier) { return tower.BaseDamage * enemy.DamageMultiplier * difficultyModifier; }
Exercise 2
To isolate side effects, we’ll separate the pure logic from the I/O operations and state mutations:
public interface IFileReader { string ReadAllText(string filePath); } public interface IEnemyRepository { void AddEnemies(IEnumerable<Enemy> enemies); } public interface ILogger { void Log(string message); } public class EnemyProcessor { private readonly IFileReader _fileReader; ...