Unused private methods, private fields and local variables - java

We are using Sonar to review our codebase. There are few violations for Unused private method, Unused private field and Unused local variable.
As per my understanding private methods and private fields can be accessed outside of the class only through reflection and Java Native Interface. We are not using JNI in our code base, but using reflection in some places.
So what we are planning is to do a complete workspace search for these methods and fields and if these are not used anywhere even through reflection, then these will be commented out. Again chances for accessing private methods and fields through reflection are very less. This is for safer side.
Unused local variables can’t be accessed outside of the method. So we can comment out these.
Do you have any other suggestions about this?

I love reflection myself, but to put it in a few words: it can be a nightmare. Keep java reflection to a very controlable (that is, stateless, no global/external variable usage) and minimal scope.
What to look for?
To find private fields and methods turned public, look for Field#setAccessible() and Method#setAccessible(), such as the examples below:
Field privateNameField = Person.class.getDeclaredField("name");
privateNameField.setAccessible(true);
Method privatePersonMethod = Person.class.getDeclaredMethod("personMeth", null);
privatePersonMethod.setAccessible(true);
So, setAccessible() will get you some smoke, but getDeclaredField() and getDeclaredMethod() are really where the fields are accessed (what really makes the fire).
Pay special attention to the values used in them, specially if they are variables (they probably will be), as they are what determine the field accessed.
Do a plain text search
Also, doing a plain text search for the field/method name on the whole project folder is very useful. I'd say, if you are not sure, don't delete before doing a full text search.
If you have many other projects that depend on this one you are trying to change; and if you weren't (or didn't know) the guy who planted those (bombs), I'd let it go. Only would change if really really needed to. The best action would be to get them one by one when you need to make a change to a code around it.
Ah, and, if you have them, running tests with code coverage can also help you big time in spotting unused code.

Calling an unused method via reflection is just weird. And unused fields are could only be used as a deposit via reflection, and used via reflection. Weird too.
Reflection is more in use as a generic bean copying tool.
So a radical clean-up should be absolutely unproblematic. It would be time better spent to look into the usages of java.reflect; whether the reflection code is legitimate. That is more intelligent work than looking for usage of private fields in strings.
And yes, remove it from the source code, which speeds up reading by seconds.
(Of course I understood that this a question of the type: did I oversee something.)

Related

Why creating a method better than declaring variable as a field?

int timeDuration = duration * MONTHS_IN_A_YEAR;
My online instructor said I should declare a method of name getTimeDuration() rather than creating a field of the same name. My question is a why creating a method is more preferable. Thanks.
This could fall into a style war. Folks from some camps will always use getters, while others rarely do so. You will find no single 100% agreed upon answer.
Practically, there will be little difference between a using a getter on a private final variable vs direct access. Good runtime environments will inline getters, making for only a slight additional overhead.
There are several reasons to prefer using a getter: If the value which is being retrieved is to be considered a part of an API; if the value obtained by the getter will be different in subclasses; if you want to place a break point or log or otherwise track calls to access the value; if you want a place to attach documentation of the value obtained by the getter, which would be the getter name and explicit documentation.
On the other hand, adding getters does add (a little) code bloat.
One reason, in future if you set variable as private or it will become private data, you are not allowed to access this variable outside the class boundary. So, the value of value of variable fetch by such getters and in object oriented getters are used for this purpose and came into action. Here getters is method like getTimeDuration().
Some code snippets are called "best practice"s, these are told by experienced people and accepted by developers and programmers because of the reasons like:
more readable code
easy to change for future extending or debugging
better performance
help developers to do better configurations
...
the matter we are talking about (using setter and getter for accessing or modifying fields), has one or some of matters that I have mentioned so it is better for developers to use it.
to talk more specific, by setting a field in a method (which that method is called setter) you can check the user input, put some rules for your code and many more features that some frameworks will give to you as a developer.
accessing the value of a field by a method (which is called getter), might add some abilities in some cases, imagine a situation that you want the user to read the field but not be able to change it. this could be done easily this way.

Why is it possible to access private data/classes via reflection? [duplicate]

This question already has answers here:
What is the security risk of object reflection?
(5 answers)
Closed 9 years ago.
In Java, at runtime it's possible to access a private field using reflection and also a private nested/inner class using reflection (e.g. see here). Is there any specific technical reason, or any general design philosophy, that explains why Java is like this? I don't know but from reading this it looks like for C#/.NET, at least in some configurations, the same thing is not possible. Does Java also have that flexibility? Are there any JVM implementations where this is not possible?
Of course even if Java didn't allow access to private fields via reflection, you can always write your own runtime to do whatever you like. Or you can modify the binary .jar/.class file and change the access modifiers (I assume this is possible).
So it seems like there are three possibilities the designers of Java had to chose from:
Allow direct access to private fields...maybe with a warning.
Do not allow direct access to private fields, but allow access to private fields using reflection.
Do not allow direct access to private fields and also do not allow access to private fields using reflection. The only way to access the private fields is to change the runtime or modify the binary .jar/.class file offline.
Choosing the middle one seems arbitrary to me...if the goal is to make it as inconvenient as possible, choice 3 is best. If the goal is to not add artificial inconvenience to things that can't be truly prevented anyway, 1 is best.
Is there something about the language or the runtime that informed or forced the decision to take choice 2?
In a sense, isn't using reflection exactly the warning you're looking for in #1?
Sometimes using reflection allows for some elegant solutions to otherwise tedious problems, how the GSON library creates and populates objects is a good example. "Normal" code shouldn't access these private fields, and using reflection lets you do so, with all the necessary overhead of exception handling and permission modification to make it clear this is not something to be done in the general case.
Reflection affords much more functionality than simply accessing private fields. It lets you, at runtime, inspect data about classes and objects you can't know at compile-time and use them to call methods and access fields that didn't exist when your code was compiled. A subset of that behavior is private access.
So yes, the Java designers could have created some sort of syntax for private access, but they also needed to create reflection, which is a more logical and powerful way to access private data; all while making it quite clear (if simply because it's complicated) that this behavior should be used with caution. To me, simply calling object.privates.field or something similar doesn't imply the same severity.
Sometimes you need access to private fields for unit testing. Such as testing small private functions in a class that is used internally but should not be called directly. Other times you may want to check if an internal data structure contains the correct data.
If you're using reflection as a means to access private data for other reasons you probably have to come up with a good reason to do so since most people reviewing your code (if any) will probably notice and that will come up as a red flag (the field is private for a reason right?).
Choice 2 was probably made to allow this use of reflection (which can be disabled in your non-debug builds).

Accessing private fields using reflection for a huge POJO: ±1?

I've just discovered that reading and writing any private field of any object could be done without any accessor, but using reflection.
So, my question is: in the case of an application which uses no third technology (e.g. EL) but JAVA, if I need a POJO that contains let say 20 fields, is it more interesting to implement 40 accessors, or to use reflection to access them? I guess some pros and cons, but any experience or feedback would be great :)
You can, but it wouldn't be very maintainable, so: don't do it. The advantages of using getter/setter to access members is, that you are able to hide the accessor, initialize lazy and you will be able to refactor easily (e.g. with IDEA or Eclipse).
You can access object fields and methods using reflection, but you should not.
This article lists at least 2 measurable reasons why not:
Performance. Accessing object methods/fields using reflection is slower than accessing via accessors.
Security restrictions
And the greatest drawback is non-maintainability, quoting from the article below:
A more serious drawback for many applications is that using reflection
can obscure what's actually going on inside your code. Programmers
expect to see the logic of a program in the source code, and
techniques such as reflection that bypass the source code can create
maintenance problems.
It's generally better to access your fields through getters, even if you're using reflection to figure out what fields are available. You can just as easily figure out what getters are available via reflection and call those getter methods. This allows you to:
1) Dynamically figure out what data is available.
2) Explicitly state which fields should be made available and which fields should be private.
3) Explicitly override a getter's behavior to suit your needs.
In most normal cases, reflection is used for figuring out what data is available on an object. You should not use reflection as a general replacement for getters and setters. Otherwise, your code will become truly unmaintainable.
Reflection is only good for specific use cases where one needs to do magic on objects without being able to assume a lot about their structure. Specifically, if your JVM uses a SecurityManager, it might very well prevent code to set privates through reflection.
You could look at this other question for more information about the security manager.

Android Dev: Avoiding Internal Getters/Setters?

I was reading this section in the Android Dev Guide :
here
and I was wondering what is a "Virtual method call" and what does it mean when it says "locally" using a getter/setter? I'm trying to figure out if what they're saying is avoid using methods EVER (for instance a method from an instanced object) or just inside a class you're already working in to get a variable?
To sum it up basically, if I'm in a different class and I want to know the value of a variable in a different class will it be more expensive to do otherclass.getX() than to do otherclass.x? Or is it the same performance if it's not within the current class to do either a method or access a public variable directly?
In that article, they are referring internally accessing private members, and doing so with the field directly rather than calling getX() inside the same class.
It is still recommended (and common) to make members private and provide public accessor methods for external use.
HTH
Using getters and setters is more expensive because first the VM will lookup the method from a virtual method table and then make the call.
For faster access on Android directly accessing member variables reduces the overhead
What the article is basically saying is to avoid the getter/setter patten when you can get away with it. In Java, all methods are Virtual that aren't marked with the private or final modifiers, so they are saying that if your code isn't interface to be implemented by other classes, just access the fields directly. Most likely the reason they point this out is because traditionally, the Java recommendation has been to always use the getter / setter pattern so that your variables can be kept private. However, in Android, you can take a pretty severy performance hit if you add this additional layer of abstraction.
So, in summary. If you're creating an API that other classes will implement, then maybe it's worth it to take the performance hit of getters / setters. But, in your own classes that all interact with each and you're not enforcing a contract, just access the variables directly. External classes accessing your class will also experience the same performance gain by accessing the variable directly, but at some point you need to do a performance-to-maintainability assessment to see if you are comfortable making those variables public or if it's worth it to take the hit and use getter / setter methods
There are MANY, MANY good reason to always use getters (and often use setters) in Java and it's still a great practice to adhere to even when writing code for 'Droid.
While naively there is a higher cost with Dalvik using virtual methods (i.e. getters/setters) rather than instance field access - you can avoid this by using ProGuard to inline these calls at build time!
In such a way you adhere to best practices when coding while avoiding any performance hit.

How would you access Object properties from within an object method? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is the "purist" or "correct" way to access an object's properties from within an object method that is not a getter/setter method?
I know that from outside of the object you should use a getter/setter, but from within would you just do:
Java:
String property = this.property;
PHP:
$property = $this->property;
or would you do:
Java:
String property = this.getProperty();
PHP:
$property = $this->getProperty();
Forgive me if my Java is a little off, it's been a year since I programmed in Java...
EDIT:
It seems people are assuming I am talking about private or protected variables/properties only. When I learned OO I was taught to use getters/setters for every single property even if it was public (and actually I was told never to make any variable/property public). So, I may be starting off from a false assumption from the get go. It appears that people answering this question are maybe saying that you should have public properties and that those don't need getters and setters, which goes against what I was taught, and what I was talking about, although maybe that needs to be discussed as well. That's probably a good topic for a different question though...
This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that needs to run every time that property is set, and the property is being set internally w/o that setter being called).
Personally, I feel like it's important to remain consistent. If you have getters and setters, use them. The only time I would access a field directly is when the accessor has a lot of overhead. It may feel like you're bloating your code unnecessarily, but it can certainly save a whole lot of headache in the future. The classic example:
Later on, you may desire to change the way that field works. Maybe it should be calculated on-the-fly or maybe you would like to use a different type for the backing store. If you are accessing properties directly, a change like that can break an awful lot of code in one swell foop.
I'm fairly surprised at how unanimous the sentiment is that getters and setters are fine and good. I suggest the incendiary article by Allen Holub "Getters And Setters Are Evil". Granted, the title is for shock value, but the author makes valid points.
Essentially, if you have getters and setters for each and every private field, you are making those fields as good as public. You'd be very hard-pressed to change the type of a private field without ripple effects to every class that calls that getter.
Moreover, from a strictly OO point of view, objects should be responding to messages (methods) that correspond to their (hopefully) single responsibility. The vast majority of getters and setters don't make sense for their constituent objects;Pen.dispenseInkOnto(Surface) makes more sense to me than Pen.getColor().
Getters and setters also encourage users of the class to ask the object for some data, perform a calculation, and then set some other value in the object, better known as procedural programming. You'd be better served to simply tell the object to do what you were going to in the first place; also known as the Information Expert idiom.
Getters and setters, however, are necessary evils at the boundary of layers -- UI, persistence, and so forth. Restricted access to a class's internals, such as C++'s friend keyword, Java's package protected access, .NET's internal access, and the Friend Class Pattern can help you reduce the visibility of getters and setters to only those who need them.
It depends on how the property is used. For example, say you have a student object that has a name property. You could use your Get method to pull the name from the database, if it hasn't been retrieved already. This way you are reducing unnecessary calls to the database.
Now let's say you have a private integer counter in your object that counts the number of times the name has been called. You may want to not use the Get method from inside the object because it would produce an invalid count.
PHP offers a myriad of ways to handle this, including magic methods __get and __set, but I prefer explicit getters and setters. Here's why:
Validation can be placed in setters (and getters for that matter)
Intellisense works with explicit methods
No question whether a property is read only, write only or read-write
Retrieving virtual properties (ie, calculated values) looks the same as regular properties
You can easily set an object property that is never actually defined anywhere, which then goes undocumented
Am I just going overboard here?
Perhaps ;)
Another approach would be to utilize a private/protected method to actually do the getting (caching/db/etc), and a public wrapper for it that increments the count:
PHP:
public function getName() {
$this->incrementNameCalled();
return $this->_getName();
}
protected function _getName() {
return $this->name;
}
and then from within the object itself:
PHP:
$name = $this->_getName();
This way you can still use that first argument for something else (like sending a flag for whether or not to used cached data here perhaps).
I must be missing the point here, why would you use a getter inside an object to access a property of that object?
Taking this to its conclusion the getter should call a getter, which should call a getter.
So I'd say inside an object method access a property directly, especially seeing as calling another method in that object (which will just access the property directly anyway then return it) is just a pointless, wasteful exercise (or have I misunderstood the question).
It is better to use the accessor methods, even within the object. Here are the points that come to my mind immediately:
It should be done in the interest of maintaining consistency with accesses made from outside the object.
In some cases, these accessor methods could be doing more than just accessing the field; they could be doing some additional processing (this is rare though). If this is the case, accessing the field directly would mean that you are missing that additional processing, and your program could go awry if this processing is always to be done during those accesses.
If you mean "most encapsulation" by "purist", then I typically declare all my fields as private and then use "this.field" from within the class itself. For other classes, including subclasses, I access instance state using the getters.
The question doesn't require an opinion based answer. It is a subject well covered by computing science for decades from the principle of high cohesion, low coupling and the SOLID principles.
The purist, read correct, OO way is to minimise coupling and maximise cohesions. Therefore both should be avoided and the Law of Demeter followed by using the Tell Don't Ask approach.
Instead of getting the value of the object's property, which tightly couples the two class, use the object as a parameter e.g.
doSomethingWithProperty() {
doSomethingWith( this.property ) ;
}
Where the property was a native type, e.g. int, use an access method, name it for problem domain not the programming domain.
doSomethingWithProperty( this.daysPerWeek() ) ;
These will allow you to maintain encapsulation and any post-conditions or dependent invariants. You can also use the setter method to maintain any pre-conditions or dependent invariants, however don't fall into the trap of naming them setters, go back to the Hollywood Principle for naming when using the idiom.
i've found using setters/getters made my code easier to read. I also like the control it gives when other classes use the methods and if i change the data the property will store.
Private fields with public or protected properties. Access to the values should go through the properties, and be copied to a local variable if they will be used more than once in a method. If and ONLY if you have the rest of your application so totally tweaked, rocked out, and otherwise optimized to where accessing values by going through their assosciated properties has become a bottleneck (And that will never EVER happen, I guarantee) should you even begin to consider letting anything other than the properties touch their backing variables directly.
.NET developers can use automatic properties to enforce this since you can't even see the backing variables at design time.
It depends. It's more a style issue than anything else, and there is no hard rule.
I can be wrong because I'm autodidact, but I NEVER user public properties in my Java classes, they are always private or protected, so that outside code must access by getters/setters. It's better for maintenance / modification purposes. And for inside class code... If getter method is trivial I use the property directly, but I always use the setter methods because I could easily add code to fire events if I wish.
If I don't edit the property, I'll use a public method get_property() unless it's a special occasion such as a MySQLi object inside another object in which case I'll just make the property public and refer to it as $obj->object_property.
Inside the object it's always $this->property for me.
Well, it seems with C# 3.0 properties' default implementation, the decision is taken for you; you HAVE to set the property using the (possibly private) property setter.
I personally only use the private member-behind when not doing so would cause the object to fall in an less than desirable state, such as when initializing or when caching/lazy loading is involved.
I like the answer by cmcculloh, but it seems like the most correct one is the answer by Greg Hurlman. Use getter/setter all the time if you started using them from the get-go and/or you are used to working with them.
As an aside, I personally find that using getter/setter makes the code easier to read and to debug later on.
As stated in some of the comments: Sometimes you should, sometimes you shouldn't. The great part about private variables is that you are able to see all the places they are used when you change something. If your getter/setter does something you need, use it. If it doesn't matter you decide.
The opposite case could be made that if you use the getter/setter and somebody changes the getter/setter they have to analyze all the places the getter and setter is used internally to see if it messes something up.

Categories