⬆️ ⬇️

The idea of ​​expanding access modifiers

Problem



I'm paranoid. When I write code, I hide all the variables, methods and classes that I can hide. I try to open only those methods and classes that are needed.



Quite often, especially when writing subsystems, it is quite difficult to hide certain methods and classes. The trouble begins, the code subsystem is large enough, and for better organization of the code, you need to have several sub-packages.

For example, if there is a com.system.InternalProperty class, which is used both in com.system.persist.PropertyManager and in com.system.network.PropertyUpdater , then the InternalProperty should be declared public .



In this post I will try to talk about existing solutions and propose a new idea.

')





Existing Solutions



1. Put all classes in one package. Use the default access modifier for internal objects. For example:
class InternalProperty

{

private final int c;



InternalProperty( int c)

{

this .c = c;

}



int getC()

{

return c;

}

}




* This source code was highlighted with Source Code Highlighter .




2. Make the class constructor visible inside the current package, and make the class and its methods public . Then the user will not be able to create an instance of such a class. In our example, it will look like this:
public class InternalProperty

{

private final int c;



InternalProperty( int c)

{

this .c = c;

}



public int getC()

{

return c;

}

}




* This source code was highlighted with Source Code Highlighter .




My idea



It would be great if in the next Java release a special @VisibleIn annotation would be included. This annotation would be placed on a class, class field, or method and would expand the scope of the object. My code would look like this:
@VisibleIn ( "com.system.network" )

@VisibleIn ( "com.system.persist" )

class InternalProperty

{

private final int c;



InternalProperty( int c)

{

this .c = c;

}



int getC()

{

return c;

}

}




* This source code was highlighted with Source Code Highlighter .




That is, the class InternalProperty would be visible in its package, in com.system.network , and in com.system.persist .



This annotation would be used both at the compilation stage and at the execution stage.



Would you like to see something similar in Java? What are the disadvantages of @VisibleIn ?

Source: https://habr.com/ru/post/75468/



All Articles