liveBook · Manning

Factory

As explained in Unit Testing Principles, Practices, and Patterns

A factory is a creation abstraction that constructs domain objects from input data while encapsulating instantiation or reconstruction logic.

A factory is a creation abstraction that reconstructs domain objects from raw input while keeping instantiation logic out of application services. It may be a separate class, a static domain method, or an ORM mapping. Separating this utility logic leaves the service simpler and makes the reconstruction code isolated and testable. section 7.2

Reconstructing a user

UserFactory.Create receives an object array, requires at least three elements, casts the identifier, email, and user type, then returns a User. UserController can therefore load data, call UserFactory.Create, coordinate the domain operation, and persist the result without knowing reconstruction details. section 7.2

Use a factory when:

  • Raw database data must become a domain object. section 7.2
  • Construction is complex enough to distract an application service but lacks direct domain significance. section 7.2
  • Input shape requires explicit validation before instantiation. section 7.2
Listing 7.3. User factory
public class UserFactory
{
    public static User Create(object[] data)
    {
        Precondition.Requires(data.Length >= 3);

        int id = (int)data[0];
        string email = (string)data[1];
        UserType type = (UserType)data[2];

        return new User(id, email, type);
    }
}

Inspect the concrete UserFactory implementation, including input validation, casts, and object creation. section 7.2

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Explains separate classes, static methods, ORM mappings, validation, casting, and test isolation, but not factory taxonomy.
Examples
Uses UserFactory.Create to transform an object array into a User and applies a three-element precondition.
What it assumes
Assumes object-oriented domain models and database data; teaches separation of reconstruction logic from zero within the example.
What you can do after
Build it from scratch by isolating reconstruction, validating input, constructing domain objects, and keeping services focused on coordination.
How it connects
Connects factories with domain models, ORM mappings, application services, reconstruction logic, and unit testing.

Also explained in

Compare how 11 books explain factory →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.