Search code examples
javaif-statementcoding-stylejtextfield

set an attribute with or without check


I've learnt that's better first to check if an attribute is already as I like and only then to set it again. If I'm wrong, just say it!

Short example: If I want to clear an JTextField (set text to ""), should I check the existing value first and if it's not yet correct, set a blank string.

...
if (!jtextfield.getText().equals("")) {
    jtextfield.setText("");
}
...

Or should I set the text directly without checking first?

...
jtextfield.setText(""); 
...

Which of these versions is better? Which do you prefer?


Solution

  • Checking if jTextfield returns null or not is a can be a good practice.

    if (jtextfield!=null) 
         jtextfield.setText("");