Isn't scope just a way to organize classes, preventing outside code from accessing certain things you don't want accessed?

More specifically, is there any functional gain to having public, protected, or private-scoped methods? Is there any advantage to classifying method/property scope rather than to, say, just public-ize everything?

My presumption says no simply because, in binary code, there is no sense of scope (other than r/w/e, which isn't really scope at all, but rather global permissions for a block of memory). Is this correct?

What about in languages like Java and C#[.NET]?

  • 1
    what do you mean by functional gain? can you give an example? – Simon Bergot Oct 23 '12 at 7:21
  • 1
    @Simon I mean does having a private method as opposed to a public method give you any sort of advantage as far as how the program works or functions? – Qix - MONICA WAS MISTREATED Oct 23 '12 at 7:23
  • 3
    For C#, it does serve a security purpose. See stackoverflow.com/a/893724/18192 . The short answer is that class scope can prevent untrusted code which is from accessing out of scope methods. Notice the word untrusted. Code which is running with full trust can use reflection to access private methods. – Brian Oct 23 '12 at 15:55
  • @Brian good point – Qix - MONICA WAS MISTREATED Oct 23 '12 at 22:16
  • Class scope is intended to help humans. – Tulains Córdova Oct 24 '12 at 1:13

As you point out, the main reason is for organisation.

I see it as a communication channel between coders and maintainers, in order to make the intent of the design clear and to keep the code clean as long as possible.

Of course, this is true not only for OOP but also for any modular design.

| improve this answer | |

I'm writing from a Java perspective (to save me having to put 'from a Java perspective' everywhere).

Carefully designing an API is about more than just "organisation". Many of the public classes I write are used by a lot of clients and by using the lowest access modifier possible I am free to change the inner workings of my classes without breaking their code (and thereby getting nasty phone calls and emails!).

tl;dr: Encapsulation/information hiding, you can change your representation and inner workings without breaking client code, public mutable fields are not thread-safe, promote immutability.

A module that is well-designed will hide its internal data and implementation details from other modules and cleanly separates its API from its implementation. This means that communication between modules is done only via their APIs and they are oblivious to the inner workings of each other.

The importance of this is that it decouples modules from each other allowing them to be developed, tested, used, optimised and modified in isolation and they can be developed in parallel. It also increases reuse because modules that aren't tightly coupled can potentially be used in other contexts.

In Joshua Bloch's book "Effective Java" he states that the rule of thumb is:

make each class or member as inaccessible as possible. In other words, use the lowest possible access level consistent with the proper functioning of the software that you are writing.

After designing your public API your instinct should be to make everything else private, and only if another class in the same package really needs to access a member should you make it package-private (remove the modifier). The need for protected members in a public class should be relatively rare as a protected member becomes part of the class's exported API.

When you have everything as public it means that the data fields of the class are accessed directly and you cannot change their representation without changing the API. You also generally cannot change the inner workings of your class as you have the potential to break the code of whoever is using your class. This issue/risk is multiplied by the number of your clients as your class may be used all over the place.

If a field is non-final or is a final reference to a mutable object (e.g. Date) and is public then you give up the ability to limit what is stored in the field or enforce invariants on the field. So if you wanted to limit an int to a certain value range, having the field public means that you no longer have control over what is stored in the field. You also lose the ability to take any action when a field is modified, which means that classes with public mutable fields are not thread-safe.

Public final fields with a mutable object in them have all of the disadvantages of a non-final field too. Whilst you cannot change the object reference, the object can still be modified which may break the inner workings of your class and have unintended and disastrous results.

By making fields private you also minimise mutability of your class. Immutable classes are generally easier to design, implement and use than mutable classes are. Private fields prevent clients of your class from obtaining access to mutable objects and modifying the objects directly. You generally also never give a client references to the mutable objects either (you give them copies).

As your class minimises mutability or becomes completely immutable it also becomes inherently thread-safe and requires no synchronisation. They cannot become corrupt by multiple threads accessing them concurrently. A huge functional gain of immutability is it is one of the easiest ways of achieving thread safety.

| improve this answer | |

I wonder why nobody has mentioned it, but there is a possible gain. As someone pointed out, it makes it possible to reason about the behaviour of a program. Which allow tools for static analysis to tell you a function or variable is not needed at all (so you can scrap it) or not written from anywhere (so you probably do not need it either). You might consider this organisation only, though.

But it also allows the compiler to optimise. Throw out unneeded functions and variables (smaller program), or analyse the flow of the program so that a known value can be cached.

| improve this answer | |
  • 1
    I'm surprised everyone here ignored this simple fact - many optimizations are not possible for public members. – Kobi Oct 23 '12 at 13:36
  • OH wow, totally didn't think about this. – Qix - MONICA WAS MISTREATED Oct 23 '12 at 22:12
  • Of course, this is only applicable to certain languages/compilers, but it is still completely prevalent. – Qix - MONICA WAS MISTREATED Oct 23 '12 at 22:13


Well, no. If you took a working program and elevated all the access modifiers to public, you would still have a working program*. Similarly, if you took a working program and replaced all the for and while loops with equivalent goto constructs, you would also still have a working program. Similarly similarly, if you took a working program and replaced all the string operations with equivalent manual char array manipulations, you would again still have a working program.

But 'Working' isn't the only measure of program goodness. Readability and Maintainability also feature, and for those, access modifiers are useful.

* modulo any Reflection-type stuff that looks for specific access modifiers, etc

| improve this answer | |
  • +1, there is almost no functional gain, but who says non-functional is least important? – Doc Brown Oct 23 '12 at 9:45

By making methods public you define the interface of your class. That way is defined how other code can use it and how it should be tested. So you define in that way how other code can communicate with it. The nice thing is that you can rewrite your internals like private methods without changing the interface.

That generates re-usable code and lowers the amount of cohesion. Using a real interface class abstracts and makes sure even more this interface.

See it maybe as an API, you should not change it and make it very clear to use. Handle the complex internals inside without making them visible.

| improve this answer | |

There is no functional benefit.

The most important benefit is that it makes it possible to reason about the behaviour of a program. If any part of a system can call any other part, it becomes too difficult for actual mortal humans to understand the program and deduce how it will behave. It will begin to drown in bugs, and become a big ball of mud. An important milestone in personal improvement is recognising that your brain is finite, and you need to keep things as simple as possible to get the most from it.

It's also beneficial for communication between developers. But that's not the main benefit - otherwise lone developers would develop big programs without organising them at all.

| improve this answer | |
  • Very true. I'm extremely (almost unhealthily) detail oriented, even when designing my own programs. Then again, I think most programmers are. – Qix - MONICA WAS MISTREATED Oct 23 '12 at 22:15

Try writing an API

Lets say that you want to write a library to share with the rest of the world. There are two important things to consider.

  • Will my library conflict with other libraries?
  • How can I prevent users from depending on code that may change later?

For the first question, classes provide scope to prevent naming collisions. Just try writing code in JavaScript for a while where everything lands in the global namespace by default. Without implementing some form of namespaces or classes, it can ugly very quickly.

The second question is controversial. As a user, I want to be able to see the internal implementation of a classes methods/parameters. As a developer, I want to limit user's accessibility prevent them from changing a classes internal implementation. Many people view the limitations as draconian but they exist for a good reason.

There's a simple saying that embodies the issue, "if it exists, somebody will depend on it."

It's the same reason that Windows still contains applications that were created in the 3.1 days. Libraries, like applications are meant to be used in the long term. The problem is, they are also meant to change and evolve over time.

Stability comes from designing a stable public API. That means, the organization of the class structure shouldn't change and, if it does, measures are taken to provide backwards compatibility.

Flexibility comes from limiting the amount of code that your users can depend on. You want to give them a structure that is named well enough that then can understand what it does but you don't want to show them how you do it. Why, because the method to make it happen may change in the future.

Whether their use outweighs the effort is debatable. In the world of dynamic languages that don't bother with access modifiers it doesn't make a whole lot of difference. If people want to depend on code that is internal to a library then they'll learn the hard way why that's a bad idea. There's still a notion of private/public/global but they're used to classify scope, not policy.

| improve this answer | |

In Java (and I guess that in .NET too) access modifiers means as much as SecurityManagers says. So if you are in controll of it, you can access private members through reflection.

But if your code runs in other application where SM is set to not allow your code to do reflection magic, you actualy cannot acces private members.

I don't know whether something like this is possible in C++ (and I guess that it isn't).

So above organizational benefits (that are huge), in some languages where it is enforced it provides functional difference.

| improve this answer | |

As far as I know, most C++ compilers strip out the access modifiers when compiling the code. Also C++ and Java do give you the ability to cross these modifiers (with C++ you really can access any part of the memory you want, and Java's introspection/reflection mechanism can allow you to call code marked as private) although this can quickly become unintuitive and un-performant if abused, not to mention that in both cases you pretty much render compile time checking useless when doing so.

So yes, you can say that access modifiers are just an active way of enforcing the "syntax" of the coded API, things such as encapsulation, implementation hiding etc. You can still say that they have a "functional" role as well, as the compiler will warn you when you're trying to violate the access modifiers (via the "official" channels) and also throw an error. This is a functional advantage over, for example, C, where you can't really tell the compiler "this part of the code here should NOT be accessible to that part over there".

| improve this answer | |
