DEV Community

Mark Rubin
Mark Rubin

Posted on

Default To private Access Modifiers

This is part of a brief series on Good Habits For Java Programmers.

Access modifiers really do matter. It's hard to appreciate that with the small programs you're writing all by yourself when you first learn to program. But as programs get bigger and as more people work on them over time and together, the access modifiers matter more and more.

Why is a large topic, and it may be hard to appreciate with the programs you've been writing. So I'll just be brief about one of the main reasons. So much of the trouble of hunting down bugs in our code is caused by its not being obvious when and why a variable changes state during the execution of the program or when and why a method is called during that execution. And even when it's obvious, there may be so many potential places that variable or method are accessed, we can't keep track of them all in our heads easily to help us think through the potential problems, especially over time and the larger the codebase gets. So one of the ways we combat this is by restricting access to those variables and methods. It reduces the surface area of what could possibly go wrong and what we have to think about when hunting down a bug: "Since this variable is private, it can only be modified by methods in this class, so I can restrict myself to thinking about only what this class does to find my bug." It also restricts the possibility of our making errors: you can't mistakenly call a method on a class from another class if it's not accessible to that second class.

But I fear this may be one of those nuisance topics where your instructors always hassle you to update your access specifiers to be more restrictive and take off points when you don't, and it seems pointless to you. It might be one of those things where you'll just have to develop the habit of doing it the "right" way, according to your instructors, just to get them to stop bothering you and to give you higher grades before you come to experience why this is so valuable a practice.

So default to specifying modifiers on methods as private. That's the habit you want to develop. Make them public only if you need to.

And always make member variables private. If you need to somehow expose the ability to set or get their values, create methods that provide a way for a user of your class to set or get the value from the method. Okay, there are exceptions, but none we need to talk about here, except if you're making a constant: e.g. public static final double MAX_SALARY = 100.0;.

Top comments (0)