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.
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.
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.
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.
Related
A ClassName.class returns the Class object for that particular class. That said and understood, I can't really grasp what the keyword does when used directly in a method.., then, if we write class and follow it immediately with a dot, the list that appears seems to include all that's in scope there, i.e. local variables of the method, other methods and variables(depending on whether the method is static or not), method itself, and class itself..
Coming from its first stated function above, I find myself at odds with this one: I can't tell what it's exactly doing.. way I see it, it's the same word, expect same function at heart, but that doesn't seem to be the case here
Blurry.. I know, but any insight into it is appreciated. Thx.
I get similar behaviour from Netbeans:
However, these are somewhat bogus suggestions.
class.emptyList(), despite being a suggestion, will not compile. This is probably a peculiarity of the way suggestions are computed. If there's a way to get legal code out of these suggestions, I can't think of it.
Note that you get the same suggestions if you just hit CTRL+enter (or whatever keys you have bound to suggestions) on an empty statement.
Usually there are only two circumstances to use the word class:
When defining a class, for example public class MyClass { ... }
With a dot, after a class name, to get the Class object for a type - Class<Person> clazz = Nurse.class
Sometimes you feel you'd like to have a variable called class, but it's a reserved word, so you can't. It's quite common to see variables called clazz for that reason.
As far as I understand, this can be used inside a class to call a method available in any of its superclass as the compiler will look for the method in its superclasses if it's not available in the (sub)class. Basically just like using a super.
So I was wondering, which is the better way of doing things? Is there a general rule of thumb for sing either?
QUESTION:
When the method in question is not coded i.e only available via inheritance from its super class) in the (sub)class, they basically do the same thing right? In that case, is there a reason to pick one over the other?
super.methodAvailableInSuper();
or
this.methodAvailableInSuper();
MORE CLARIFICATION
WHY USE this. AT ALL?
There seem to be two groups of people in this context : people who hate using this and people who love it. I am obviously no expert and these are only the arguments THEY (the people who recommend using it) use :
When you complete the message with this. you know for sure that you intended to send it to this.. Not using this. could mean you might have forgotten to write what you wanted to send the message to. It is used with variables to disambiguate the local variables from instance vairables
**this, super OR NEITHER? **
If you don't like using this, "neither" is your obvious answer because the compiler is not going to ask you for it.
If you think there is some point in using this, as a convention, in the question's context, each has its benefits:
super makes sure overriding in the subclass doesn't affect the message send but if you prefer the code reflected the any changes made via override, you'd want this.
I was hoping there was a default/better choice already made by programmers after going through this thought process and that's what I am asking for.
They're not equivalent, so your question isn't meaningful.
this.method() will invoke the most-derived override of method(), including in any derived classes that this object may be an instance of
super.method() will invoke the base class's implementation of method(), or whatever implementation it inherited if it doesn't provide an implementation itself.
You should use whichever one does exactly what you want. It's not just an aesthetic choice, or a question of 'good practice'.
EDIT Re your edited edit:
When the method in question is not available in base class, they basically do the same thing right?
Wrong. super always calls a method in the base class or one of its parents. this calls the most-derived override. You would write super if you definitely didn't want to call any future implementation in any future derived class, and you would write this, or nothing, if you did want to call such an implementation if it exists when the call is made. Which is not something you can know when coding.
This is not a question of "best practice" since these keywords are very different.
When you call super.methodAvailableInSuper(); then all parent classes are searched for this method at runtime. If this method exists in the current class or any subclass, this method wont be executed.
You can use this, if you want to call the super implementation of an overriden method without cousing an endless loop.
The keyword this calls the method on the current object. Thus the normal execution of methods will be performed.
See also:
http://docs.oracle.com/javase/tutorial/java/IandI/super.html
WHY USE this. AT ALL?
There seem to be two groups of people in this context : people who hate using this and people who love it. I am obviously no expert and these are only the arguments THEY (the people who recommend using it) use :
When you complete the message with this. you know for sure that you intended to send it to this.. Not using this. could mean you might have forgotten to write what you wanted to send the message to. It is used with variables to disambiguate the local variables from instance vairables
**this, super OR NEITHER? **
If you don't like using this, "neither" is your obvious answer because the compiler is not going to ask you for it.
If you think there is some point in using this, as a convention, in the question's context, each has its benefits:
super makes sure overriding in the subclass doesn't affect the message send but if you prefer the code reflected the any changes made via override, you'd want this.
I was hoping there was a default/better choice already made by programmers after going through this thought process and that's what I am asking for.
In this Java program I'm writing I’m finding that I’m clogging up the main() method with a lot of code that would make it hard to quickly understand/read. Specifically due to a lot of error checking that I’m doing. As a result I want to write a quick function that is only going to be used by this one method to improve readability.
Is writing another method within the class my only option or are there other alternatives?
Is writing another method within the class my only option or are there other alternatives?
It depends:
If the methods should belong only to this class, they should be declared as private or protected methods in the class, depending if the class can be inherited or not.
If the methods should be reused in other classes, it would be better to move it to utility classes as public. For example, check if a String is empty and also validating if is not null. Note that for this example there are methods covering these validations in utility classes from Apache Common Langs, explicitely StringUtils#isEmpty(String).
By the way, Java has methods, no functions.
Answer is yes, generally private methods in the classes hold the code which is not used by outside world. But havig private methods help to reduce the cyclomatic complexity of your public methods. Smaller methods lead to more readable and understandable methods.
Since Java was designed that way, you can only have methods. So, yes, that's the only way. Usually you would use class methods (static) for instance independent methods. These can also be within another class, for example a utility or helper class.
I was examining the StringTokenizer.java class and there were a few questions that came to mind.
I noticed that the public methods which are to be used by other classes invoked some private method which did all of the work. Now, I know that one of the principles of OOD is to make as much as you can private and hide all of the implementation details. I'm not sure I completely understand the logic behind this though.
I understand that it's important to make fields private to prevent invalid values being stored in them (just one of many reasons). However, when it comes to private methods, I'm not sure why they're as important.
For example, in the case of the StringTokenizer class, couldn't we just have put all of the implementation code inside the public methods? How would it have made a difference to the classes which use these methods since the API for these methods (i.e. the rules to call these public methods) would remain the same? The only reason I could think of why private methods are useful is because it helps you from writing duplicate code. For example, if all of the public methods did the same thing, then you can declare a private method which does this task and which can be used by the public methods.
Other question, what is the benefit of writing the implementation in a private method as opposed to a public method?
Here is a small example:
public class Sum{
private int sum(int a, int b){
return a+b;
}
public int getSum(int a, int b){
return sum(a,b);
}
}
Vs...
public class Sum{
public int getSum(int a, int b){
return a+b;
}
}
How is the first sample more beneficial?
In order to add something, a private method can ALWAYS be changed safely, because you know for sure that is called only from the own class, no external classes are able to call a private method (they can't even see it).
So having a private method is always good as you know there is no problem about changing it, even you can safely add more parameters to the method.
Now think of a public method, anyone could call that method, so if you add/remove a parameter, you will need to change also ALL the calls to that method.
The only reason I could think of why private methods are useful is because it helps you from writing duplicate code.
In addition to consolidating duplicate code (often expressed as "Don't Repeat Yourself" or "DRY"), use of private methods can also help you to structure and document your code. If you find yourself writing method which does several things, you may wish to consider splitting it into several private methods. Doing so may make it clearer what the inputs and outputs for each piece of logic are (at a finer granularity). Additionally, descriptive method names can help supplement code documentation.
When writing clean code in Java or any other object-oriented language, in general the cleanest most readable code consists of short concise methods. It often comes up that the logic within a method could be better expressed in separate method calls to make the code cleaner and more maintainable.
With this in mind, we can envision situations where you have many methods performing tasks towards a single goal. Think of a class which has only one single complex purpose. The entry point for that single goal may only require one starting point (one public method) but many other methods which are part of the complex operation (many private helping methods).
With private methods we are able to hide the logic which is not and should not be accessible from anywhere outside of the class itself.
Public methods are generally code that other classes which implement that class will want to use. Private methods are generally not as useful outside the class, or don't(alone) serve the purpose of what the class is meant to accomplish.
Say you're in your IDE of choice, and you implement a some class A. Class A is only designed to do one thing, say document generation. Naturally you will have some mathematical and byte operation methods in Class A that are required to do document generation, but people trying to use Class A are not going to need these other methods, because they just want a document. So we make these methods private to keep things simple for any future users of our class.
The purpose of declaring a method private is to
hide implementation details
exclude the method from being listed as public API
make sure the logic behind the code is not used/misused externally
most of the time your method's execution depends on other methods being run before it; then you can also be sure that you control the correct sequence of using your method
Use private for your methods unless you intend for your method to be safely used outside of the context of your class.
Making functions private gives you advantage in following cases :
Making function private gives JVM compiler the option of inlining the function and hence boosting up the application performance
If the class is inheritable and you extend it from a child class, then in case if you want to hide the functions from child class then you can do this (you can extend StringTokenizer).
If a piece of code has to be used in multiple functions the you move that code in private utility method
An advantage and also a good reason to use private methods inside public classes is for security and bug prevention. Methods that are declared as private are only accessible by the class they are part of. This means that your private method can't be accidentally called from else where within the program reducing bugs and other complications. If you declare your method as public it can be accessed by the whole problem and can cause complications.
You may have a number of methods that work on a certain piece of data that you don't want any other part of the program to be able to interfere with. Using data encapsulation via private methods and/or variables helps to prevent this and also makes your code easier to follow and document.
Is it possible in Java, to declare a method with a string instead of an identifier?
For example can I do something like the following:
class Car{
new Method("getFoo", {
return 1+1;
});
}
//Use it
Car car = new Car();
car.getFoo();
EDIT: I am adding a Purpose WHY I need this. In order to not hardcode method names when using Jersey and its UriBuilder, which requires a method name:
https://jsr311.dev.java.net/nonav/releases/1.1/javax/ws/rs/core/UriBuilder.html
See path() method with signature:
public abstract UriBuilder path(java.lang.Class resource,
java.lang.String method)
throws java.lang.IllegalArgumentException
So then I may just use string constants and not worry that the method name will ever be different from the string that I am passing to the path() method.
I hope my question is clear, if not - let me know and I can clarify it.
It's not possible in the way you described.
The closest thing is probably the asm library to create java bytecode.
As per the purpose, why don't you just have a single method and let it act/behave differently depending on the caller and the parameters?
It's indeed not great to have the method name as string in the code, but if feel the usage of reflection from your side and from jax-rs side should compensate so that this does not happen.
Let me clarify. I guess you are using UriBuilder because you want to expose a service, or something similar. If you reflect on the class and list the method, then pass their name in UriBuilder, which also reflect on the class, the method is never explicitly mentioned in the source.
I'm not familiar with jax-rs though, and without knowing more about what you exactly try to achieve (your edit does provide a bit more information, but does not explain the end goal you have in mind), I don't know if that makes sense. But it could be a track to follow.
If you can consider using another language on the JVM, Groovy can do that.