Search code examples
javaandroidbaseadapteranonymous-class

are there any disadvantages to creating anonymous instances of BaseAdapter?


I work on projects that use a lot of different types of lists, so I did this

BaseAdapter someAdapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return 0;
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                return null;
            }
        };

and do all list-specific changes here; Is this bad practice? I feel like extending a new adapter every time overcomplicates my project files, and this helps me better organize my code. Are there any disadvantages to this approach, i.e. something that could go wrong/ bad code style?

I'm sorry if this question is broad/offtopic. I saw a few other questions asking the general adv./disadv. of anonymous classes, but nothing specific.


Solution

  • If the different BaseAdapters all have distinct implementations, that's fine.

    But if you feel that many of your anonymous BaseAdapters repeat the same (or similar) code, then go for named implementations because you can re-use them (Don't Repeat Yourself).

    There's hardly anything that can go wrong with anonymous classes when compared to named ones. Only thing I personally experienced: The technical naming of the classes appends something like "$nnn" to the enclosing class name. So don't persist these class names, expecting they keep stable even over version changes of your application. It's quite likely that after editing your class, you get different "$nnn" suffixes with the next compilation.