2.6.10 Designing Constructors

Designing Constructors

Design the Team creation contract around what the caller knows and what Team should initialize itself. A constructor is more useful when its parameters have clear responsibilities.

Choose supplied values and owned objects
Team creation decisions
Information Choice Reason
Team name Caller supplies string Different teams have different names
Captain Caller supplies Player reference The player already exists
Roster list Team creates internally Team owns its roster storage
Initial captain entry Team registers internally Avoid a separate setup step

This continues the received-reference and contained-object examples.

Review a constructor before writing it

A suitable signature is public Team(string name, Player captain). The body assigns the supplied name and captain, creates its list, and registers the captain. State that the supplied captain must be non-null, unless the design explicitly handles that case.

  1. List the state needed for a usable initial object.
  2. Identify which values vary between instances.
  3. Decide whether each related object is received or created internally.
  4. Order initialization so references exist before they are used.
  5. Review every creation call and verify the resulting state.
Leave later behavior as behavior

A long parameter list can be difficult to read. Begin with small contracts and use named local variables for supplied objects. Do not introduce extra classes or advanced syntax just to shorten a beginner example.

Apply the idea
Check your understanding