This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I think that I do not understand the meaning of the get and set methods in java beans. May be someone could help me with a simple example. Say, I have a property ItemCost and in my java bean and I have
1. if the ItemCost is assigned by the "developer" manually; say, 24.99, it is the get or the set method in which I insert the value 24.99? I mean, it is
2. if the value of ItemCost is found and retrieved from the database to populate the java bean, it is the get or set method via which the property is assigned a value? 3. if the value of ItemCost is supplied by the visitor by filling out a text field, and of course ItemCost = request.getParameter( "NameOfTextField" ); then, it is the get or set method via which this property of the java bean is populated? I am not even sure that I ask the right questions. Anyway, I am very confused. Please help. [ December 24, 2003: Message edited by: JiaPei Jen ] [ December 24, 2003: Message edited by: JiaPei Jen ]
I think the example given can be changed slightly in trying to understand the workings of a Java Bean. The setters are used to get values from an actor of some sort and then getter help to get a result based upon this set item. I would say something like:
This could have been written differently in a normal Java class by doing the following:
However, the use of Java Beans will facilitate being able to use the JSP useBean feature and avoid having scriptelets in your code which call the latter metod etc. HTH
The secret to creativity is knowing how to hide your sources.
I think you may be missing the idea that the "getter" and "setter" methods are for use by other code. All a "getter" should do is to return the value of an object attribute. All a "setter" should do is set an object attribute to a supplied value. For example:
Other code can use this in any way it likes. For example:
I'm not sure quite what you mean by "if the code developer wants to assign a value manually". To set a value in your code you can do it lots of different ways. Here are a few examples:
call "setter" from somewhere in your code: ugh.setName("Frank");
assign a default value for the attribute when an object is created, so calling the "getter" will return a reasonable value even if the "setter" has never been called:
provide your bean class witha constructor which automatically sets attributes to supplied values when an object is created:
if your value will never need to change, you can have a "getter" without having a "setter". In this case, the "getter" can just return the value, without storing it as an attribute:
Has that helped at all? [ December 27, 2003: Message edited by: Frank Carver ]