Friday, January 27, 2017

Clean code, better code

Last week I was working with my team to create a REST API for our sensor to publish data. At the time of writing, the sensor XDK we used supports only HTTP GET and we need a way to pass the temperature and acoustic data to our MQTT broker.

The quick and dirty suggestion is to create a WebAPI GET method and pass the message to our MQTT broker using M2Mqtt client.
This post, I don’t like to explain the implementation details, however I explain how neatly you can write the code.

The developer wrote the code like this
  [Route("publish")]
 public IHttpActionResult Get(string id, string noise, string temp){
              -compare mac id with database, if not throw error
              - convert noise to integer and find the noise level (low, medium or high based on the value matrix - a set of if else)
              -convert temperature to integer. Since the sensor returns mill-degree Celsius, convert it to Celsius
               - send data to MQTT using M2Mqtt
}
The controller contains > 200 lines code and it worked!!! I talked to the developer and asked, are you satisfied with the code you had written. He said it works well.
Then I explained the ways to organize the code
  • Write a class for noise. All conversion (string to double) can be handled there. So the code is completely unit testable.
  •   Create a class for temperature. Create properties for Degree Celsius, Fahrenheit…..
  •   Create a NoiseRange class with max, min and "text" which specifies what that range means (refer Martin Fowler’s range pattern) and implement a method Includes (Noise noise) 
  •  Create a NoiseManager class that contains the list of noise ranges (I've added noise ranges in a json file and stored in App_Data folder)
  •  Create a repository pattern to interface with the data base (to verify the macid).
  •  Create a MqttManager class to interface with the MQTT broker
  •   Inject the repository, Noise Manager and MqttManager as dependencies. I prefer Autofac

Now each and every part of the program is modular and self-containing which can be unit tested individually


It takes some time to understand what a better clean code means. When you get it right, you always follow the right ritual. Happy coding !!!

No comments:

Featured post

How to connect to Mongo Atlas from Robo 3T

If you use a local instance of MongoDB, you might be a great fan of Robo3T. However, if you are using Mongo Atlas, the Atlas web interface p...

Popular Posts