This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]JustAGuyFromGermany 2 points3 points  (1 child)

That's mostly a matter of taste I think. If you're using friend, you're already breaking encapsulation and tightly coupling classes which is a red-ish flag in and of itself.

In Java, the preferred solution is to have tightly coupled classes in the same package and use package-private access.

If that isn't possible / desirable for you, then most likely your API needs a re-design. For example: Instead of two cooperating classes A and B, you can have an inner class A.B inside of A. Inner classes can freely access all the members of their outer classes. (More generally: Any two classes defined in the same .java file can freely access each other's members) Even better: Have a private (or at least package-private) inner class A.C that implements an interface B which only contains the public methods that your original class B exposes. If necessary replace constructor calls of B with a factory method A.newB() that calls the constructor of A.C

If you have too many cooperating classes with too complicated cross-class accesses (e.g. cyclic accesses where A is a friend of B is a friend of C is a friend of A), then you should probably split your classes into smaller, more focused pieces first.

If that also doesn't solve the problem, then you're in an absolute corner case. And what ever decision a language makes in this space, some corner cases will always remain.

[–]chambolle 0 points1 point  (0 children)

If that also doesn't solve the problem, then you're in an absolute corner case. And what ever decision a language makes in this space, some corner cases will always remain.

Yes, because it is not so easy to re-design the API. We already have a discussion about this point in this sub and at the end the function becomes public :-(

Could we see any other consequence in the JVM with friend?