The Context

The inspiration for this post came to me mainly because of the discussion in comments which I had on Sebastian’s Malaca blog. We had a little debate there about the famous “getters and setters” duo. In my opinion, you can peacefully write software, completely avoiding them (with the obvious exception for DTO’s). My interlocutors had a little different point of view – they stated, that although you should avoid them, there are some cases when G&S are a must. I came up with classic example of a Human, which we can image as:

Could not embed GitHub Gist 1388156: API rate limit exceeded for 213.251.182.110. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)

As we see in this example, you don’t have any getters or setters, all possible actions of a Human are expressed by the methods attached to its class. OK, everything looks beautiful, but what happens if our walking Human gets hit by a car ? If the injury is serious, he will be taken to the hospital. In the hospital he will be medically examined by some (let us hope) skilled medical personnel. If the injury was real worse, the situation may require to perform an operation on an open heart. Unfortunately our properly encapsulated Human doesn’t expose its internal state of which the heart is part of. So, what can (and does) a surgeon ? He just simply breaks the encapsulation by cutting the chest and gets his job done.

If we wanted to translate (model) the actions of a surgeon in Java code, we would write:

Could not embed GitHub Gist 1392023: API rate limit exceeded for 213.251.182.110. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)

In the above example, Java’s reflection API was used to break the encapsulation of the instance of a Human class. If we dive into the body of the method “operate”, we could see that an exception could be thrown – the IllegalAccessException. This is because the JVM could be configured to ban such usages of the reflection API. In the real world, the family could also disagree to operate the patient.

So much for drawing parallels between the real world and Java code. As we see, we cannot relay on this particular feature of Java’s reflection API. If we want to save our innocent Human being, we have two options:

  1. write getters and setters for the organs
  2. add a new method to the Human class, to let him be operated

Let write some code to see, how could it be implemented:

Leave a Reply

Notify me of followup comments via e-mail. You can also subscribe without commenting.