As long as you're not chaning the signature of a method you can change it's behavior to some degree as long as you honor the intent of the method. This "should" not cause other code to break, but it could, depending on the changes you make. A common setter change is to add validation to the value being passed in. This should not break code that calls it and any code that was passing bad values in previously should have been considered broken, but it just wasn't being dealt with.
I think we may have missed the actual questions being asked here.
Mir Ahmad wrote:But i cant understand what breaking other code means
Breaking other code means, making changes in one place that will force other code to change, or it will not compile, or not work correctly.
Imagine I write a class A, with a getFoo() method that returns an int. And then other people at my company write classes B and C, that both use A, and expect the getFoo() method to return an int. And then, I decide to change the getFoo() method to return a double, and I check that change in so others can use it. Well, for the people who wrote classes B and C, when they update their code to use my latest code, they may suddenly see compilation errors. Or maybe it compiles, but now something doesn't work the way it was supposed to work. Either way, the change in A has broken classes B and C, and forces the owners of that code to understand what has changed, and rewrite their code somehow. That's what encapsulation is designed to avoid.
Mir Ahmad wrote:and how this prevent it but using instance variable directly will not?
In the example I just gave, in class A I might change an instance field "foo" from an int to double. But I can still have a getFoo() method that returns an int:
That allows B and C to continue using the original code. Maybe I add a getFooAsDouble() method to return the more correct value. And I can mark getFoo() as a deprecated method, and warn the owners of B and C that they really should stop using getFoo() and switch to the more accurate method getFooAsDouble(). But, I make it so that their code still works, while they figure out how they want to handle the situation.
posted 1 week ago
Thank you so much Mike Simmons for taking the time to respond I appreciate it. I can finally get it
Check your pockets for water buffalo. You might need to use this tiny ad until locate a water buffalo:
Devious Experiments for a Truly Passive Greenhouse!