I am currently working on a project based on the struts 2 framework with my colleagues and we were discussing something about overloading setters. Nevertheless, this thread is more related to Java Beans, rather than the struts framework. I am not very experienced in Java Beans and I'd like to get some advices on it.
Suppose we have a pseudo bean with enum variables, getters and setters:
We want to use this bean to collect data from a html form, but we realise there are some casting problems - submitted data from the form is in type of String rather than being automatically casted into MyEnum.
So I suggested to overload the setter:
I've tried building and running on my local environment - it seems to work. My colleague could not get that run perfectly and also complained that this is a bad bean practice. He said that if we overload a setter method with different number of parameters, that'll be ok, but if we overload the setter method with the same number of parameters but of different types, this will break things.
I am not very experienced in beans. May be this is a bad practice but I believe my overloading should work, shouldn't it? I'd like to hear views from others.
I don't see the need for overloading because overloading Javabean setters can lead to ambiguity (depending on the framework that is using the Javabean) and affects code readability. Since the data from a html form is a String, stick to the void setE(String s) method and discard the void setE(MyEnum e) method.
Joined: Jul 25, 2011
Sorry, has been away for a while.
He thinks it's a bad practise because it is easy to confuse other developers.
Also there is one thing that I am double of: He said that if there are more than one setter of one argument(despite type difference), struts 2 framework will pick a setter by randomly and try to stuff in the html data regardless of type.
Anyone knows if this is true? I am not entirely sure but I think all html form data are passed in as Object and Struts converts the data to String type if it is convertible. "Random" isn't a word I would link to a good programming language like Java or a commonly used framework like struts. That's my opinion... not sure if "random" is really the case.
Although my first thought to solution is to remove the Enum setter and just use the String setter, the Enum setter is actually there for some other classes to interact with, so I would preferably keep the Enum setter if possible. May be someone here can suggest a better practise?