DEV Community

Cover image for Refactoring: Code Comments for API Reusability
John Peters
John Peters

Posted on • Edited on

Refactoring: Code Comments for API Reusability

Image of a multiple choice English test, I loved english but didn't like learning what all the parts were called, so my scores were in need of help. My instructors would often comment on my tests.

If we are following PolyMorphic Compositional techniques we are creating many functions in our solution. So many in fact; due to following the Single Responsibility Principle, we simply have too much stuff to remember regarding what each function really does.

The API

We should treat each function as an API, this means that it must be discoverable, both by name and by what it does.

Assume an Address component that must allow for changing a State from a Select HTML Element like this:

Note : We name all our functions with the prefix func. Its great for intellisense and for knowing where the code lives.

onStateChange(state: NgModel) {
  if (state.viewModel) {
   // a reusable function in our API
   funcAddressResetProperties(this.address);

Enter fullscreen mode Exit fullscreen mode

We can see that the function names go a long way in telling us what each does, but there's more.

Alt Text

Ahh, we didn't know that the ID wasn't reset. But now we do. The time to learn this was a simple hover action, we didn't have to dig into the code.

How did we get the comments above?

/**Resets all but the ID property, 
// this is a design whereby new address 
// information overwrites old. */
export function 
funcAddressResetProperties(address: Address) 
{
   ... 
}
Enter fullscreen mode Exit fullscreen mode

When we have hundreds of functions this is the best way to go. It also contributes to the eventual on-line API documentation to be published later. People that are new to any API rely heavily on online documentation to get started.

JWP2020 Code Comments as an API

Top comments (0)