KPIs are data driven, often calculated from raw metrics collected from data sources that do not always contain data for a specific date or time or may occasionally not respond. This unpredictability of real world data needs to be taken into account when writing KPI formula. As with all forms of programming there is value in a certain amount of *defensive coding*.

Take our first example KPI calculation for the *percentage critical issue*. This is a KPI built from two metrics, a metric that collects the number of critical issues opened in a day and one that collects the total number of issues raised on the day. On a typical day the hope would be that there are zero critical issue to it likely that the value for the critical issues metric will regularly be zero. If we review our formula we can see that this doesn’t present much of an issue:

`% critical = 100 * (number of critical / total number unresolved)`

A zero value for *number of critical* will return zero which is the correct answer.

On a really good day we can hope that the *total number unresolved *is also zero. In this case our original formula fails because with a zero value for *total number unresolved* we have a divide by zero error. To cope with this possibility we need to add some defensive coding.

While we consider possible error scenarios we should also protect against issue with collecting data from the underly data source. Not all sources of data are available 100% of the time and although the likelihood of failure is sometimes vanishingly small ServiceClarity provides simple ways to protect against this when writing KPI formula.

On line 1 as before we use the variable

*metrics*to get the last known value for the metric: total number unresolved only this time we set a default value of 0 so that we can be sure that even unexpected failures don’t interfere with our calculation.On line 2 the same

*metrics*variable is used to get the last known value for the metric: number of critical again with a default value of 0On line 4 we protect against the possibility that the total is zero before we calculate the percentage KPI value, on line 5.

On line 7 we provide the correct alternative KPI value of zero critical issues