Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TDD and encapsulation priority conflict

I just started practicing TDD in my projects. I'm developing a project now using php/zend/mysql and phpunit/dbunit for testing. I'm just a bit distracted on the idea of encapsulation and the test driven approach. My idea behind encapsulation is to hide access to several object functionalities. To make it more clear, private and protected functions are not directly testable(unless you will create a public function to call it).

So I end up converting some private and protected functions to public functions just to be able to test them. I'm really violating the principles of encapsulation to give way to micro function testability. Is this the correct way of doing it?

like image 865
Hanseh Avatar asked Dec 01 '22 05:12

Hanseh


1 Answers

There is a pretty standard answer to this in TDD circles. If there is functionality in a class that you both want hidden and directly tested, you should sprout a class with that functionality. This is a great example of how TDD improves your design.

In the original class, that extraneous functionality is gone, wrapped within the sprouted class, so the original class' design is simpler, and better conforms to the Single Responsibility Principle. In the sprouted class, the extracted functionality is its raison d'etre, therefore it's appropriate for it to be public, and therefore it's testable without test-only modifications.

like image 173
Carl Manaster Avatar answered Dec 15 '22 00:12

Carl Manaster