Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / November 2006

Tip: Looking for answers? Try searching our database.

Constructor with a lot of arguments?

Thread view: 
howa - 05 Nov 2006 17:02 GMT
If my constructor has a lot of arguments..e.g.

People p  = new People("john", "1960-12-30", "M", ...);

should I write in this way?

People p = new People();
p.setName("john");
p.setBirthday("1960-12-30");
...

but some web site saying this is not a good way also...

so any recommendation for ctor having long arguments?

thanks
ge0rge - 05 Nov 2006 17:35 GMT
> If my constructor has a lot of arguments..e.g.
> People p  = new People("john", "1960-12-30", "M", ...);
[quoted text clipped - 7 lines]
> but some web site saying this is not a good way also...
> so any recommendation for ctor having long arguments?

Looks the same to me (except you write a little more code in the second
instance) and will achieve the same results. I would not make a big deal
of it.

hmm... given that you are a lazy writer (ctor? what's that?), I would
suggest the first approach.

Signature

Your analyst has you mixed up with another patient.  Don't believe a
thing he tells you.

Eric Sosman - 05 Nov 2006 19:43 GMT
> If my constructor has a lot of arguments..e.g.
>
[quoted text clipped - 10 lines]
>
> so any recommendation for ctor having long arguments?

   A constructor with a lot of arguments has the same
disadvantage as a method with a lot of arguments: it's
hard for the programmer to remember what's what while
writing or reading the code.  Different programmers will
have different ideas about how many arguments is "a lot,"
and it may also depend on context (for example, if many
of the arguments come in obvious groups like pairs of
X,Y coordinates, the "perceived" argument count may be
lower than if the arguments were unrelated).

   However, moving arguments out of the constructor
and providing mutator methods has disadvantages, too.
Most obviously, it means you cannot use `final' for
the variables that are now set through mutators.  It
can also make it more difficult to ensure that an object
has a self-consistent state (a constructor can easily
compare birth and death dates and throw an exception if
they're out of order[*], but if the dates are controlled
by mutators the consistency checking is more complex
and more widely diffused).

   [*] and if the person's name is not "P.D.Q. Bach."

   In extreme situations, you may want to create a
special class whose job is to hold data for the one-
argument constructor of the "target" class:

    PersonParameters p = new PersonParameters();
    p.setFirstname("Yankee");
    p.setSurname("Dandy");
    p.setMiddleInitial("D");
    p.setBirthdate("1776-07-04");
    ...
    Person person = new Person(p);

... or the last line might instead be

    Person person = p.makePerson();

   This idea is not really all that strange: think
for a moment about how StringBuffer (or StringBuilder)
gathers data for the eventual construction of a String.

Signature

Eric Sosman
esosman@acm-dot-org.invalid

Lew - 06 Nov 2006 20:35 GMT
>> If my constructor has a lot of arguments..e.g.
>>
[quoted text clipped - 10 lines]
>>
>> so any recommendation for ctor having long arguments?

>     A constructor with a lot of arguments has the same
> disadvantage as a method with a lot of arguments: it's
> hard for the programmer to remember what's what while
> writing or reading the code.  

This is worse if all the arguments are Strings.  One way to manage multiple
arguments is to give them different types:

  public People( String name, Date birth, Gender gender );
  // Gender is (type-safe) enum

In the given example, the ellipsis (...) tells us that even the class author
regards the remaining elements as less "essential" than the first three;
perhaps the { String, Date, Gender } tuple represents some sort of key.

Make such 'key' fields immutable; allowing change to elliptical fields is less
threatening to the People's identity.  Set only the immutable fields in the
constructor.

Override equals() and hashCode() to use just the immutable fields.  This
admits of caching the hash and the toString().

>     However, moving arguments out of the constructor
> and providing mutator methods has disadvantages, too.
> Most obviously, it means you cannot use `final' for
> the variables that are now set through mutators.  

Now you only need attribute methods for the mutable, i.e., "less essential"
fields.

> It can also make it more difficult to ensure that an object
> has a self-consistent state (a constructor can easily
> compare birth and death dates and throw an exception if
> they're out of order[*], but if the dates are controlled
> by mutators the consistency checking is more complex
> and more widely diffused).

Only the dangerous fields contribute to consistency; make those the immutable
fields.  Only the safe fields will be mutable.

>     [*] and if the person's name is not "P.D.Q. Bach."
>
[quoted text clipped - 17 lines]
> for a moment about how StringBuffer (or StringBuilder)
> gathers data for the eventual construction of a String.

A very useful pattern.

-Lew
steve - 06 Nov 2006 22:02 GMT
> If my constructor has a lot of arguments..e.g.
>
[quoted text clipped - 12 lines]
>
> thanks

use the second way.

yes it is longer, but it is 100% clear and extendable, it also allows you to
validate you data correctly.

also i would recommend you make it 'Person' , not people.
because in reality a "people" object" would consist of a group of 'persons'

steve
Casey Hawthorne - 06 Nov 2006 22:58 GMT
Use different types for each argument to avoid mistakes and/or bundle
up some of the arguments into new types.
--
Regards,
Casey


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.