gaer darrd
gaer darrd

Reputation: 35

confusing java: a method calls another method which returns something

I have been working on this tutorial and the following code has stumped me:

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public ImageLoader getImageLoader() {

    getRequestQueue();
    //getRequestQueue returns an object, but we dont have any variable to receive it.. how is this possible ?

    if (mImageLoader == null) {
        mImageLoader = new ImageLoader(this.mRequestQueue,
                new LruBitmapCache());
    }
    return this.mImageLoader;
}

so the problem is that getRequestQueue returns an object, but we dont have any variable to receive it.. how is this possible ?

example: shouldnt it be like this:

RequestQueue x = getRequestQueue();

therefore, how can we work with what RequestQueue returns, when we did not capture it in a variable ?

Upvotes: 0

Views: 84

Answers (3)

EpicPandaForce
EpicPandaForce

Reputation: 81588

The getter lazy-initializes the member variable mRequestQueue of the class, then refers to the member variable directly.

Any reasonable person would change

getRequestQueue();
if (mImageLoader == null) {
    mImageLoader = new ImageLoader(this.mRequestQueue,
            new LruBitmapCache());
}

to

RequestQueue requestQueue = getRequestQueue();
if (mImageLoader == null) {
    mImageLoader = new ImageLoader(requestQueue,
            new LruBitmapCache());
}

Does the same thing, but definitely more readable, isn't it?

Upvotes: 0

Mena
Mena

Reputation: 48444

It should if you need to utilize the object returned.

Sometimes, methods returning objects implement some logic that does something, which justifies the invocation without assignment.

It looks like the method modifies an instance variable called mRequestQueue, by assigning it a value.

Therefore it returns that value, but also impacts on the instance of your class.

Bottom line, syntactically this is not a mistake, although it looks like poor design.

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200306

getRequestQueue(), contrary to its name, is actually a method with side-effects. This is why it makes sense to call that method and discard its return value. The state of the program will have changed after the method returns.

Upvotes: 1

Related Questions