New Inspection "Make type more generic"

Does anyone think this would be a good code inspection?

/*****************************************/
MyJCheckBox j = new MyJCheckBox();

if(j.isSelected())
//do something
/*****************************************/

Idea would say change type of variable j from MyJCheckBox to JCheckBox, since we only use methods of JCheckBox.

6 comments
Comment actions Permalink

+1, I like the idea.

0
Comment actions Permalink

charles decroes wrote:

Does anyone think this would be a good code inspection?

/*****************************************/
MyJCheckBox j = new MyJCheckBox();

if(j.isSelected())
//do something
/*****************************************/

Idea would say change type of variable j from MyJCheckBox

> to JCheckBox, since we only use methods of JCheckBox.

If you already know that you've used MyJCheckBox in a lot of places
where you should use JCheckBox, you can use Refactor | Use Interface
Where Possible to change these usages. But an inspection would be a
nice tool to determine where you could abstract away from the concrete
implementation class in this way.

0
Comment actions Permalink

A long time ago I've asked for a "Type Refactoring" (issue 6017) that
covers this example. Select the "j" and invoke the action to be able
to choose from allowed types for the variable. It would make sense to
preselect the top-most type (here JCheckBox).

Tom

0
Comment actions Permalink

oops, i need to start checking for those ;) Sorry for the redundant posts.

0
Comment actions Permalink

I've already got an old request open for this, #7305. It would be a very good inspection, but there seems to be little interest in it. I was going to tackle it myself in the new Inspection API, but it's one of the few where the new API isn't powerful enough. You could do it for local variables and private instance variables, but whet you really want is to be able to do it for method parameters (possibly with overrides) and method return values (ditto). For those, you need to do global analysis
(equivalent to "Find Usages"), and the InspectionsAPI makes that difficult.

Wierdly enough, IDEA will already do something like this as a post-processing step on "Introduce Interface" and "Introduce Superclass", but as I said there's been little interest in generalizing it. Pity, this could be very powerful.

0

Please sign in to leave a comment.