If you ever worked with a team of people you probably know how hard it is to maintain existing code that someone else has written, how people tend to copy 'n paste all over the place and not recognize that they are basically dropping time bombs, ironically, to keep their own deadlines...
Take a regular day from my current job:
I'm working on a new product for some insurance company and this product has a 5 step selling-process with a steps-indicator on the right. Sounds simple right? There was a problem however with the indicator: it was a generic component built for a fixed 7 step process as they once agreed all their products would require 7 steps to complete. What they instead should've done was provide a way for products to provide their own way of managing the steps in a process.
In the end, decoupling the indicator and refactoring the existing products took a couple of days longer than if they realized this right away. The code would've been much cleaner and better readable as well, because decoupled its scope and domain would've been clearly visible.
Afterall that's what encapsulation is really about; creating parameterized decoupled reusable components
To give an indication how complicated the indicator was, it was based on product code, process code per product (calculate, mutate, buying etc.), optional extra steps and current step. consider there are about 12 products with each 3-4 process options what a mess this must've been before it was refactored.
In short they should've done the following: Encapsulate what varies. In the example what varied was the way the indicator displayed the steps; the names of the steps and how they should be displayed. In our case: active (current step), normal, and inactive (grayed out, meaning it's actually an appended optional process yet to begin).
So here's what I did:
I've refactored the indicator to accept two kinds of Strategies: StepGeneratorStrategy and StepManageStrategy. Each product now could define their own strategy that returned a list of steps and another strategy that determined how each step should be rendered based on the process and current step. In effect I encapsulated what varied: the number steps, and how they are rendered.
The funny thing was a couple of days later a colleague came to me and said: "Hey, I need to add a new product which has its own number of steps, 3. I've heard you made that possible?". I told him he needed to write a couple of strategies and he was done in 20 min. Instant payoff right there.
Cm.
To learn more about the powers of encapsulation, read
Encapsulate what varies - Part 1