Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Declaring and instantiate values

Status
Not open for further replies.

cleanair4me

Technical User
May 16, 2008
61
0
0
I am using this JavaBean but I think I shouldnt be declaring String type with emply values and also instantiating the bean in the no arg constructor with null values:
Code:
public class SimpleBean  {
 
	private String firstname = "";
                private String lastname = "";
 
	public SimpleBean() 
                {
                      firstname = null;
                      lastname = null;
                }
 
..

Please advise how I should be doing this?
 
I am no guru at this stuff but the way I normally do is

public class MyBean {

private String fname = StringUtil.EMPTY;

public MyBean(String fname) {
this.fname = fname;
}

public String getFname() {
return fname;
}

public void setFname(String fname) {
this.fname = fname;
}

}


I normally create Util classes such as StringUtil where I will have common methods and stuff. EMPTY is just a constant with value "".

I usually avoid assigning null to variables. If you do forget to check for null then are screwed.

Also I keep 1. constructors that accepts no arguments, 2. constructors that accepts mandatory properties as args 3. constructors that accepts all the properties as args. This way you can declare you obj the way you like.

I am going to watch this thread to see what others recommend.
 
Well - a bill for Mr. "" "" will not produce a NullPointerException, so it might be harder to detect than an bill for Mr. null null. That might screw you even more.

@cleanair4me:
You code ist mostly equivalent to:
Code:
public class SimpleBean  
{
    private String firstname, lastname;
just using more noise.
I'm not used to Beans, but afaik you provide getters and setters for every attribute, but that wasn't your question - was it?

In your example your Bean get's loaded with firstname = "", but the constructor will later set firstname to null.
Without an alternative constructor that doesn't make sense, and with one, hardly.

don't visit my homepage:
 
Thanks for your replies.

I ended up changing it to:
Code:
public class SimpleBean  {
 
    private String firstname = "";
    private String lastname = "";
  
    //use default no arg constructor and I dont need any other constructors for this bean..
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top