15.01.2013 Views

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 4 - Dependency Injection<br />

worry, you won’t actually have to create mock implementations <strong>of</strong> each component, but for now it<br />

keeps things obvious):<br />

internal interface IDataAccess<br />

{<br />

int Save(Car car);<br />

void Update(Car car);<br />

}<br />

internal class MockDataAccess : IDataAccess<br />

{<br />

private readonly List _cars = new List();<br />

}<br />

public int Save(Car car)<br />

{<br />

_cars.Add(car);<br />

return _cars.Count;<br />

}<br />

public void Update(Car car)<br />

{<br />

_cars[_cars.IndexOf(car)] = car;<br />

}<br />

Although our mock’s upgrade function could probably be improved, it’ll do for now. Armed with this<br />

fake class, only a minor change to the Car class is required:<br />

public class Car<br />

{<br />

private int _id;<br />

private IDataAccess _dataProvider;<br />

public Car() : this(new SqlServerDataAccess())<br />

{<br />

}<br />

internal Car(IDataAccess dataProvider)<br />

{<br />

_dataProvider = dataProvider;<br />

}<br />

public void Save()<br />

{<br />

if (!IsValid())<br />

{<br />

//todo: come up with a better exception<br />

throw new InvalidOperationException("The car must be in a valid<br />

state");<br />

}<br />

if (_id == 0)<br />

{<br />

<strong>Foundations</strong> <strong>of</strong> <strong>Programming</strong> Copyright © <strong>Karl</strong> <strong>Seguin</strong> www.codebetter.com<br />

29

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!