The underrated Encapsulation
Just like all others, I learnt the encapsulation the way it is written all over the internet and all the programming babas explained but when was the last time you used it?
I wanted to draft this to share with you all the underrated encapsulating technique which i came across while doing a code review of one of my colleagues’. I was amazed with his thought process and the way he implemented it.
The Encapsulations were not limited only to the classes and those inner methods but almost everything. I chose one classic example of using it so you can get this technique into your implementations next time you write the code.
There is this piece of code where there is a if condition for getting a boolean value, at the first glance we do not understand what conditions re checked exactly and debugging is comparatively difficult. though there seems nothing wrong in this code, it can be improved.
return (carDetails &&
carDetails.location === 'XYZ' &&
carDetails.insides.specifications.find(detail => detail.cylinders === '2').segment === 'superLuxury' &&
carDetails.availability.country.includes('usa').pincode == '5904504'
)
the code is pretty simple, it is checking for a different attributes of a car but the way it is coded and maintaining it is pretty difficult. may be not at this point of time but if further more conditions are added. Lets see how well this can be simplified or bring in encapsulation technique for writing this code in a more presentable way.
return (isEmpty(carDetails) &&
isLocationBelongTo(carDetails, 'XYZ') &&
IsTwinCylinderAndSegmentMatched(carDetails, 'superLuxury') &&
IsAvailableInCityWithPincode(carDetails, 'usa', '5904504')
)
The idea behind suggesting this technique is not to create multiple methods on each condition but to write a more sensible and easily understandable code, coz at the end its the human who tries to understand your code and not the machine.