Graduate Program KB

Clean Code

Chapter 8

Third-Party Code

  • There's natural tension between the provider and user of an interface

  • Providers want their frameworks to be broad and applicable to many environments

  • Users want an interface focused on their needs

  • Consider using a Map in Java to store Sensor objects

    • Everytime we retrieve an object, it needs to be type casted to Sensor. This becomes the user's responsibility
    Sensor sensor = (Sensor)sensors.get(id);
    
    • Even with generics, if the Map interface changes then that's a lot of fixes in the code
    Map<Sensors> sensors = new HashMap<Sensors>();
    Sensor sensor = sensors.get(id);
    
    • One way is to encapsulate the retrieval logic in the Sensor class, handling casting in a single location
    public class Sensors {
        private Map sensors = new HashMap();
    
        public Sensor getById(String id) {
            return (Sensors)sensors.get(id);
        }
    }
    

Exploring and Learning Boundaries

  • It can be difficult to learn third-party code and integrate it

  • Spend some time reading documentation and deciding how to use a library

  • Instead of experimenting production code, write some "learning tests" to explore our understanding

    • Create controlled experiments to reinforce our understanding of the API
    • Costs nothing, but has the benefit of testing future package releases to identify behavioural differences
  • A clean boundary should be supported by a set of outbound tests that use the interface in the same way as production

Code that doesn't exist

  • Another boundary is one that separates the known from the unknown
  • Often times, code must be written to interact with an API that hasn't been designed yet
  • To maintain workflow, you can define your own interface which mimics the interface you wished you had
    • The "fake" interface is convenient for testing
    • The "real" interface can be implemented when the API is designed, which encapsulates all the API logic in one place
    • Creating these interfaces also keeps the main code clean overall

Clean Boundaries

  • When using code that's not in our control, we must be careful to ensure future changes aren't too costly
  • Boundary code needs clear separation and tests to define expectations
  • Third-party boundaries are managed by having few places in the code that refer to them, utilising encapsulation and interfaces