44
Encapsulation and Data Abstraction Testing Applications in Smalltalk

Encapsulation and Data Abstraction Testing Applications in Smalltalk

Embed Size (px)

Citation preview

Encapsulation and Data Abstraction

Testing

Applications in Smalltalk

Object-oriented Programming and Design

2

Encapsulation and Data Abstraction

An object should hide design decisions from its users what is stored / what is computed classes used

Can’t hide everything Interface of object Interface of parameters of object

Object-oriented Programming and Design

3

Encapsulation

Class contains variables and all the code that accesses the variables.

Code should go with data.

Overuse of accessing methods is a sign of poor encapsulation

Code that uses a lot of accessing methods of an object should be moved to that object

Object-oriented Programming and Design

4

Encapsulation

(aPoint x squared + aPoint y squared) sqrt aPoint r

Some patterns (State, Strategy) break encapsulation. These are exceptions to the general rule that code should go with data.

Object-oriented Programming and Design

5

Inside/outside

Class describes the implementation of an object

Users care about specifications of object Interface (Java, C++) Pre and post-conditions (Eiffel) Tests, examples, English description (all

languages)

Types of arguments/results

Smalltalk does not check types at compile time

Programmer needs to know types Method names tell:

Type of returned object Role of arguments

• addEmployee:

Object-oriented Programming and Design

6

Side effects

Names indicate whether method has side effect Nouns, property – no side effect Command – changes state of object

• add:, remove:

Object-oriented Programming and Design

7

Object-oriented Programming and Design

8

Tests

See if feature works Make sure changes don’t break anything. Document features. Measure of completeness.

Object-oriented Programming and Design

9

Test-driven development

Write test for new feature first, then implement the feature.

Stop when tests work.

Use the simplest design that makes all the tests work

Refactor to eliminate duplication

Object-oriented Programming and Design

10

SUnit

The testing framework.

Each test is written in a subclass of TestCase.

Test is a method of the form “testXXX” Each subclass is a group of related tests.

Object-oriented Programming and Design

11

TestRunner

Object-oriented Programming and Design

12

Important TestCase methods

assert: aBoolean deny: aBoolean should: aBlock should: aBlock raise: anException shouldnt: aBlock shouldnt: aBlock raise: anException

Object-oriented Programming and Design

13

Test first design

How should feature work? Give example Write test case Make test work Write another test case Make test work ...

Object-oriented Programming and Design

14

Problems with test first

What about testing GUIs? What about testing real-time systems?

Tests show the presence of flaws, not their absence.

What about design?

Object-oriented Programming and Design

15

But you can’t test everything!

Testing increases your confidence. Testing involves tradeoffs - better testing is

more expensive. Testing is never perfect; you can’t afford

perfection. Zero testing is always wrong; you must

decide how much is enough.

Object-oriented Programming and Design

16

You can’t test everything

You can’t specify everything. Automated tests with Sunit are easy and

cheap most of the time. Hard to test hardware. Hard to test concurrent systems. Most parts of a system are easy to test;

write automated tests for them.

Object-oriented Programming and Design

17

Finding abstractions

Do one thing Eliminate duplication Keep rate of change similar Decrease coupling, increase cohesion Minimize interfaces Minimize size of abstractions Minimize number of abstractions

Object-oriented Programming and Design

18

Do one thing

Method should do what its name says Class should be what its name says

Break complex classes/methods into simpler ones

Object-oriented Programming and Design

19

Eliminate duplication

(Ranks indexOf: rank) < (Ranks indexOf: argument rank)

self rankIndex < argument rankIndex

Object-oriented Programming and Design

20

Keep rate of change similar

Separate initial conditions from an algorithm’s temporary variables

Separate tax tables from employee data from time cards

Use “timer” to separate quickly changing information from slowly changing

Object-oriented Programming and Design

21

Decrease coupling, increase cohesion

Coupling is dependencc between components Cohesion is dependence within a component

Object-oriented Programming and Design

22

Minimize interfaces

Use the smallest interface you can Use Number instead of Float

Avoid embedding classes in names add: instead of addNumber:

Don’t check the class of an object

Object-oriented Programming and Design

23

Mimize size of abstractions

Methods should be small median size is 3 lines 10 lines is starting to smell

Classes should be small 7 variables is starting to smell 40 methods is starting to smell

Object-oriented Programming and Design

24

Minimize number of abstractions

Can only learn 4-5 new things at a time. 3 is better

A class hierarchy 6-7 levels deep is hard to learn

Break large system into subsystems, so people only have to learn part of the system at a time

Object-oriented Programming and Design

25

A Payroll System

PayrollSystem keeps track of employees.

Employee knows salary, how much has been earned, how much has been payed, how much taxes have been withheld. Employee should be able to tell us about past transactions, not just current balances.

Object-oriented Programming and Design

26

Object Model for Payroll

EmployeeEmployeeTransaction

PayrollSystem

post:

date

Paycheck

Timecard

SalaryChangesalarypay, taxes

hoursWorkedvacation

A class with a method #post:

A payroll systemhas a set ofemployees.

An employee has aset of transactions(and a transactionis for an employee) Timecard, paycheck

and salarychangeare kinds of employee transactions

postTo::

abstract classabstract class

abstract methodabstract method

** **

Object-oriented Programming and Design

27

EmployeeObject subclass: #Employee

instanceVariableNames: 'name transactions salary earned paid withholding accruedVacation taxRule'classVariableNames: 'HeadTaxRate MarriedSeparateTaxRate MarriedTaxRate SingleTaxRate'poolDictionaries: ''category: 'CS598rej-Payroll HW2'

Object-oriented Programming and Design

28

Employee Comment

(View/Comment in RB)

I represent an employee in a payroll system. Thus, I keep track of the number of hours worked, the wages paid, the vacation accrued, the taxes withheld, and so on. My values change only when transactions are posted to me. Transactions are subclasses of EmployeeTransaction.

Object-oriented Programming and Design

29

(continued)

Variables

name <String>

transactions <Collection of Transactions, sorted by date posted>

salary <Number>

...

taxRule <TaxRule>

Object-oriented Programming and Design

30

Hiding classes

Employee knows class Timecard Users of Employee do not

Employee creates Timecards for users

Object-oriented Programming and Design

31

Using Employee

| ralph |

ralph := Employee new name: 'Ralph Johnson'.

ralph changeSalaryFor: (Date newDay: 5 year: 1996) to: 20.

ralph postTimeCardFor: (Date newDay: 10 year: 1996) hoursWorked: 40

vacation: 0.

Object-oriented Programming and Design

32

Testing Employee

EmployeeTest is a subclass of TestCase

testOvertime

| ralph |

ralph := Employee new named: 'Ralph Johnson'.

ralph changeSalaryFor: day1 to: 20.

payroll addEmployee: ralph.

self postTimeCards: aLittleOvertime to: ralph..

self assert: ralph earned = 3500.0

Object-oriented Programming and Design

33

Initializing an Employee

named: aString

name := aString.

transactions := OrderedCollection new.

salary := 0.

...

taxRule := SingleTaxRate

Object-oriented Programming and Design

34

Complete Creation Method

Employee has the class method

named: aString

^self new named: aString

Object-oriented Programming and Design

35

Timecard

Timecard is a subclass of EmployeeTransaction

with instance variables 'hoursWorked' and 'hoursVacation '

Object-oriented Programming and Design

36

Initializing a Timecard

date: aDate employee: anEmployee worked: hoursW vacation: hoursV

date := aDate.

employee := anEmployee.

hoursWorked := hoursW.

hoursVacation := hoursV

Object-oriented Programming and Design

37

Complete Creation Method

Timecard has class method

date: aDate employee: anEmployee worked: hoursW vacation: hoursV

^self new date: aDate employee: anEmployee worked: hoursW vacation: hoursV

Object-oriented Programming and Design

38

Using a Timecard

Employee has method:

postTimeCardFor: aDate hoursWorked: hoursW vacation: hoursV

self postTransaction: (Timecard date: aDate employee: self worked: hoursW vacation: hoursV)

Object-oriented Programming and Design

39

Initialization PatternsThere should be one or more methods that initialize object. They should be in

protocol "initialize-release".

There should be one or more class methods that create initialized objects. They should be in protocol "instance creation".

Object-oriented Programming and Design

40

Processing a Transaction

In Employee:

postTransaction: aTransaction

aTransaction postTo: self.

transactions add: aTransaction

Object-oriented Programming and Design

41

Processing a TimecardpostTo: anEmployee

| money overtime nonovertime |

overtime := (hoursWorked - 40) max: 0.

nonovertime := hoursWorked min: 40.

money := (overtime * 1.5 + nonovertime) * anEmployee salary.

anEmployee incrementEarned: money.

Object-oriented Programming and Design

42

Processing a Timecard

salary

^salary

incrementEarned: anAmount

earned := earned + anAmount

Object-oriented Programming and Design

43

Employee Action Protocol

All changes to an Employee should be recorded as transactions.

postTimeCardFor: aDate hoursWorked: hoursW vacation: hoursV

self postTransaction:

Object-oriented Programming and Design

44

Assignment

Look up assignment on speedy.cs.uiuc.edu:2500

Create a page for yourself on the “people in the class” page

Choose a time to meet with me to discuss the assignment