An ‘internal’ scope class available only to selected classes

  softwareengineering

In many languages there is a scope that is just less than public called internal.

Wondering, Why none of the language, implemented a feature on internal such that one can specify

  • Only what other classes are permitted to access or
  • Accessible to all classes in the module

There are many examples where a group of class works together as a concept, while only one or few classes are really needs to be accessed by other concepts in the system. Which means, if I could make some low level classes only available to the group of classes handling the concept, then that way I could prevent it from widely available to the entire module. Which also means those classes becomes encapsulated behind my higher level classes, in turn less coupling points in the design.

Is this feature available in any language?

3

This is exactly how access restriction works in Eiffel. In Eiffel, instead of a small number of coarse-grained access-levels like public, protected, package private, private, internal, etc. the class can specify for each member the precise list of other classes that should have access to this member.

For example, an export clause in an Eiffel class definition might look something like this:

export
    {NONE}        -- to nobody …
        all       -- … export everything (in other words, make everything private)
    {LINKED_LIST} -- to the class `LINKED_LIST`
        add,
        remove    -- export these two
    {ANY}         -- to all classes
        for_each  -- export the routine `for_each`

Based on this it seems other languages have not been keen on implementing C++’s concept of friend classes/functions.

I don’t know whether the suggested reason (friend breaks encapsulation) is a valid reason that would make “friend considered harmful”, but as it seems to be missing from most languages it certainly isn’t essential in making your design work. For example Java’s package private (default) visibility could be used to imitate friend functionality, by keeping “friends” in the same package.

LEAVE A COMMENT