OPEN SOURCESHIPPED

Open Source: Apache Commons Imaging

Refactored a complex method in Apache's pure-Java imaging library and wrote tests for its untested branches. Cyclomatic complexity went from 20 to 8, and branch coverage of getImageInfo went from 83% to 96%.

ROLEContributor
TEAMApache Commons community
TIMELINEJan 2026 - Mar 2026
CATEGORYOpen Source

20 → 8

CYCLOMATIC COMPLEXITY

83% → 96%

BRANCH COVERAGE

20 (by hand)

DECISION POINTS COUNTED

Overview

Apache Commons Imaging is a pure-Java library for reading and writing images, and it gets used all over the Java ecosystem. Our software engineering course at KTH had us work on a real codebase, and I picked the PNG handling code. The plan was to bring down the complexity of one function and improve the test coverage around it.

What I did

  • Counted all 20 decision points of the target function by hand. The lizard tool reported a different CCN than the textbook formula, so I went through it again, this time counting exit points, to work out where the difference came from.
  • Refactored the function by moving logic into helper methods and replacing inline values with named constants. Cyclomatic complexity dropped from 20 to 8 and the behaviour stayed the same.
  • Wrote JUnit tests for error and edge-case branches that weren't covered before: empty chunks, duplicate PHYS/SCAL chunks and missing palettes. Branch coverage of getImageInfo went from 83% to 96%.

What I learned

The library is around 20 years old, and a lot of its complexity is there because of some old bug fix. Writing the tests before refactoring made the changes much less scary, since I could check after every step that nothing had broken.

APPENDIX A // MEDIA

IMAGE SLOT · AWAITING UPLOAD

FIG.01 · COVERAGE REPORT BEFORE AND AFTER THE NEW JUNIT TESTS