user952887
user952887

Reputation: 425

Why I cant' use nested classes/Objects?

I often do stuff like this while coding:

getNamedJdbcTemplate().update(sql, new MapSqlParameterSource() {

        {
            addValue("a", obj.getA());
            addValue("b", obj.getB());
            addValue("c", obj.getC());
        }
    });

or this

getJdbcOperations().queryForObject(sql, new Object[] { id}, new RowMapper<Obj>(){

        @Override
        public Obj mapRow(ResultSet rs, int rowNum) throws SQLException {
            // TODO Auto-generated method stub
            return null;
        }});

I also use a lot off Inner classes with Java methods.

For sure, if I use the code more then once I will place it on a different class so I can reuse it... the problem is that my team mates don't like this, and nobody is able to give me a proper reason of why not...

They talk a lot about memory leaks and Garbage Collection(GC) but I believe that those are stuff from the past. I'm using Java6 and Spring 3. the apps are deployed on a Tomcat 6 server.

Upvotes: 1

Views: 102

Answers (1)

Alex Vayda
Alex Vayda

Reputation: 6494

There are just a couple disadvantages I can think about using double brace initialization and basically any anonymous classes in general:

  1. A little bit more memory consumption - every time you write new A() { } you essentially create a new anonymous subclass of A which has to be loaded by the class loader and hence consumes some memory. But I would say that although this might be important for some applications for which memory consumption is critical, for the vast majority program (especially server side programs) the Java class memory overhead is so tiny that I wouldn't even take it in the consideration.

  2. Creating anonymous subclass can cause unexpected troubles for many frameworks and libraries relying on reflection. It also might trip the equals() method if it doesn't expect the existence of subclasses. For example think about how the instance new A() { int x = y; } could be serialized and deserialized? Is new A() {{ a = 7; }} is equal to new A() {{ a = 7; }} (assuming their classes are A$5 and A$9 respectively). And so fourth.

But besides that I don't see any other disadvantages of doing that. Both mentioned issues only appear in certain circumstances and are can be easily fixed or worked around when needed.

In general I also prefer anonymous classes for one-time usage and I also do double brace initialization a lot because it makes the code so much nicer, structured and easier to read.

P.S. Some of my colleagues are also yelling at me :D

Upvotes: 1

Related Questions