What is Single Source of Truth in Coding?
As a current student at Flatiron School, one of the most important concepts I’ve learned when writing code is single source of truth (SSOT). But what is it and how does it relate?
Single source of truth, like the name suggests, is a single “place” where data exists. When information is maintained in one location, our database or code is “truthful.” In other words, it is reliable and easy to refer back to.
Let me try to relate this to the real world. You and a couple of your friends are playing the Telephone Game. If you aren’t familiar with this game, it starts with one player whispering a phrase to the next player in line. Players will continue whispering the phrase to the person next to them until it reaches the last person. The last person will then say the phrase out loud. Who’s the “single” source of truth? That would be player one. But what if player 3 got the phrase correct? Are player 1 and player 3 both sources of truth? Yes! What if we played another game, player 1 going first again but this time player 3 wasn’t able to get the phrase correct. Oh no. In this game of Telephone, we know player 1 was the “true” single source of truth because they initiated both games.
Want to read this story later? Save it in Journal.
However, in coding and working with data, single source of truth will be difficult to locate if your models and data are not structured and associated to each other correctly.
Why is this concept important for coding? Our data needs to have a single source to be accurate. Any associations to the data will be referred through the “single source of truth”. This ensures that our data is correct and reliable. For instance, if a retail store had multiple sources of truth to keep track of their inventory, how would you know if you were getting the correct number of an item in stock? You wouldn’t.
Let’s take a closer look at the retail store inventory example.
We have an Item class and Inventory class. Within the Item class, there is a method #sold that takes in an argument of an integer. For example purposes, let’s have @stock start with 100. If we make a sale, #sold will subtract the amount sold from our stock! Perfect! But wait, with this method our Inventory class will not be able to track any sales and @stock will not accurately express current information. This is because I have two sources of truth for stock. Let’s make some changes.
There! Now every time a sale is made, our Inventory class will accurately reflect the current stock. This is because we have a Single Source of Truth. The Inventory class will keep track of its stock so our data is authentic even when manipulated.
📝 Save this story in Journal.
👩💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. Read the Noteworthy in Tech newsletter.