API viscosity measures the resistance to change of code written using a particular API. For each goal that the user might want to accomplish with the API, describe how easy it is to make changes to the code required to accomplish that goal. In particular, consider situations where the user has a choice between two or more alternatives for accomplishing a particular goal. Describe how easy it is to change code that uses one approach to using another.
It’s important to describe these changes from the developer’s perspective. Think of the changes that developers might expect to make in terms of the different scenarios that the API supports, rather than the support that the API provides for modification.
You should also think of the ‘domino’ effect of any change. Some changes might require the user to make additional changes elsewhere in their code that uses your API, which in turn require other changes, etc etc…
In the System.IO namespace, one goal might be to write code that appends text to a text file. There are at least two different approaches that might be taken to accomplish this goal. The first approach might be to use the StreamWriter class exclusively:
StreamWriter sw = new StreamWriter(“C:\test.txt”, true);
sw.WriteLine(“Text to append to test.txt”);
Another approach might be to use the File class to create the instance of the StreamWriter instead of calling the StreamWriter constructor. The changes required are simply to change the first line of code above to:
StreamWriter sw = File.AppendText(“C:\\test.txt”);
The remaining lines of code in the sample would be the same, since the only thing that has changed is the way that the instance of the StreamWriter is created.
It’s important to consider other changes that users might reasonably be expected to make. For example, if the user wants to write to a different file they only need to change the path to the file that is passed in as a string whenever the StreamWriter is created. On the other hand, if a user uses the File class to create the StreamWriter then decides that they want to modify the encoding that the output is written, they will need to modify the creation of the StreamWriter to use the StreamWriter constructor and pass the encoding they wish to use in the constructor.
API Viscosity can be defined in the following terms.
- If the API allows users to make changes to code written against an API easily, the API has low viscosity.
- If the API allows users to make changes to code written against an API with moderate effort, the API has medium viscosity.
- If the API allows users to make changes to code written against an API with significant effort, the API has high viscosity.