Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why programming languages don't have an 'allow specific classes' access modifier

Today, programming languages have these well-known access modifiers: private, public, internal, and protected. But sometimes when I write a program in OOP manner, I think I require a 'special' modifier that can manually specify what class I want to allow access for.

Now I want to know the reason why language designers don't add such modifier to programming languages, maybe the conflict with OOP concept, or about the difficulty?

Thanks for the answer :)

p.s. Sorry if the same question has been already asked.

like image 455
armamoyl Avatar asked Oct 18 '22 12:10

armamoyl


2 Answers

C# and VB.Net both have the concept of friend assemblies, where specified assemblies can access the internal members of the specified assembly. This allows you to give provisional access to specific callers, the checking for this is done at compile time.

Only assemblies that you explicitly specify as friends can access Friend (Visual Basic) or internal (C#) types and members. For example, if assembly B is a friend of assembly A and assembly C references assembly B, C does not have access to Friend (Visual Basic) or internal (C#) types in A.

The reality is that there are limited legitimate uses for this feature (in these languages at least), unless you are into developing smelly code.

But having said that, the idea of a class defining who can call it is borderline violating the encapsulation and abstraction rules of OOP. By allowing a class to nominate who it's caller can be you are allowing the class to have a knowledge beyond its realm and you are throwing good design out the window. A class can dictate how a caller should call, but not who should call.

I hope that helps somewhat - personally I'm looking forward to the answers from the more academic language oriented people.

like image 189
slugster Avatar answered Oct 21 '22 23:10

slugster


Well, Scala allows you to restrict access to specific packages or just to an instance of a class you're referring to as 'this'

like image 37
chester89 Avatar answered Oct 21 '22 21:10

chester89