Search code examples
javacoding-stylesun-coding-conventions

Anonymous class instance placement


Where do you place instance of anonymous class?

public class MyClass {
    // Variables
    private Api api;

    // Functions
    public void callApi() {
        api.get(<...>, responseListener)
    }

    // Where to put that? Top of the file, bottom, next to function?
    private ResponseListener responseListener = new ResponseListener() {
        @Override
        public void onSuccess(Object response) {
        }
    };
}

And also, in that case, would it be preferable to instantiate directly in the api call?

    public void callApi() {
        api.get(<...>, new ResponseListener() {
            @Override
            public void onSuccess(Object response) {
            }
        });
    }

Solution

  • That's a decision that you get to make. The way you wrote it originally, you have a field called responseListener that gets initialized once and reused on each callApi() invocation. If that's the behavior you want, you could put it above the callApi() method (with the other field, api). Or leave it where it is. They're both ok, it's just which do you prefer.

    If, however, you want a new instance each time callApi() is invoked, then it would make sense to put it inside callApi().

    So it matters whether you put it inside callApi() or outside, but only you can decide which is better. And if you want it outside, it doesn't matter where outside, and again only you can decide which is better.