I have a method that I want to be called each time one of the other methods is called. I dont want to have to explicitely call it each time. Is there a way to have the other methods naturally call that method before executing its own code?
If I have a method thats called isThere() and I want it called in each other method, I dont want to have isThere() written in each method. I was hoping there would an easier way to do this.
You should look into AOP - Aspect Oriented Programming.
Since you are using Java, I recommend you to take a look at AspectJ.
You could access all other methods through another method, which first calls there, and then uses a parameter you passed to it to identify which method you want it to use, using a switch statement or something similar.
You may take a look into Observer pattern, which may also solve your problem a bit differently. Read the Wikipedia page linked here. Alternatively, you can read the Observer pattern from the Head First Design Pattern book.
Related
I'm working on a JSONObject with multiple sub-JSONObjects.
Here is the way I fill the content :
myJson.getJSONObject(CAT_NAME).put(VAR_NAME, var)
.put(VAR_NAME2, var2)
.put(...);
A friend told me that it is a very bad practice to use "nested function/method calls" and that I should do it this way :
myJson.getJSONObject(CAT_NAME).put(VAR_NAME, var);
myJson.getJSONObject(CAT_NAME).put(VAR_NAME2, var2);
myJson.getJSONObject(CAT_NAME).put(...);
From my view, my way is more like an chained method call than a nested one.
And I don't like the second way because it force the program to get the same object again and again when the put() method already returns it.
Is my case is a "nested function calls" case ?
Is this dangerous or bad for any reason ? And what are those reasons ?
edit : I don't feel like my question is duplicated. The other question involves chained methods but it mainly talks about c# interfaces.
Is my case is a "nested function calls" case ?
No that is method chaining (Builder pattern).
Is this dangerous or bad for any reason ?
No. Your friend is wrong. Not at all bad practice in your case. It's quite Ok since you are building a Json.
Using method chaining will actually be more efficient than the alternative you provided because myJson.getJSONObject(..) is only called once in the first case, whereas you call it many times in the second. There is a much more significant cost for calling getJSONObject(..) than there is for reusing the original object returned by it.
The correct way to accomplish this without using method chaining would be more like this:
JSONObject obj = myJson.getJSONObject(CAT_NAME);
obj.put(VAR_NAME, var);
obj.put(VAR_NAME2, var2);
obj.put(...);
Personally, I prefer to not use method chaining because I think it looks better, but ultimately it's your preference and the code here would have basically the same performance as your first chunk of code.
He PROBABLY considers it bad because it can be less readable (but that's a personal opinion and depends a lot on code formating, how well someone understands the specific APIs, is familiar with the concept of method chaining, etc. etc.).
It's certainly not a generally bad thing to do though. In fact a lot of APIs work exactly like that. Just look at StringBuilder in the Java standard API as a very commonly used example.
As others already pointed out it's potentially more performant (depending on how the called methods are implemented) as well, but that's not a given.
Given a java.lang.reflect.Method object, is there anyway to determine whether the method is purely functional (i.e., given the same input, it will always produce the same output and it is stateless. In other words, the function does not depend on its environment)?
No, there's no way to do it.
Reflection does not allow you to inspect the actual code behind the method.
And even if that where possible, the actual analysis would probably be ... tricky, to say the least.
No there is no way to do that with reflection or any other mechanism.
The developer knows if the method is functional. For example, Spring has a #Cacheable annotation that gives a hint to the application that the method is functional and can therefore cache the result for a given set of arguments. (Spring will wrap your object in a proxy that provides the caching behavior.)
is there anyway to determine whether the method is purely functional(ie., given the same input, it will always produce the same output
I know it's now what you've asked for, but Unit Tests may help you with this.
No. Reflection can not read the byte code of the method. So you can't really tell what a method does or even what other classes it uses.
Reflection will not help you here. If you really want to define it at run time, you can try to use javap -c classname.class. But it would be better to avoid such a hacks.
I have a method in java class file like
public void SIMPLE_METHOD(some params){
...code here...
}
Is there annotation I can use above this method so, a method will be ran before SIMPLE_METHOD, if that pre-method returns true this SIMPLE_METHOD will run other wise this method will be ignored and control will be shifted to next execution point.
I guess the best way to do something like that in your case (since you're already using spring) is to use Spring AOP and #Around advice.
See 6.2.4.5. Around advice:
Around advice runs "around" a matched method execution. It has the
opportunity to do work both before and after the method executes, and
to determine when, how, and even if, the method actually gets to
execute at all.
UPDATE: Also, if you need this for implementing cache on method call it might be a good idea to take a look on Cache Abstraction and #Cacheable.
I am starting to learn Android programming with Java, mainly from online Android documentation. I also looked through several books but they don't seem to address this issue: a feature of Java syntax which I have come across several times and which is a mystery to me. Here is just one example from about half-way through the Contacts Provider documentation at
http://developer.android.com/guide/topics/providers/contacts-provider.html
I have removed the comments to unclutter the code snippet:
op =
ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, emailType);
This is all one statement, I think. What is confusing me is all those "dot operators" that look as though they belong in a Visual Basic "with clause". Where can I find out what all this means?
youre looking at a builder pattern, where the return value of each such with* method is the builder itself (or the object, if its not a builder exactly). theyre handly when you want to chain a lot of setters, or when there are a lot of constructors for the underlying object and you dont want people using it to get confused. or, as fge stated below, when you want the returned object to be immutable (so it cant have setters).
more specifically to your case, the return value of ContentProviderOperation.newInsert() is a ContentProviderOperation.Builder, all of who's methods return itself. usually such a chain of configuration calls will end in a call to build(), which will produce an operation.
This is an instance of so called fluent interfaces (link to wikipedia). There is noting special about it: the value returned from the previous call is being used as the target of the subsequent call.
API like this present a useful alternative to methods with lots of optional parameters, because the resulting code is much easier to read and understand. The code is somewhat more verbose, but in this case it is a good thing, because the parameters passed to constructors get better "tagging". This style is also preferable when you have multiple parameters of the same type (say, strings) next to each other, because it lets the readers avoid parameter counting.
each of those methods returns an ContentProviderOperation.Builder object that has been modified by the method. So you can chain together calls to methods like that and do everything in a more compact way. It's similar to how jQuery works in the javascript world.
It may clear things up a bit to look at the newInsert method on the Android documentation, then look at the documentation for the ContentProviderOperation.Builder class. note that all of the methods on that object also return ContentProviderOperation.Builder objects.
How can i get hold of the instantiating object from a constructor in java?
I want to store reference to the parent object for some GUI classes to simulate event bubbling - calling parents handlers - but i dont wanna change all the existing code.
Short answer: there isn't a way to do this in Java. (You can find out what class called you, but the long answer below applies there for the most part as well.)
Long answer: Code that magically behaves differently depending on where it's being invoked from is almost always a bad idea. It's confusing to whoever has to maintain your code, and it seriously hurts your ability to refactor. For example, suppose you realize that two of the places instantiating your object have basicaly the same logic, so you decide to factor out the common bits. Surprise! Now the code behaves differently because it's being instantiated from somewhere else. Just add the parameter and fix the callers. It'll save you time in the long run.
If you want to know the invoking class, then pass "this" as a parameter to the constructor.
Thing thing = new Thing(this);
Edit: A modern IDE allowing refactoring will make this very easy to do.
Intercepting method calls (including constructors) without changing a ton of existing code is one thing Aspect-oriented programming was made for.
Check out AspectJ for a start.
With AspectJ, you can define a "pointcut" that specifies that you want to intercept constructor calls for a certain object or set of objects (using wildcards if need be), and within the interception code ("advice"), you will be given method context, which includes information about the both the calling method and object.
You can even use AspectJ to add fields to your object's to store the parent reference without modifying their existing code (this is called "introduction").