Validate business data before passing it on

The sales system API expects a three-letter country code. You remember seeing a longer code in the raw data when reviewing the data.

Re-quoting a quote from an earlier chapter:

A business exception can be caused by invalid data, for example. Such an exception might need manual handling since retrying will not help if the data is invalid.

You decide to validate the traffic data before passing it to the sales system API. If the robot spots invalid data, it can flag the work item in question as a business exception. Those exceptions can be managed in Control Room. An action might be correcting the data manually or marking the work item complete (essentially ignoring it).

One simple validation you decide to implement is checking that the country code is indeed three letters long. Shorter or longer country code will be considered invalid.

def consume_traffic_data(): """ Inhuman Insurance, Inc. Artificial Intelligence System automation. Consumes traffic data work items. """ process_traffic_data() def process_traffic_data(): for item in workitems.inputs: traffic_data = item.payload["traffic_data"] validate_traffic_data(traffic_data) def validate_traffic_data(traffic_data): country = traffic_data["country"] if len(country) == 3: return True else: return False
  • The validate_traffic_data() function encapsulates the logic and returns a boolean (True or False).

Again, we know we can directly return the expression to be evaluated - so we do a quick refactoring of our code:

def validate_traffic_data(traffic_data): return len(traffic_data["country"]) == 3

Great! Now you can check if the traffic data is valid before sending it to the sales system API.