Isn’t class scope purely for organization? [duplicate]

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]?

5

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.

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.

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.

3

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?

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

1

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.

1

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.

1

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.

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.

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”.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật