tags:

views:

182

answers:

5

I'm creating a cell editor, but I've done (and seen) this in other code. I'm creating an object and then dropping it on the floor like this:
ButtonCellEditor buttonColumn = new ButtonCellEditor(table, 2);

This class takes the table and sets a TableColumnModel and custom cell renderers to it. Then, the method ends and I don't reference the buttonColumn object anymore.

So, is there a difference between doing the above and doing this (which also works)?
new ButtonCellEditor(table, 2);

Anything really wrong with doing this?

+1  A: 

There's nothing wrong with either of those way of creating a ButtonCellEditor. However, if you later want to reference that object, with method two you have no way of doing so. With method 1 you can at least say buttonColumn.method().

AlbertoPL
A: 

No tangible difference, as far as I know.

Nothing wrong either -- I would prefer shorter form, if the only reason really is to get side effects of constructing the object (which is not necessarily a very good API design in itself, IMO, but that's irrelevant here).

StaxMan
A: 

they are the same, but a comment about why you are doing it might be in order. otherwise someone might come along and delete it, thinking it is a no-op without investigating.

you could also be more explict and call

table.getColumn(2).setCellEditor(new ButtonCellEditor());

akf
A: 

There is no real difference between the two cases. In the second case an anonymous variable will be created that will be normally garbage collected. The second case will also save you some typing and is somewhat more readable. A reader may expect to find a reference at the created object (if you choose the first version) and be surprised if he doesn't find one.

In any case, a static method may be more suitable for such cases.

kgiannakakis
+9  A: 

You shouldn't have unused variables in your code, that makes it less clear. Also, a constructor is (as its name states) a method for initialize the object, this in your case is not done.

I suggest you to have a static method instead:

ButtonCellEditor.niceNameHere(table, 2);

The only case I can think in which a constructor would be adequate is when it takes params to initialize itself and then perform some actions later, but not for doing the action inside and this is not like yours.

victor hugo
+1 on pointing out the side effect in the constructor.
akf
in this case, however, it might not be appropriate for the new object to contain the passed in variable. A CellEditor shouldn't have a JTable as a member.
akf