DEV Community

Discussion on: Handling complex MVC applications - How to scale and avoid Controller chaos

Collapse
 
erebos-manannan profile image
Erebos Manannán

I just spotted the private keyword in your code, which triggered a need to rant.

Personally I really hate code that uses the private keyword even once. It's pretty much always the wrong solution, unless you're delivering code to 100% externals who are intended to have limited access points. At least issues with protected code can be fixed (in most cases) relatively easily by extending the class.

In frameworks, or your own code that is supposed to be used by your own people, it's always wrong.

I can give several examples of issues I've had that are purely due to someone thinking they're smarter than every other programmer and thus using private to lock down their code from modifications (the only reason I've ever figured out for using it).

Just a few that first come into mind:

  • OAuth library, which we needed to reconfigure in automated tests just slightly, and ended up having to use reflection to change a private method to public
  • Frameworks have had bugs that would be easy to work around if the methods were protected or public so I could e.g. manually clear some state, even protected would've allowed extension to fix, but instead had to copy & paste the whole class and change one word from private to public to work around the issue
  • Database layer where someone built an optimization which caches lots of things internally, but in certain cases the cache caused problems and out of control memory use when we tried to batch process a few million entries in the db - it had a method for clearing the cache, which was private

Code should optimally be written with exactly zero attempts to limit what other developers can do with it, but hints as to what they probably shouldn't be using if they don't know what they're doing. The _ prefix for functions and variables, as e.g. Python has standardized, tends to be good enough.

This way, when you're trying to interface with something, you see the methods you're supposed to be calling for normal operation, and when you run into problems with your specific use case you can work around that, and then open an issue to get the issue solved later on.

Collapse
 
pavlosisaris profile image
Paul Isaris

Hey Janne, thaks for your fruitful comment. You are right, I also tend to use protected instead of private in my code, so that I can be able to extend the class and create sub-classes.

However, the point of the code snippets in this article is to provide a view of a layered MVC architecture and modularized classes.

In a more realistic scenario one would have preferred to use protected, for all the reasons you referenced.