Tuesday, December 25, 2018

For Encapsulation, Ask "What's the Cost of Changing Visibility Later?"

Santa taking a selfie with the caption "once it's out there it's out there."

Most languages give you a choice regarding how visible a member of a class will be. The choices vary from language to language but, typically, they range from more-widely exposed options to those granting narrower visibility.

Every time you define a member, you are making this choice. Even if you take the default level of visibility, you are still making the choice to accept the implicit level of visibility.

One thing you can do to inexpensively start improving the level of encapsulation in your system is to start asking a simple question:
What's the cost of changing visibility later?
Generally, all levels of visibility have the same cost, initially. You aren't going to choose an access-modifier that prevents something from being used the first time you write it.

What really matters is how the level of visibility will interact with change. If you make something too private, now, how hard will it be to make it more public, later? If you make it too public, now, how hard will it be to change it to be more private, later?

In a lot of cases, it's pretty straightforward but it isn't always obvious. That's why it's worth asking the question.