[Java] Calling Font.deriveFont(int) when Font.deriveFont(float) was intended

The method java.awt.Font.deriveFont has two easily confusable overloads: deriveFont(int), which changes the style (eg. bold or italic), and deriveFont(float), which changes he size of the font.
Most of the time, the programmer intends to call the second, especially when math is involved, but in the absence of explicit casting to float or operations that involve floats, the overload deriveFont(int) is wrongly called.
(Note that deriveFont(int), as well as the java.awt.Font constructors, silently ignore invalid styles)

This can be the cause of (minor) graphical issues that can be hard to track down: font sizes not being what’s expected, or text that appears bold or italic for no apparent reason.

In general, the rule should raise an issue whenever the overload deriveFont(int) is called with anything other than the constants Font.PLAIN, Font.BOLD, or Font.ITALIC, or the expressions Font.BOLD | Font.ITALIC and Font.ITALIC | Font.BOLD. (Combining PLAIN with BOLD or ITALIC ought to be considered wrong as per javadoc of the latter)

There is an argument to be made about the compliance of font.deriveFont(0) as equivalent to font.deriveFont(Fond.PLAIN), since a zero-size font makes little sense. For consistency, I believe it should be considered noncompliant.

Noncompliant Code:

font.deriveFont(12); // Noncompliant, meant to set font size but style was set instead
font.deriveFont(font.getSize() * 2); // Noncompliant, doesn't actually double size
font.deriveFont(anotherFont.getSize()); // Noncompliant (!), actually meant to copy size

Compliant Code:

font.deriveFont(12.0f); // Float constant
font.deriveFont(font.getSize() * 2.0f); // Using floating-point math
font.deriveFont((float) anotherFont.getSize()); // Explicit cast to float


font.deriveFont(Font.BOLD); // Explicitly using style constants

Hi @ivaniesta14,

Thank you for engaging with the community!

I really like this rule idea and created a rule proposal ticket for it. You can track progress here: https://sonarsource.atlassian.net/browse/SONARJAVA-4887.

All the best,


1 Like