Anticipating evolution

API designers need to resolve an apparent paradox: how to keep APIs virtually unchanged yet respond to ever-changing customer requirements. It is more intricate a skill than simply applying specific API evolution techniques. It can be compared to a chess master’s ability to anticipate several upcoming moves of a game. Just like beginner chess players, we start by learning the specific API evolution techniques, but we become true experts when we are able to plan ahead for at least a couple of API releases. We are more likely to design long-lasting, successful APIs if we master this skill.

Let’s start with the fundamental rule of API evolution: existing clients must work with a new product release without any changes, not even a recompilation. While breaking changes can be tolerated in internal code, they are prohibited in public APIs. We must either limit ourselves to binary compatible changes or keep the old API unchanged while introducing a new API in parallel, a method called API versioning.

Maintaining backwards compatibility

Backwards compatible changes are preferable because clients can upgrade smoothly and without any human intervention, taking advantage of new features at their convenience. Conversely, API versioning demands an explicit decision to upgrade because code changes are required. Clients frequently choose to defer upgrades, requiring a long period of support for multiple API versions. We should plan to evolve APIs primarily through backwards compatible changes. We should avoid API versioning if possible.

Anticipating evolution means choosing designs which allow the largest number of backwards compatible changes. For example, C++ developers know that adding a field to a C++ class changes its size and breaks binary compatibility with client code into which size was hard-coded by the compiler. Similarly, adding a virtual method modifies the virtual method table, causing clients to call wrong virtual functions (see Listing 1). Because the need for new fields and methods is likely to arise, smart designers move all fields and virtual methods into a hidden implementation class (see Listing 3), leaving only public methods and a single private pointer in the public class (see Listing 2):

Listing 1: Original API class design is hard to evolve

#include <vector>  //exposed direct dependency on STL
#include "Node.h"  //exposed implementation class Node
class OriginalClass {

public:
	int PublicMethod(...);

protected:
	std::vector<Node> children; 

	// Adding a field modifies the size, breaks compatibility
	int count; 

	// Adding a method modifies the vtable, breaks compatibility
	virtual void ProtectedMethod(...);
};

Listing 2: New API class design using the Façade pattern

class ImplementationClass; //declares unknown implementation class

class FacadeClass {

public:
	int PublicMethod(...); 

private:
	ImplementationClass *implementation; //size of a pointer
};

Listing 3: The implementation details are never exposed to the client

#include <vector>  //OK, client code never includes it
#include "Node.h"  //OK, client code never includes it

class ImplementationClass {

public:
	int PublicMethod(...);

protected:
	std::vector<Node> children; 

	//OK, client never instanciates direcly
	int count; 

	//OK, the client has no direct accesses to the vtable
	virtual void ProtectedMethod(...);
};

Binary compatible changes are different depending on platform. Adding a private field or a virtual method is a breaking change in C++, but a backwards compatible change in Java. As one of our teams recently discovered, extending SOAP Web Services by adding an optional field is a compatible change in JAX-WS (Java) but a breaking change in .Net. Providing lists of compatible changes for each platform is outside the scope of this document; this information can be found on the Internet. For example, the Java Language Specification states the binary compatibility requirements and Eclipse.org gives practical advice on maintaining binary compatibility in Java. The KDE TechBase is a good starting point for developers interested in C++ binary compatibility.

While we are comparing platforms, we should mention that standard C is preferable to C++ for API development. Unlike C, C++ does not have a standard Application Binary Interface (ABI). As a result, evolving multi-platform C++ APIs while maintaining binary compatibility can be particularly challenging.

Keeping APIs small and hiding implementation details help maintain backwards compatibility. The less we expose to the clients, the better. Unfortunately, compatibility requirements also extend to implementation details inadvertently leaked into the API. If this happens, we cannot modify the implementation without using API versioning. Carefully hiding implementation details prevents this problem.

We can break backwards compatibility (without modifying method signatures) by changing the behavior. For example, if a method always returned a valid object and it is modified so that it may also return null, we can reasonably expect that some clients will fail. Maintaining the functional compatibility of APIs is a crucial requirement, one that requires even more care and planning than maintaining binary compatibility.

The only backwards compatible behavior changes are weakened preconditions or strengthened postconditions. Think of it as a contractual agreement. Preconditions specify what we ask from the client. We may ask for less, but not more. Postconditions specify what we agreed to provide. We may provide more, but not less. For example, exceptions are preconditions (we expect clients to handle them). It is not allowed to throw new exceptions from existing methods. If a method is an accessor, a part of its postcondition is a guarantee that the method does not change internal state. We cannot convert accessors into mutators without breaking the clients. The invariant is part of the method’s postcondition and should only be strengthened.

API behavior changes are likely to go undetected since developers working with implementation code often do not realize the full impact of their modifications. When we talked about specifying behavior, we already noted the importance of explicitly stating the preconditions, postconditions and invariants, as well as providing automated tests for detecting inadvertent modifications. Now we see that those same practices also help maintain functional compatibility as the API evolves.

SPIs (Service Provider Interfaces) evolve quite differently from APIs because responsibilities of the client and the SPI implementation are often reversed. APIs provide functionality to clients, while SPIs define frameworks into which clients integrate. Clients usually call methods defined in APIs, but often implement methods defined in SPIs. We can add a new method to an interface without breaking APIs, but not without breaking SPIs. The way pre- and postconditions can evolve is often reversed in SPIs. We can strengthen preconditions (this is what the SPI guarantees) and weaken postconditions (this is what we ask from the client to provide) without breaking clients. The differences between APIs and SPIs are not always clear. Adding simple callback interfaces will not turn APIs into SPIs, but callbacks evolve like SPI interfaces.

Surprisingly, we need to worry less about source compatibility, which requires that clients compile without code changes. While binary and source compatibility do not fully overlap, all but a few binary compatible changes are also source compatible. Examples of exceptions are adding a class to a package or a method to a class in Java. These are binary compatible changes, but if the client imports the whole package and also references a class with the same name from another package, compilation fails due to name collision. If a derived class declares a method with the same name as a method added to the base class, we have a similar problem. Source incompatibility issues are rare with binary-compatible APIs and require few changes in client code.

If we focus too much on source compatibility, we increase the risk of breaking binary compatibility since not all source compatible changes are binary compatible. For example, if we change a parameter type from HashMap (derived type) to Map (base type), the client code still compiles. However, when attempting to run an old client, the Java runtime looks for the old method signature and it cannot find it. The risk of breaking binary compatibility is real because during their day-to-day work, developers are more concerned about breaking the build than about maintaining binary compatibility.

Versioning

API versioning cannot be completely avoided. Some unanticipated requirements are impossible to implement using backwards compatible changes. Software technologies we depend on do not always evolve in a backwards compatible fashion (just ask any Visual Basic developer). Also, API quality may also degrade over time if our design choices are restricted to backwards compatible changes. From time to time, we need to make major changes in order to upgrade, restructure, or improve APIs. Versioning is a legitimate method of evolving APIs, but it needs to be used sparingly since it demands more work from both clients and API developers.

Anticipating evolution in the case of explicit versioning means ensuring that an incompatible API version is also a major API version. We should deliberately plan for it to avoid being forced by unexpected compatibility issues. The upgrade effort must be made worthwhile for clients by including valuable new functionality. We should also use this opportunity to make all breaking changes needed to ensure smooth backwards compatible evolution over the several following releases.

API versions must coexist at runtime. How we accomplish this is platform-dependent. Where available, we should use the built-in versioning capabilities; .Net assemblies have them and so does OSGi in Java, although OSGi is not officially part of the Java platform. If there is no built-in versioning support, the two API versions should reside in different namespaces, to permit the same type and method names in both versions. The old version keeps the original namespace while the new version has a namespace with an added version identifier. The API versions should also be packaged into separate dynamic link libraries, assemblies, or archives. Since C does not support namespaces, separate DLLs are needed to keep the same method names. We should make sure we change the service end point (URL) when versioning Web Services APIs, since all traffic goes through the same HTTP port. We should also change the XML namespace used in the WSDL. This ensures that client stubs generated from different WSDL versions can coexist with each other, each in its namespace.

It is often advantageous to re-implement the old API version using the new one. Keeping two distinct implementations means code bloat and increased maintenance effort for years. If the new API version is functionally equivalent to the old one, implementing a thin adaptor layer should not require much coding and testing. As an added benefit, the old API can take advantage of some of the improvements in the new code, such as bug fixes and performance optimizations.

Conclusion

Designing for evolution can be challenging and time consuming. It adds additional constraints to API design which frequently conflict with other design requirements. It is essentially a “pay now versus pay later” alternative. We can spend some effort up front designing easy-to-evolve APIs or we can spend more effort later when we need to evolve the API. Nobody can reasonably predict how an API is likely to evolve; hence nobody can claim with authority that one approach is better than the other. It is thought provoking, however, that nobody has yet come forward saying they regretted making APIs easier to evolve.

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 Canada License.