Let’s begin with the ‘why’. The need to
interface patterns, as stated above, may come from technical leads as a tool to form the code to what they expect to be common. More formally,
interfaces provide a blueprint to a common
API between two code bases. A few better definitions can be found on Stack Overflow.
undefined checks are required. LoDash’s
get method is one great method that makes this for the code in a common pattern. These checks bleed into software and make changing the software hard.
“Do we have this method and if so, use it”.
“Does the data contain this object, else give an empty array”.
If the structure of the data or object change, these safeguards must all be updated. Worse still, they can not be added and the page may error out.
Interface pattern is one of the best tools to counter this. A not so hard to use example is taking advantage of the
extends property in classes. In this case we want to create a Menu, but we want to make sure that all of our Menu’s have the same method to get the items. Each menu however will have their own items and we will write many tests assuming the
getItems exist. We must make sure all menu’s have this method, else we have to safeguard within all uses.
In a way, we have provided a ‘forced structure’ of the Menu. This is the basic
interface pattern that solves one of those major issues of safeguarding. We know that
baseMenu.getItems() will exist and not fail. Further, we can use
interfaces, that provide proven abstractions to problems being solved. They free the code and the developer to think about the logic, not every little implementation detail by positioning the behaviors of the code into well organized and easily understood logic.