I fooled around with for
-loops, remembered the with
keyword from delphi and came up with following pattern (defined as a live template in IntelliJ IDEA):
for ($TYPE$ $VAR$ = $VALUE$; $VAR$ != null; $VAR$ = null) {
$END$
}
Should I use it in productive code? I think it might be handy for creating temporary shortcut variables like these one-character variables in lamdas and couting for loops. Plus, it checks if the variable you are going to use in the block is null
first. Consider following case in a swing application:
// init `+1` button
for (JButton b = new JButton("+1"); b != null; add(b), b = null) {
b.setForeground(Color.WHITE);
b.setBackground(Color.BLACK);
b.setBorder(BorderFactory.createRaisedBevelBorder());
// ...
b.addActionListener(e -> {
switch (JOptionPane.showConfirmDialog(null, "Are you sure voting +1?")) {
case JOptionPane.OK_OPTION:
// ...
break;
default:
// ...
break;
}
});
}
Best Answer
It's not an anti-pattern, because that would mean it is a commonly used technique that's problematic somehow. This code fails to meet the "commonly used" criterion.
However, it is problematic. Here are some of its problems:
new
never returns null.)