DEV Community

ruthmoog
ruthmoog

Posted on • Edited on

Book Club: "Test Driven Development: By Example" #8

Chapter 8: Makin' Objects

This chapter is prep for removing the duplication of the times methods which multiply either Francs or Dollars.

The next step forward is not obvious

No, it is not. What we achieve though, involves having the two methods return the same type (Money as opposed to either Dollar or Franc): Makes sense!

We also use a factory in Money and that means we don't have to new up Dollar or Franc objects in the tests, but the book doesn't talk much about factories here, and since this terminology is used in a much simpler way here than I'm familiar with, I wanted to explore Java factories a little bit.

Factory Pattern

A Factory is an object which controls the creation and/or access to other objects - like the teller in a bank or a librarian in a library.

This means that a factory (or factory method) can simply be a method which creates a new object.

class Library {

  /**
   * The librarian is a factory method, controlling 
   * the creation of book loans.
   */
   BookLoan Librarian(Book request) {
    return new BookLoan(request);
  }
}
Enter fullscreen mode Exit fullscreen mode

But, instead of a librarian, we can have a dedicated factory method for the creation of the object, which makes the factory easier to maintain by encapsulating the creation behaviour, and it also allows us defer object instantiation to a sub-class.

Abstract factory methods need the subclasses to define an implementation.

Concrete factory methods are an interface and also define the implementation, and subclasses can override the implementation.

Static factory methods are efficient but don't allow subclasses to override the implementation. When invoked it's not needed to new up an instance like when using a constructor, and the instances can be controlled to avoid duplication and unnecessary object creation.

📚 Resources

🔎 View my code-along repo at https://github.com/ruthmoog/test-driven-development-by-example


Book cover Kent Beck's "Test Driven Development: By Example" was released in 2002. The book aims to explain how to use TDD to write quality code that works.

Top comments (0)