Friday, January 27, 2017

Information hiding

It looks like the concept of information hiding is familiar to a lot of developers, but from what I have seen it is viewed as more of “hide the complex logic that I don’t care to see from me and just give me the object to work with”

While this is certainly true, this is not the only definition or implementation of information hiding…

Here is an example of how to make information hiding work for you when you have something that can change in the future and make it possible for you to localize the changes instead of refactoring entire code base.

Let’s say that you are writing some type of program that created new records and add them into the database. Each record would have their own id that would be generated by your program.

A trivial approach is to get max record number in the database, increase it by one and then add a new record. This would certainly work, but here is a first glimpse of where information hiding can help… Instead of incrementing the id inside of the block of code that adds new record create a new method that would generate new id. This way, if in the future you would want to change the logic, for instance, due to security concerns you don’t have your ids to be sequential and you want to make them random. Also, you might want to reuse deleted ids. All of this logic would be in one place! No need to change this logic throughout your code base!

Well, that was a simple one… but here is another example! Let’s say that you no longer allowed to have numerical ids… that means that if you have snippets of code that compare objects simply on theirs id with assumptions that they are numeric, this code would be broken.

So to change the id generation, that’s not a problem. You can do that inside of one method.

Now, to make your code even more robust, you have to implement comparable in your class that would make type of id irrelevant outside of your class. All you have to do is to be able to specify logic (numeric, alphanumeric, etc.) inside your one class and now you can have as many comparisons throughout your code that would never have to change! All thanks to information hiding that now would hide what type of id you have and how it is compared.

Another example of where information hiding should be used are for methods that throw exceptions. For example, let's say that you use same class as before and need to get the id. The method that retrieves the id, shall not throw any low level exceptions like EOFException. This would expose the underlying implementation of your method... instead create higher level exception like DataNotFound that still in line with your domain object and provides little to its user in terms of its concrete implementation.

Hope you enjoyed this and like always ping me with questions or feedback!


No comments:

Post a Comment