Dependency Injection and Advanced Collections

Dependency injection hands a class the objects it needs instead of letting it build them, which keeps code flexible and testable. You will also meet three more collections: HashSet, Queue, and Stack.

Updated

Dependency Injection

  1. What is a Dependency (Apprentice): A dependency is an object a class needs to do its job. When a class creates its own dependencies with new, it's wired to them for good, and hard to test.
  2. Constructor Injection (Journeyman): A class asks for its dependencies in its constructor and keeps them in readonly fields. Whoever creates it passes them in, so a test can pass a fake.
  3. Layers: Models, Services, Controllers (Journeyman): Apps are split into layers (controllers, services, data access and models), each with one job, each handed the layer below it through its constructor.

Advanced Collections in C#

  1. HashSet (Journeyman): A HashSet<T> holds each value once, answers "is it in here?" fast, and has no index or guaranteed order. Add tells you whether a value was new.
  2. Queues (Journeyman): A Queue<T> hands values back in the order they arrived, first in, first out. Enqueue adds to the back of the line, Dequeue takes from the front, and Peek looks without taking.
  3. Stacks (Journeyman): A Stack<T> hands values back newest first, last in, first out. Push adds to the top, Pop takes from the top, and Peek looks without taking. Undo is the classic use.

Exercise: Dependency Injection

  1. Exercise: Dependency Injection (Journeyman): Write a cinema box office that is given its clock and price list, sells each seat once with a HashSet, keeps a waiting list in a Queue, and undoes sales with a Stack.