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.
Related
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.
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.)
why we use private keyword?i know it limits the access to a var or a method,but why we have to limit the access?
If you expose all of the methods and variables publicly, when another programmer tries to do something with a class you have written it will be really hard because he wont know which methods take care of the internal behavior of your class, which are the methods he is not supposed to use because he would mess up the internal state of the objects and cause a bug.
You don't "have to" do anything of the sort. It's just good practice to only expose that which absolutely must be exposed, especially when you're creating a large program where connections increase exponentially, and risk of side effects increase with it. It's really all about managing complexity. Read up on encapsulation and information hiding and how this helps reduce complexity in large systems. A good book is Grady Booch's Object-Oriented Design for more on this.
In OO world to achieve encapsulation it is very essential to understand the functionality or behavior of object you would like to expose and each access identifier plays important role in it.In Code Complete book McConnell strongly encourages making all variables private.
Consider you are building a utility library and you are going to expose methods to external world as utilities. But those methods may call few methods which are private. So calling those private methods directly may not make any sense and in worst case, they may even harm the state of the object too. There are lots of examples to explain the usage of private even in jdk.
In String class, there is a private method checkBounds which just checks for valid constructor arguments in case of public String(byte bytes[], int offset, int length, String charsetName)
Exposing this method (making it public) makes no sense for String class.
private as the name implies it is something which resides private/unaccessable from the outer class. Object Oriented Programming language has one important concept called Encapsulation which means to restrict the access to some of the object's components. While developing a code you need to hide some objects from the other class, in these case delete those object/variable as private. A private access is only to the class where is it defined.
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.
This question already has answers here:
Using getters within class methods
(6 answers)
Closed 9 years ago.
In Java classes is it considered good or bad practice to access member fields with their getters and setters?
e.g which is better:
public Order {
private Agreement agreement;
public Agreement getAgreement() {
return agreement;
}
public void process() {
//should I use:
getAgreement().doSomething();
//Or:
agreement.doSomething();
}
}
In general I think accessing the field directly is best due to the KISS principle and also someone may override the get method later with unpredictable results.
However my colleagues argue that it is better to keep a layer of abstraction. Is there any consensus on this?
Honestly, in my opinion, it depends on what you're using it for. Personally, when in doubt, I always leave that extra level of abstraction in there just in case I need to override it later in a subclass. Many times have I been saved from the pain of rewriting a class just because I left a getter or a setter open to overriding.
Another thing is that other clients/programmers might need to use your class in a way that you haven't yet thought of, for example, pulling the Agreement class out of a database. In that case, when they override your class, you have made it painless for them (or potentially a future you) to modify how that data is retrieved.
So unless you're absolutely certain that there is only one way to access that field, and that it's 100% direct, it's probably best to decouple the retrieval and modification of values so that at some future point you can save yourself from rewrite hardship.
The core issue here is that direct field access is ineligible for interception by subclass overridden methods, AOP, dynamic proxies and the like. This can be a good or bad thing depending on the case. I would say that using getters and setters internally is not an anti-pattern or a pattern. It is a good or bad thing depending on the situation, and the design of your class.
I think that the public interface of a class represents encapsulation around state and as such even the other workings of the class benefit from that encapsulation.
If you have wrapped a field in a public get method then there is a reason you have done so. Perhaps there is logic within that method to lazy-load the field, or provide an audit trail. Whatever the reason for the method, your class will most likely need that logic as well.
It sounds to me like some people are interpreting this question as being about getters and setters that are used externally; my interpretation of Pablojim's question was that it's about using them within the class, as opposed to the class directly accessing its fields. (Which are private.)
In that light, I'm with Jherico and patros; use direct access from within the class unless there's some reason not to.
Keeping a layer of Abstraction is a good thing in Java.
The problem is that all the code that directly accesses your member variables without the class noticing it isn't under the control of your class.
So the moment you decide to edit your class in a way that one member that is used in a division as an example should never be 0 you have to be able to ensure that this value is only changed in a way that ensures this. So you would add a setter for this method and change the member to private. But now you need to change all the code that is accessing the member without the setter.
If you know you are changing the value from outside the class and only then provide a setter if you don't know make the variable private and if you need access later maybe provide a getter or a setter.
It gets an Anti-Pattern if there are certain methods in other objects that are always using get for a member then performs some calculations and then uses get. This shows that either the member should be in the other class or that the method needs to be in this class.
Having a getter and a setter without thinking about it for every member breaks encapsulation and is not a good design choice. For mor insides read this article
I'm now working on something that makes me in favor of the getters: we're now moving part of our properties into a "property bag", which means you cannot just reference the variable. So in addition of changing the getter, we need to change all the places that reference that variable. It's something to keep in mind.
It depends on what you use your getters and setters for. Generally I use them when I need to sanity check data coming into a class or format data going out. In that respect, I really use getters and setters as an interface layer between this class and other classes that might need access to its data.
I tend to write my internal code such that it knows how to handle data private to this class, so accessing it with its own getters and setters is generally unnecessary and undesired.
It all depends on how you use your getters and setters, though.
My rule of thumb is that if they do anything more complex than just set or return the value, use the setters/getters. Otherwise, it's not needed since you can fix any problems caused by changes to the member variables.
You're right in that it's annoying to do all that extra work for every attribute variable. Why does the language allow something so basic that no one does? There are very compelling reasons for not allowing direct attribute access, however.
I prefer Eiffel's Unified Access Principle. You can never assign to an attribute, and attributes and functions are accessed in the same way:
class EXAMPLE
feature
variable: INTEGER
variable_function: INTEGER
do
result := 4
end
variable_two: INTEGER assign variable_assign
variable_assign (in: INTEGER)
do
variable_two := in
end
end
feature
test
local
test: EXAMPLE
value: INTEGER
do
create test
value := test.variable -- Valid
value := test.variable_function -- Valid and same even though it's a function
test.variable := value -- Invalid
test.variable_two := value -- Valid, an explicit setter is defined
end
I think this is something that needs to be considered on a case by case basis. Using a getter throughout your class code does complicate it, and probably makes it slightly slower. However, it also makes it more extensible and reusable.
What I've usually done is use the getter if I can forsee any reason someone might want to override my getter with another one. If it's something so basic and simple that it would never make sense, I generally don't use getters.
If you write your code to access the variables without the getter, consider making the getter function "final". That way, no one will try to override your code and tear his hair out wondering why it's not working. (Note that Spring and Hibernate proxies might make this a bad idea.)
In order for it to be an anti-pattern, it'd have to be decidedly harmful. I don't see how there can possibly be any harm in defining getters and setters. At most, it is a waste of time (and typing), which makes it pointless, but not an antipattern.