Search code examples
javaapirefactoringreadability

Java: Best practices for turning foreign horror-code into clean API...?


I have a project (related to graph algorithms). It is written by someone else.

The code is horrible:

  • public fields, no getters/setters
  • huge methods, all public
  • some classes have over 20 fields
  • some classes have over 5 constructors (which are also huge)
  • some of those constructors just leave many fields null
    (so I can't make some fields final, because then every second constructor signals errors)
  • methods and classes rely on each other in both directions

I have to rewrite this into a clean and understandable API.

Problem is: I myself don't understand anything in this code.

Please give me hints on analyzing and understanding such code.

I was thinking, perhaps, there are tools which perform static code analysis and give me call graphs and things like this.


Solution

  • Oh dear :-) I envy you and not at the same time..ok let's take one thing at a time. Some of these things you can tackle yourself before you set a code analyzing tool loose at it. This way you will gain a better understanding and be able to proceed much further than with a simple tool

    • public fields, no getters/setters
      • make everything private. Your rule should be to limit access as much as possible
    • huge methods, all public
      • split and make private where it makes sense to do so
    • some classes have over 20 fields
      • ugh..the Builder pattern in Effective Java 2nd Ed is a prime candidate for this.
    • some classes have over 5 constructors (which are also huge)
      • Sounds like telescoping constructors, same pattern as above will help
    • some of those constructors just left many fields null
      • yep it is telescoping constructors :)
    • methods and classes rely on each other in both directions
      • This will be the least fun. Try to remove inheritance unless you're perfectly clear it is required and use composition instead via interfaces where applicable

    Best of luck we are here to help