Automatically change public to private (Java)

非 Y 不嫁゛ 提交于 2020-01-02 04:12:09

问题


I am doing a refactoring on code is translated from other languages into Java and I want to do it automatically. My problem is that I have a lot of methods that aren't private but are just called in the same class that they are declared and I want to make them private. I have a lot of classes and I guess if there is something that can help me to do it semi-automatically I would like to know it.

Do you know if I can look for these methods to make them private fastly? I am using Eclipse.


回答1:


Replace all is one option.

But I suggest you don't do it. private and public are there for the programmer. If you only call a method from the class itself, it doesn't automatically mean it has to be private. The best thing you can do is go through them one at a time and ask yourself "should this method be part of the public interface or not?".

Personally, whenever I encounter a private method in a class which I need to use, 99% of the time I leave it private and look for a workaround. That's because I assume the original author of the code knew what he was doing. Of course, this doesn't always apply.

private is a statement of intent. It's like saying - if you need to use this from outside the class, you're doing something wrong. You shouldn't need this.




回答2:


One thing to be aware of is, since it is assumed public scope, you may have classes outside of your class calling the method. If you are able to guarantee yourself that you have all possible code calling this. You can also check if the method is being use in eclipse by right mouse click on the method and use the Reference or (ctrl+shift+G) to make sure that no where is calling this method.

To actually making the change from public to private, a search and replace is probably your best bet.




回答3:


Maybe one way would be replacing "public" words with "private" words on selected documents and with "Replace all" function. But it has side effects if you have "public" in the content of some code other than the method signature, e.g. inside a String maybe.

After replacing all method signatures you select, check one more time to make sure them they are in the way you wanted.



来源:https://stackoverflow.com/questions/9328926/automatically-change-public-to-private-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!