Use constructor or setter method?

Posted by user633600 on Programmers See other posts from Programmers or by user633600
Published on 2012-06-29T05:18:35Z Indexed on 2012/06/29 9:23 UTC
Read the original article Hit count: 190

I am working on a UI code where I have an Action class, something like this -

    public class MyAction extends Action {
      public MyAction() {
          setText("My Action Text");
          setToolTip("My Action Tool tip");
          setImage("Some Image");
      }
    }

When this Action class was created it was pretty much assumed that the Action class wont be customizable (in a sense- its text, tooltip or image will be not be changed anywhere in the code). Of late, now we are in need of changing the action text at some location in code. So I suggested my co-worker to remove the hardcoded action text from the constructor and accept it as an argument, so that everybody is forced to pass the action text. Something like this code below -

public class MyAction extends Action {
    public MyAction(String actionText) {
        setText(actionText);
        setTooltip("My Action tool tip); 
        setImage("My Image"); 
    }
}

He however thinks that since setText() method belongs to base class. It can be flexibly used to pass the action text wherever action instance is created. That way, there is no need to change the existing MyAction class. So his code would look something like this.

MyAction action = new MyAction(); //this creates action instance with the hardcoded text
action.setText("User required new action text"); //overwrite the exisitng text.

I am not sure if that is a correct way to deal with problem. I think in above mentioned case user is anyway going to change the text, so why not force him while constructing the action. The only benefit I see with the original code is that user can create Action class without much thinking about setting text.

© Programmers or respective owner

Related posts about java

Related posts about design