Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSE 501N Fall ‘09 06: Data Abstraction & Design

Similar presentations


Presentation on theme: "CSE 501N Fall ‘09 06: Data Abstraction & Design"— Presentation transcript:

1 CSE 501N Fall ‘09 06: Data Abstraction & Design
15 September 2009 Nick Leidenfrost

2 Lecture Outline Conditional Statements Revisited The this keyword
else if The switch statement The conditional ternary The this keyword Program design Class relationships Design Exercises

3 Review: if / else Conditional statements allow us to conditionally execute statements Based on value of boolean expressions if ( conditional ) { // Statements } else { if ( conditional ) { // Statements } if ( conditional ) // Statement

4 else if An if statement can be used as the statement executed by an else clause if (count == 0) { // Statements } else if (count < 0) { else { if (count == 0) { // Statements } else if (count < 0) {

5 Multiple Cases if / else statements can be ‘chained together’ to test for multiple cases if (count == 0) { // Statements } else if (count == 1) { else if (count == 2) { else if (count == 3) {

6 The switch Statement The switch statement evaluates an expression, then attempts to match the result to one of several possible cases The switch statement can be used to replace long chains of else if conditions

7 Syntax: switch The general syntax of a switch statement is: switch and
case are reserved words switch ( expression ) { case value1: statement-list1 case value2: statement-list2 case value3: statement-list3 case ... } If the result of expression matches value2, control jumps to here The values held by case statements must be constant expressions (not variables)

8 The switch Statement The implicit boolean condition in a switch statement is equality (==) The expression of a switch statement must result in an integral type, meaning an int Okay: int, short, char, enum* Assignable to int Not okay: long It cannot be a boolean value, a floating point value (float or double) You cannot perform relational checks with a switch statement

9 The switch Statement Often a break statement is used as the last statement in a case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

10 Error: Unreachable Statement
The switch Statement A switch statement with break: switch (count) { case 0: zeroCount++; break; case 1: oneCount++; case 2: twoCount++; doSomething(); } Error: Unreachable Statement

11 The default case is traditionally last, but does not have to be last
The switch Statement A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch The default case is traditionally last, but does not have to be last switch (value) { case 1: doSomething(); break; case 2: doSomethingElse(); break; default: eatIceCream(); }

12 The ternary operator Allows for quick, one line conditional execution
Best for conditional assignments Conditional (predicate) Statement to execute if true double max = (valueOne > valueTwo) ? valueOne : valueTwo; Statement to execute otherwise

13 The this Reference me, myself, and I
The this reference allows an object to refer to itself Think of this as a variable that refers to the currently executing object We can interact with the this reference in almost the same way as any other object variable We can perform assignments, supply this as the actual parameter of a method invocation, or use the dot operator to reference / invoke fields and methods Exception: This cannot be used as the left-hand side of an assignment. this = new BankAccount(1000, 500.0);

14 The this Reference Typically, this is used when referencing instance variables, or the object itself inside methods this can also be used to invoke methods on the object public class BankAccount { public void withdraw (double amount) { if (amount > this.balance) this.borrowMoney(amount); this.balance -= amount; } public class BankAccount { public void withdraw (double amount) { this.balance -= amount; }

15 The this Reference Self-Commenting Code
this can also help to increase the readability of our code When another programmer sees a variable referenced with this and the dot operator, it is immediately evident that the variable is an instance variable We don’t have to search for a local variable declaration, we know immediately what we are interacting with public class BankAccount { public void withdraw (double amount) { this.balance -= amount; }

16 The this Reference public void withdraw (double amount) { this.balance -= amount; } account1.withdraw(500); account2.withdraw(10); In the first invocation, the this reference refers to account1, in the second it refers to account2 this is often used to supply the “current” object as a parameter // Inside a method of the BankAccount class bank.awardInterest(this);

17 The this reference Removing Ambiguity
The this reference can also be used to distinguish the instance variables of a class from corresponding method parameters with the same names The constructor of the BankAccount class could have been written as follows: The this keyword used with the dot operator tells Java that we are referring to the instance variable name Notice that the name of the formal parameter is the same as the name of the instance variable. protected String name; protected double balance; public BankAccount (String name, double balance) { this.name = name; this.balance = balance; }

18 What is the end result of these assignments?
The this reference When a local variable (or formal parameter) has the same name as an instance variable, Java chooses the variable that is most relevant to the context The local variable is used This can cause very subtle problems: What is the end result of these assignments? protected String name; protected double balance; public BankAccount (String name, double balance) { name = name; balance = balance; }

19 Designing Software Object-Oriented Design
Although there are established styles and paradigms for object-oriented design, the practice as a whole is subjective No absolute right and wrong way Kind of like writing an essay… One approach to OO Design is Top-Down First identify high-level entities in the program What attributes do the entities have? (state) How should the entities interact to manipulate that state? (behavior)

20 Designing Software Identifying High Level Entities
The core activity of object-oriented design is determining the classes and objects that will make up the solution The classes that comprise our solution may be part of a class library, reused from a previous project, or newly written One way to identify potential classes is to identify the objects discussed in the requirements Objects are generally nouns, and the services (behavior) that an object provides are generally verbs

21 Identifying Classes and Objects …From a Formal Requirements Document
A partial requirements document: Of course, not all nouns will correspond to a class or object in the final solution, but this generally a good way to get an initial breakdown of the classes in a design. The user must be allowed to specify each product by its primary characteristics, including its name and product number. If the bar code does not match the product, then an error should be generated to the message window and entered into the error log. The summary report of all transactions must be structured as specified in section 7.A.

22 Identifying Classes and Objects Determining Class Granularity
Sometimes it is challenging to decide whether something should be represented as a class For example, should an Employee's address be represented as a set of instance variables or as an Address object The more you examine the problem and its details the more clear these issues become Is functionality that would be in this class reusable? Can this class provide functionality for two or more uses? Do the interactions of this functionality obscure the purpose of the class that is using it?

23 Identifying Classes and Objects Determining Class Granularity
When a class becomes too complex, it often should be decomposed into multiple smaller classes to distribute the responsibilities public class Employee { protected String address1, address2; protected String city, state, zipcode; public String getAddressLineOne () { return address1; } public String setAddressLineOne (String address1) { this.address1 = address1; } ...

24 Identifying Classes and Objects Determining Class Granularity
When a class becomes too complex, it often should be decomposed into multiple smaller classes to distribute the responsibilities public class Employee { protected Address address; public String getAddress () { return address; } public String setAddress (Address address) { this.address = address; public class Address { protected String address1, address2; protected String city, state, zipcode; public String getAddressLineOne () { return address1; } public String setAddressLineOne (String address1) { this.address1 = address1; } ...

25 Identifying Classes and Objects The Appropriate Level of Detail / Abstraction
We want to define classes with the proper amount of detail For example, let’s say we want to design a program to control the various systems of a house it may be unnecessary to create separate classes for each type of appliance in a house It may be sufficient to define a more general Appliance class with appropriate instance data It all depends on the details of the problem being solved

26 Identifying Attributes
We know that classes often mimic real-world entities and the instance variables that define the state typically model attributes of the real world entity What attributes do we care about in our program? What attributes are unimportant? Is the attribute something that is transient, e.g., not actually stored in an instance variable, but calculated from other attributes? E.g. the GPA of a Student

27 Identifying Behavior Every activity that a program must accomplish must be represented by one or more methods in one or more classes Generally, methods get verbs for names Or short verb-oriented phrases We should start to think about: What behavior should be accessible to other classes and their objects (public) What behavior should be more closely guarded (private, default (package protected), protected) In early stages it is not necessary to determine every method of every class – begin with primary responsibilities and evolve the design

28 Class Relationships Classes in a software system can have various types of relationships to each other Three of the most common relationships: Dependency: A uses B Aggregation: A has-a B Inheritance: A is-a B

29 Dependency I Need You. A dependency exists when one class relies on another in some way, by referencing the fields or invoking the methods of the other: Our Calculator class from Lab 1 depends on the Math object public double exp (double a, double b) { return Math.pow(a, b); }

30 Balancing Dependency A Two-Sided Blade
Numerous / complex dependencies among classes Dependencies should use methods as much as possible Dependency on implementation specific entities (instance variables) creates susceptibility to change Example: GPA Classes that don't depend on others Forces us to reinvent functionality Role or purpose of class would not be as clear Muddied by code that is not central to the purpose of the class A good design strikes the right balance

31 Aggregation You Complete Me.
An aggregate is an object that is made up of other objects Therefore aggregation is a has-a relationship A car has-a chassis In software, an aggregate object contains references to other objects as instance variables The aggregate object is defined in part by the objects that make it up This is a special kind of dependency – the aggregate usually relies on the objects that compose it

32 Aggregation For example, a Student object is composed, in part, of Address objects A student has an address (in fact each student probably has two addresses) [Example on the board]

33 Inheritance We’re Practically Related.
Inheritance allows us to use an existing, more generalized, class to create more specific functionality Leverages existing functionality Reduces code duplication Allows for polymorphism Much more on this later…

34 Data Abstraction Hey! Don’t touch that!
Enforcement of clear separation between Abstract properties of a data type (class) and Concrete details of its implementation What does this mean?

35 Data Abstraction Defining the Granularity of Interaction
A separation between what is publicly viewable and what is encapsulated Decide what other entities should be able to access / manipulate Use access modifiers and packages to define encapsulation Define accessor and mutator methods to define access / manipulation of state What is publicly viewable in a data type? Typically a subset of its methods On occasion certain public variables or constants

36 ADT Exercises Bank Account Football League A Card Game

37 Questions? Lab 2 will be assigned on Wednesday Lab 1.5 due by Midnight
Lab now in Sever 201


Download ppt "CSE 501N Fall ‘09 06: Data Abstraction & Design"

Similar presentations


Ads by Google