Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Reflection Against OOP Principles

DZone's Guide to

Reflection Against OOP Principles

· DevOps Zone
Free Resource

Download “The DevOps Journey - From Waterfall to Continuous Delivery” to learn learn about the importance of integrating automated testing into the DevOps workflow, brought to you in partnership with Sauce Labs.

What is so cool about the possibility to access private class members from outside? Everyone keeps asking you during job interviews what are the basic rules of object oriented programming. This is a mandatory knowledge to pass at least the first round. Encapsulation is one of them. Of course, of course.

When you finally get a job and start coding, you realize that many popular frameworks for ORM break this rule easily. Usually it is used in some form of data mapping (for instance @Autowired in Spring). Don't worry. The frameworks are wiser than some ancient principles. Just sit back and relax.

What's wrong with that?

  1. Strange things are happening in your code and you have no idea what and when is changing value in your private int. How can it be even changed if there is no assignment to it? Where would you put a breakpoint to debug it? 
  2. You would like to use such class in your unit test and would like to set the value explicitly. Hmm, you can't. There's no setter because nobody needed it before.
  3. If there is some form of annotation like @Autowired it's easier to find out what's going on, but there are tools that don't need such annotation. What would you think when you look at a class with private members only and without any getters and setters? You know that the class is used and that the application works. What? How?
Reflection is very powerful, but I think that there are better ways of using it.

Discover how to optimize your DevOps workflows with our cloud-based automated testing infrastructure, brought to you in partnership with Sauce Labs

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}