Quick Index
A Solution Without and With Components


Problem Statement
  • Code a "Contact" type
  • It should be able to print a mailing address (like shown here).
Buddy Baker
100 Apple Road
Big City, UT
99930
Solution (Without Composition)
Here we try a solution without composition. We add five ivars to Contact. All the ivars are primitive/basic values like String types (not full objects/components).
Contact (with five ivars)
	name
	street
	city
	state
	zip
Solution (Without Composition - Code)
Here is the code.
public void printMailingLabel()  {
	prn(this.name);
	prn(this.street);
	prn(this.city);
	prn(",");
	prn(this.state);
	prn(this.zip);
}
Address Type Identified
We realized that there is an existing "USAddress" type as shown here. Or, alternatively, we code it.
USAddress
	street
	city
	state
	zip
}
Solution (WITH Composition)
Here is our solution with composition.

Much simpler.
Contact (one ivar - a component)
	name
	address (type USAddress)
Solution (WITH Composition - Code)
Here is the revised code using composition.

Where did all the code go? Our component "address" is doing the work for us -- we are thankful.

Simple is good.
public void printMailingLabel()  {
	prn(this.name);
	prn(this.address.toMailingString());
}


How Did We Do It?


The first thing we did is add a component (ivar) of type Address.
public class Contact {
	private String name;
	private USAddress address;

	//etc (more code follows)

}
Then we look at the menu of method headers for Address.java.

We note that "toMailingString" looks very helpful.
public String getStreet()
public String getCity()
public String getState()
public String getZip()
public String toMailingString()
Then we simply sent "toMailingString" to our child object
public class Contact {
	private String name;
	private USAddress address;

	public void printMailingLabel()  {
		prn(this.name);
		prn(this.address.toMailingString());
	}

	//etc (more code follows)

}

Where Did The Component Class Come From?


Two possibilities:


Often, we'll code our own components. We prefer more lighter classes vs fewer heavier classes. Here's why:


Side note: With our design it is not difficult to swap in another address type e.g. CanadianAddress. We'll learn more later.

Here is the source code for the component class and parent class.