sixtytrees
sixtytrees

Reputation: 1233

Separation of code to different classes [Java]

I have a bloated JDialog class (~2000 lines) that displays two unrelated JTables. I want to split it into three classes (JDialog, Jtable1 and JTable2). I can study which variables and which methods are used by each table and move them to relevant classes, but this manual refactoring is going to be tedious.

Is there any way to automate such refactoring?


To achieve this a script should have an accumulator of tokens. First token is, for instance jTable2 from panel.add(jTable2). Now check all lines that have jTable2 in them and add tokens to accumulator. Repeat search for relevant tokens until new tokens are not discovered. Now for each token find lines that contain it. Expand selection to include brackets.

It is hard to believe that programmers of the arguably largest language haven't created such a tool yet. This should be pretty similar to find usages tool in IDE.

Upvotes: 0

Views: 295

Answers (3)

kc2001
kc2001

Reputation: 5247

Take a look at this post (How to refactor thousands of lines of Java code? Is there any tool available?) that asks a similar question.

Basically, there are some production quality tools that help you extract classes once you know what it is what you want to put in the classes. Notably, IntelliJ's IDEA has a good "extract class" refactoring.

The harder part is determining what should go into those classes. AFAIK, there are only research tools available for that.

Upvotes: 0

user6683490
user6683490

Reputation:

In NetBeans you can use Refactor->move. It starts a wizard that conveniently displays relevant methods. You need to select them that you want to move, but you don't have to hunt in code. Other IDEs have similar functionality.

This way you still have to think, but the boring part of finding them is done for you by IDE.

Upvotes: 1

duffymo
duffymo

Reputation: 308763

Automatic? No, thank goodness. Refactoring requires thought. Deep learning isn't there yet.

Most IDEs (e.g. IntelliJ from JetBrains, the best IDE on the market) has excellent refactoring support.

But it won't think for you.

One piece of advice: You'll have better luck if you have unit tests, do it in small incremental bites, and use a version control system. Write a test, make a change, show that the test still passes, commit the change, repeat.

You can always go back to the last working version that way. You won't make a bigger mess than a single incremental step.

I think you can do even better: look at moving listeners and processing code out of the UI, too. Swing apps end up with big classes because people learn to cram everything into the UI classes. If you decompose it you'll find that the code is easier to read, more modular, and easier to unit test.

Upvotes: 6

Related Questions