CodeSOD: Counting References

If you're working in a research field, references matter- specifically, the citations made by your paper and the citations eventually made against yours. But when programming, references can be hard.getProcessor
Dorothy is a scientist, and understands that code itself is a valuable artifact- it's not enough to just to get the solution, but the code itself needs to be maintanable and readable. So when her peers get into trouble, they frequently come to Dorothy to figure out why.

This Java code is one such example:

// convert image stack to correct architecture with scaling if (impType != "GRAY32") { ImageProcessor ip; for (int i = 1; i <= testImage.getStackSize(); i++) { ip = testImage.getStack().getProcessor(i); if (impType == "GRAY16") ip = ip.convertToShortProcessor(true); else ip = ip.convertToByte(true); } }

Without knowing the details, we can already see that there's some stringly-typed data. Java has had enums for a long time, and that'd be a much better way to manage these variations.

But that's boring style nonsense. testImage is an ImagePlus object, which contains a set of ImageProcessor objects. An ImageProcessor wraps an actual image, and has concrete subclasses for various kinds of ImageProcessors.

This code wants to iterate across all the ImageProcessors in an ImagePlus and convert them to a new type. Here's the problem with this approach: the convertTo methods don't modify the object in place: they return a new instance.

The developer has gotten a little lost in their references and the result is that they never update the object they're trying to update: they create a local copy and modify the local copy.

It's a pretty basic mistake, but it's the sort of thing that ends up eating a lot of time, because as you can imagine, nobody actually documents which methods work in place and which return copies, and as you can see they don't even consistently name methods which do the same thing- convertToShortProcessor and convertToByte.

The real WTF though, is that for loop. Array types with 1-based indexes? That's just unforgivable.

[Advertisement] Keep the plebs out of prod. Restrict NuGet feed privileges with ProGet. Learn more.

This post originally appeared on The Daily WTF.

Leave a Reply

Your email address will not be published. Required fields are marked *