Presentation is loading. Please wait.

Presentation is loading. Please wait.

Composition Phil Tayco San Jose City College Slide version 1.2

Similar presentations


Presentation on theme: "Composition Phil Tayco San Jose City College Slide version 1.2"— Presentation transcript:

1 Composition Phil Tayco San Jose City College Slide version 1.2
Created Sep. 30, 2018

2 Dates Some data types, such as Dates, appear to need to be stored as Strings As a String type, a Date can be useful for presentation purposes, but not necessarily so for evaluation purposes: Is a date before or after another date? What day of the week is the given date? To answer these questions with the date stored as a String requires parsing the data Dates can also have multiple formats (US, European, 2 or 4 digit year,…) Extra work can be done to handle these format situations but OO designers will approach it differently

3 Dates Dates actually contain multiple parts (properties) that imply creating a complex data type Such data types suggest designing a class As we design more classes, we start applying a consistent approach to consistently define them All classes have 2 major components: properties/attributes and behaviors (functions/methods) We address properties by asking “what does this class we want to model have?” We address behaviors by asking “what do we want this class to be able to do?”

4 Date Properties With potential class property, we ask what their respective data types will be For our Date class, we can at least say that each Date has a month, day and year For each one of these properties, we can also say that we’ll define their data types as int That immediately establishes some code: public class Date { private int month; private int day; private int year; }

5 Date Properties Given that, we immediately have 7 functions to consider: At least a default constructor 3 Set methods for month, day and year properties 3 Get methods Other functions can be developed as well: Multiple constructors (int, int, int) or just (int) Predicate methods to check if the Date is valid or is a leap year Notice now that at the very least, we can put together the function signatures for each of these potential functions

6 Date Properties public class Date { private int month;
private int day; private int year; public Date() public Date(int, int, int) public void setMonth (int) public int getMonth() // …other set/get methods for day and year public boolean isValid() public boolean isLeapYear() }

7 Date Properties All of these functions you can immediately write
You can create your own test main program with your own data to test each of the functions (this is called “black box testing”) Notice how these function signatures also inform other potential programmers how your Date class could be used The signatures act as an “Interface” for “Application Programmers” to use – a.k.a. “API” Note how we develop and test the Date class functions – it is treated as a stand-alone class It is also useful to develop a method that creates a String version of the object (in Java, this is the toString() method)

8 Date Properties public String toString() { return String.format(“%2d/%2d/%4d”, month, day, year); } This function returns the month, day, and year of the Date object in the form of a String such as “09/13/2018” String representations of objects are very useful functions particularly for testing purposes In Java, toString is called by default when an object is needed in the form of a String “System.out.println(myDate);” is a good example of wanting to print an object Java will see myDate as needed to be a String. Since myDate is a Date object, it implicitly calls the toString method of the Date class

9 Back to Student Now let’s return to the Student class and add a property to the Student class to support date of birth: public class Student { private int id; private String dateOfBirth; } This is a nice start and easily supported and you can add appropriate set/get methods, constructors and so forth accordingly However, it is limited in what you can do with it to do any evaluation with the dateOfBirth (such as an “isAdult” predicate function) Remember when selecting a property, that we have to choose a data type In this case, the Date class we created can be reused here

10 Composition public class Student { private int id; private Date dateOfBirth; } Classes that contain properties that are other classes is designing using “Composition” How does this complicate matters? There is definitely more to keep in mind when completing the class design, but the rule of thumb is to keep development consistent: Once you defined the properties, create the constructors and supporting methods as normal The purpose of a constructor is to initialize all properties of the object at instantiation. To initialize a property with a class data type, you are creating another object Now let’s look at a constructor for Student

11 Default Constructor public Student() { id = -1; dateOfBirth = new Date(); } dateOfBirth is just another property and in the Student default constructor, we need to give dateOfBirth a default initial value dateOfBirth can represent this by using its default constructor This implies when classes contain properties that are classes, they require using that property’s appropriate constructors within them This is powerful code reuse, but also implies that defining these behaviors must be clear If a default Date value is “1/1/1900” and you decide to change that to something else, Student is impacted

12 Another Constructor public Student(int i, int m, int d, int y) { id = i; dateOfBirth = new Date(m, d, y); } dateOfBirth is initialized using the constructor that receives 3 integers The 3 integers are provided through the instantiation of the Student constructor – this means the code creating the Student object must know to provide 4 integers for id, month, day and year (an API comes in handy here) For the default constructor, it was not given any values to use to create a Date object – that is why we used the default Date constructor What if we had a Student constructor that only took one integer for id?

13 Another Constructor public Student(int i) { id = i; dateOfBirth = new Date(); } Like the default Student constructor, we don’t have enough information to instantiate dateOfBirth We have information for id, but that’s it so we have to instantiate dateOfBirth with the default This stresses the importance of having a default constructor. In this example, other classes are using the class as a property and may not have enough information to instantiate, thus relying on the use of a default Now let’s move to other functions – how can we check if a Student was born before 2000?

14 Predicates public boolean isMillennial() { return (dateOfBirth.getYear() >= 2000); } Note the signature for this predicate function – it returns a boolean and we are using information already inherent within the object – this is consistent as we’ve seen with other predicates In this case, the property to use is dateOfBirth and specifically, we need to see if the year is before 2000 Note we have to use getYear() to do this – even though dateOfBirth is using Date in Student, the properties of Date are hidden

15 Testing Complex Objects
Don’t forget the main program. At first we used it to test Date objects. Now we can add testing Student objects as well public static void main(String args[]) { Student s1 = new Student(); Student s2 = new Student(101, 5, 19, 1995); if (s2.isMillennial()) System.out.println(“Young”); } It seems straightforward but also raises questions How does creating a String version of a Student change? Can I create a Student object with a Date object? How does this impact the set methods for Student? How would I design the Student object to maintain age?

16 Complex Objects as Strings
public String toString() // this is defined in Student { return String.format( ??? ) } With the Date class’ toString function, we created a String version of the object by making a String from the month, day and year properties We can do the same thing with a Student object by looking to create a String from the Student’s id and dateOfBirth We are fortunate in Java that this is automatically done by it implicitly calling the toString function of a class when a String version of an object is needed

17 Complex Objects as Strings
public String toString() // this is defined in Student { return String.format(“%d:%s”, id, dateOfBirth); } This returns a String version of a Student object by implicitly calling the toString function of the Date class when we need a String version of the dateOfBirth This allows for separate and parallel maintenance of Student and Date classes because of their stand-alone ability (you can change the toString function in Date and affect Student) Class design rule of thumb: design properties, create constructors, set/get methods and a function to create a String version of the object

18 Objects as Parameters Since objects are instances of data types, we can use them in function calling, but you have to be careful because this is call by reference! public static void main(String args[]) { Date d1 = new Date(2, 29, 1996); Student s5 = new Student(102, d1); } Here we are creating a Student object s5 using a Date object already created in d1 This means we need a constructor in Student that takes Date as an input parameter. No problem right?

19 Objects as Parameters public Student(int i, Date d) { id = i; dateOfBirth = d; } Here we are given a Date object as an input parameter stored in d and using that to assign the object’s dateOfBirth property to it This seems okay, but note that the Date object is a pass by reference which means “d” here is a reference to the original Date object created (which is “d1” in main)

20 Objects as Parameters Current picture after the constructor is called
s5’s dateOfBirth points to the same object as d1 Most important: main may not know this!! s5 102 d1 0x1234abcd 0x1234abcd 2 29 1996

21 Objects as Parameters Now when we change d1 in main, we change s5’s dateOfBirth as well! public static void main(String args[]) { d1.setMonth(10); System.out.println(s5); } This may actually be something you want to do or it may not Most important is to know that this is going on and occurs with all objects that are passed into functions To separate this, we can use the information from the d1 object passed in to create a new instance of dateOfBirth in the constructor

22 Objects as Parameters public Student(int i, Date d) { id = i; dateOfBirth = new Date(d.getMonth(), d.getDay(), d.getYear()); } Here we are using the given Date object to “get” all the object properties The dateOfBirth is explicitly creating a “new” Date object when the Student object is created – this will earn its own place in memory that is separate from d1 Deciding between instantiating objects and reusing the reference is a design call – knowing how both approaches work is essential

23 Objects as Parameters Current picture after the constructor is called
d1 can now be changed in main independent of s5 and vice versa with s5’s dateOfBirth s5 102 d1 0x1234abcd 0x3f4a2290 2 29 1996 2 29 1996

24 Copy Constructors public Student(int i, Date d) { id = i; dateOfBirth = new Date(d); } Notice the difference with this code from the previous code slide Instead of passing in Date properties to the constructor, we are passing in (a reference to) a Date object The Date constructor in this case will need to copy the values from the given Date to the new object being constructed The advantage here is that the Date class already knows all the properties it has and can code the constructor in this case accordingly

25 Copy Constructors public Date(Date d) { month = d.getMonth(); day = d.getDay(); year = d.getYear(); } This type of constructor that takes an object of its own type to create a new object is called a “copy constructor” Notice that even though the Date class knows the properties of Date, it still must use the d object’s get methods access d’s values Benefits with this approach: The Date copy constructor owns the process – any code using it simply only has to pass in the object to copy If the Date class changes, the copy constructor can adjust accordingly and code using stays the same

26 Set Methods The constructors also imply design decisions for putting together set methods with Composition As class designer, we get to decide what to make available - set with a specific sub-properties or with an object public static void main(String args[]) { d2 = new Date(4, 8, 1960); s5.setDateOfBirth(3, 29, 2007); s5.setDateOfBirth(d2); } Note that both “setDateOfBirth” properties have the same name but with different input parameter types (a.k.a. overloading)

27 Set Methods Overloading and Composition gives us different ways to support creating set methods public void setDateOfBirth(int m, int d, int y) { dateOfBirth = new Date(m, d, y); } public void setDateOfBirth(Date d) dateOfBirth = new Date(d);

28 Other Design Considerations
What about an age property for Student? We could take the traditional approach: public class Student { private Date dateOfBirth; private int age; } This means we create the normal adjustments to constructors, toString, set/get methods etc. age is available for immediate use, but now the question is, does its value need to be stored? By storing it, the value would need to be maintained appropriately, particularly when: dateOfBirth changes The Student object “has a birthday”

29 Other Design Considerations
If you store the value, simply saying “return age” in the “getAge()” method might be inaccurate Calculating age is a function of date of birth and current day. Since you have access to these values, getAge may be better designed to calculate on the fly: public int getAge() { // Date currentDate = code to get System date // Return age based on currentDate and dateOfBirth } The pseudocode here implies more work every time getAge is required but may be considered a more reliable value when obtaining the Student object’s age

30 Summary Composition is the design of a class where one of its properties is another class you’ve created All classes designed this way are treated independently – one class does not know it is being used in another Maintaining code with composition is more complex but the concepts are still all applied consistently as if the properties were simple data types Passing objects as input parameters are by reference which is significant for constructors Modifying set and get methods may be necessary depending on the class and property context Good to develop a method to return a String version of the object (toString in Java)

31 Programming Exercise 2 Part 1: Create an Address class with properties for street number, street name, street type, city, state, and zip code Create property types, set/get methods and constructors based on the OO guidelines discussed to this point No predicate methods are necessary unless you want to add some in of your choice Create a toString method (if you are not using Java, create a method that converts the object into a String) Create a main program that tests all methods similar to what you did for exercise 1

32 Programming Exercise 2 Part 2: Modify your House class from exercise 1 to use the Address class in part 1 If you already have an address property in your current House class, change its data type to this class Address If you don’t have an address property, add it in Modify all existing methods as necessary to support the addition or change of your address property If you had to change the address property from String to Address, do not change the existing methods you have and use overloading appropriately instead Create a toString method for your House class using address appropriately Show in main testing all methods and constructors in your new House class (you can add this code in main to the test code you wrote in main for part 1)

33 Programming Exercise 2 You should have an Address class and a House class with one main program testing all methods in each class You do not need to create an interactive program with the user this time – you can hard code creating a objects and calling methods as long as you show you’ve tested everything You are free to add methods and classes as you like as long as these minimum requirements are met – if you do, though, remember that the testing rules apply such that all methods must be called from main to show they work as designed


Download ppt "Composition Phil Tayco San Jose City College Slide version 1.2"

Similar presentations


Ads by Google