Computing Applicable Methods in Object-Oriented Programming - Prof. Jeremy R. Johnson, Study notes of Programming Languages

How to determine the most specific method to apply for given arguments in object-oriented programming. It discusses the concept of method applicability, sorting methods based on method more specific, and checking classes to determine subclasses. The document also includes a sample assignment and a tutorial exercise.

Typology: Study notes

Pre 2010

Uploaded on 08/19/2009

koofers-user-vej
koofers-user-vej 🇺🇸

10 documents

1 / 13

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
MASSACHVSETTS INSTITVTE OF TECHNOLOGY
Department of Electrical Engineering and Computer Science
6.001|Structure and Interpretation of Computer Programs
Sample assignment
Object-oriented programming
Reading: Section 4.1
Languages for Ob ject-Oriented Programming
This problem set is probably the most dicult one of the semester, but paradoxically, the one
that asks you to write the least amount of code, and for whichyou should have to spend the least
time in lab,
provided that you preparebefore you come to lab
. Instead of asking you to do a lot of
implementation, we are asking you to assume the role of language designer, and to think about and
discuss some issues in the design of languages for object-oriented programming. Note especially
that there is a signicant part of this problem set to be completed
after
you have nished in the
lab.
This problem set has been designed so that the interpreter you will be dealing with is an extension
of the metacircular evaluator in chapter 4 of the book. The implementation below is described
with reference to the programs in the book. In order to understand what is going on, it will be
necessary to work through section 4.1 b efore starting on this assignment.
Although Object-Oriented programming has become very popular, the design of languages to sup-
port Object-Oriented programming is still an area of active research. In this problem set, you will
be dealing with issues that are not well-understood, and around which there are ma jor disagree-
ments among language designers. The questions in this problem set will not ask you to supply
\right answers." Instead, they will ask you to make reasonable design choices, and to be able to
defend these choices. We hope you will appreciate that, once you have come to grips with the
notion of an interpreter, you are in a position to address major issues in language design, even
issues that are at the forefront of current research.
1
Tutorial exercise 1:
Do exercise 4.2 of the notes. Don't actually go to lab to implement this.
Just be able to explain precisely what procedures need to b e modied, what new procedures need
to be written, and what the code must do.
1
This problem set was developed by Hal Ab elson, Greg McLaren, and David LaMacchia. It draws on a Scheme
implementation of Oaklisp by McLaren and a Scheme implementation of Dylan by Jim Miller. The organization of
the generic function code follows the presentation of the Common Lisp Object System (CLOS) in
The Art of the
Metaobject Protocol
,by Gregor Kiczales, Jim des Rivieres, and Dan Bobrow (MIT Press, 1991).
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Computing Applicable Methods in Object-Oriented Programming - Prof. Jeremy R. Johnson and more Study notes Programming Languages in PDF only on Docsity!

MASSACHVSETTS INSTITVTE OF TECHNOLOGY

Department of Electrical Engineering and Computer Science Structure and Interpretation of Computer Programs Sample assignment Ob jectoriented programming

Reading Section 

Languages for Ob jectOriented Programming

This problem set is probably the most dicult one of the semester but paradoxically the one that asks you to write the least amount of co de and for which you should have to sp end the least time in lab provided that you prepare before you come to lab Instead of asking you to do a lot of implementation we are asking you to assume the role of language designer and to think ab out and discuss some issues in the design of languages for ob ject oriented programming Note esp ecially that there is a signi cant part of this problem set to b e completed after you have nished in the lab

This problem set has b een designed so that the interpreter you will b e dealing with is an extension of the metacircular evaluator in chapter  of the b o ok The implementation b elow is describ ed with reference to the programs in the b o ok In order to understand what is going on it will b e necessary to work through section  b efore starting on this assignment

Although Ob ject Oriented programming has b ecome very p opular the design of languages to sup p ort Ob ject Oriented programming is still an area of active research In this problem set you will b e dealing with issues that are not well understo o d and around which there are ma jor disagree ments among language designers The questions in this problem set will not ask you to supply right answers Instead they will ask you to make reasonable design choices and to b e able to defend these choices We hop e you will appreciate that once you have come to grips with the notion of an interpreter you are in a p osition to address ma jor issues in language design even issues that are at the forefront of current research

Tutorial exercise  Do exercise  of the notes Dont actually go to lab to implement this Just b e able to explain precisely what pro cedures need to b e mo di ed what new pro cedures need to b e written and what the co de must do

This problem set was develop ed by Hal Ab elson Greg McLaren and David LaMacchia It draws on a Scheme implementation of Oaklisp by McLaren and a Scheme implementation of Dylan by Jim Miller The organization of the generic function co de follows the presentation of the Common Lisp Ob ject System CLOS in The Art of the Metaobject Protocol by Gregor Kiczales Jim des Rivieres and Dan Bobrow MIT Press 

 Sample assignmentOb jectoriented programming 

 Issues in ob jectoriented language design

Weve already seen two dierent approaches to implementing generic op erations One is data directed programming which relies on a table to dispatch based on the typ es of arguments The second metho d messagepassing represents ob jects as pro cedures with lo cal state As we saw in problem set  these ob jects can b e arranged in complex inheritance relationships such as a troll is a kind of p erson

One drawback with b oth of these approaches is that they make a distinction b etween generic op erations and ordinary pro cedures or b etween message passing ob jects and ordinary data This makes it awkward for example to extend an ordinary pro cedure so that it also works as a generic op eration on new typ es of data For instance we might like to extend the addition op erator so that it can add two vectors rather than having to de ne a separate vectoradd pro cedure

Recent exp eriments with ob ject oriented languages have attempted to integrate ob jects into the core of the language rather than building an ob ject system on top of the language The idea is that everything in the language is an ob ject and al l pro cedures are generic op erations Two such languages b oth based up on Scheme are Oaklisp develop ed in  by Kevin Lang and Barak Pearlmutter at CMU and DylanTM^ Dy namic Lan guage currently under development at the Apple Research Center in Cambridge The language we will implement in this problem set is called MIT TOOL Tiny Ob ject Oriented Language It is essentially a very simpli ed version of Dylan designed to make the implementation an easy extension of the metacircular evaluator of chapter 

 Classes instances and generic functions

The framework well b e using in TOOL which is the same as in many ob ject oriented systems includes basically the same ideas as weve already seen although with dierent terminology An ob jects b ehavior is de ned by its class the ob ject is said to b e an instance of the class All instances of a class have identical b ehavior except for information held in a set of sp eci ed slots which provides the lo cal state for the instance Following Dylan well use the convention of naming classes with names that are enclosed in angle brackets for example account or number

The defineclass sp ecial form creates a new kind of class You sp ecify the name of the class the classs superclass and the names for the slots In TOOL every class has a sup erclass whose b ehavior and slots it inherits There is a prede ned class called object that is the most general kind of ob ject Every TOOL class has object as an ancestor Once you have de ned a class you use the sp ecial form make to create instances of it Make takes the class as argument together with a list that sp eci es values for the slots The order in which the slots and values are listed do es not matter since each slot is identi ed by name For example we can sp ecify that a cat is a kind of ob ject that has a size and a breed and then create an instance of cat Note the use of the getslot pro cedure to obtain the value in a designated slot

 Keep in mind that this use of brackets is a naming convention only like naming predicates with names that end in question mark

 Sample assignmentOb jectoriented programming 

TOOL definegenericfunction say defined generic function say

TOOL definemethod say cat cat stuff object print meow print is TOOL s procedure for printing things print stuff added method to generic function say

TOOL defineclass housecat cat address defined class housecat TOOL define fluffy note that a house cat is a cat and therefore make housecat has slots for breed and size as well size tiny as for address TOOL getslot fluffy breed undefined we never initialized fluffy s breed TOOL say garfield feed me meow feed me TOOL say fluffy feed me meow feed me TOOL say hal feed me No method found  APPLYGENERICFUNCTION

In the nal example TOOL gives an error message when we apply say to the symb ol hal This is b ecause hal is a symb ol not a cat and there is no say metho d de ned for symb ols

We can go on to de ne a sub class of cat

TOOL defineclass showcat cat awards defined class showcat

TOOL definemethod say cat showcat stuff object print stuff print I am beautiful added method to generic function say

TOOL define CorneliusSilverspoontheThird make showcat size large breed Cornish Rex awards prettiest skin undefined

TOOL say corneliussilverspoontheThird feed me feed me i am beautiful TOOL definemethod say cat cat stuff number print cats never discuss numbers added method to generic function say

TOOL say fluffy  cats never discuss numbers

As the nal example illustrates TOOL picks the appropriate metho d for a generic function by examining the classes of all the arguments to which the function is applied This diers from the

 Sample assignmentOb jectoriented programming 

message passing mo del where the dispatch is done by a single ob ject

Notice also that TOOL knows that  is a memb er of the class number In TOOL every data ob ject is a memb er of some class The classes number symbol list and procedure are prede ned with object as their sup erclass Also every pro cedure is a generic pro cedure to which you can add new metho ds The following generic pro cedures are prede ned each initially with a single metho d as indicated by the sp ecializer

 number number  number number number number  number number  number number  number number  number number sqrt number cons object object append list list car list cdr list null object print object getslot object symbol setslot object symbol object

Tutorial exercise  Show how to implement two dimensional vector arithmetic in TOOL by extending the generic functions and  which are already prede ned to work on numb ers De ne a class vector with slots xcor and ycor Arithmetic should b e de ned so that adding two vectors pro duces the vector sum and multiplying two vectors pro duces the dot pro duct

x  y  x  y   x x  y y

Multiplying a numb er times a vector or a vector times a numb er should scale the vector by the numb er Adding a vector plus a numb er is not de ned Also de ne a generic function length such that the length of a vector is its length and the length of a numb er is its absolute value

 The TOOL Interpreter

A complete listing of the TOOL interpreter is app ended to this problem set This section leads you through the most imp ortant parts describing how they dier from the Scheme evaluator in chapter 

EVAL and APPLY

Weve named the eval pro cedure tooleval so as not to confuse it with Schemes ordinary eval The only dierence b etween tooleval and the eval in chapter  are the new cases added to handle the new sp ecial forms definegenericfunction definemethod defineclass and

 Sample assignmentOb jectoriented programming 

An instance is a structure that contains the class of the instance and the list of values for the slots

See the attached co de for details of the selectors and constructors for these data structures

Dening generic functions and metho ds

The sp ecial form

definegenericfunction name

is handled by the following pro cedure

define evalgenericfunctiondefinition exp env let name genericfunctiondefinitionname exp let val makegenericfunction name definevariable name val env list defined generic function name

This pro cedure extracts the name p ortion of the expression and calls makegenericfunction to create a new generic function Then it binds name to the new generic function in the given environment The value returned is a message to the user which will b e printed by the read eval print lo op

Evaldefinemethod handles the sp ecial form

definemethod genericfunction  paramsandclasses  body

for example

definemethod say cat cat stuff number print cats never discuss numbers

In general here genericfunction is the generic function to which the metho d will b e added params andclasses is a list of parameters for this metho d and the classes to which they must b elong and body is a pro cedure b o dy just as for an ordinary Scheme pro cedure^ The syntax pro cedures for this form include appropriate pro cedures to select out these pieces see the co de

Evaldefinemethod rst nds the generic function Notice that the genericfunction piece of the expression must b e evaluated to obtain the actual generic function Evaldefinemethod disas sembles the list of paramsandclasses into separate lists of parameters and classes The parameters the body and the environment are combined to form a pro cedure just as in Scheme The classes b ecome the sp ecializers for this metho d Finally the metho d is installed into the generic function

 The dot b efore the word b o dy signi es that we can put more than one expression in the b o dy just as with ordinary Scheme pro cedures

 Sample assignmentOb jectoriented programming 

define evaldefinemethod exp env let gf tooleval methoddefinitiongenericfunction exp env if not genericfunction gf error Unrecognized generic function  DEFINEMETHOD   methoddefinitiongenericfunction exp let params methoddefinitionparameters exp installmethodingenericfunction gf map lambda p paramlistelementclass p env params makeprocedure makelambdaexpression extract the parameter names from the paramlist map paramlistelementname params methoddefinitionbody exp env list added method to generic function genericfunctionname gf

Tutorial exercise  Evaldefinemethod calls paramlistelementclass in order to nd the class for each parameter Without lo oking at the attached co de predict whether paramlistelementclass should call tooleval Now lo ok at the co de and see if you were right Give a careful explanation of why tooleval is or is not called and what dierence this makes

Dening classes and instances

The sp ecial form

defineclass name superclass  slots

is handled by

define evaldefineclass exp env let superclass tooleval classdefinitionsuperclass exp env if not class superclass error Unrecognized superclass  MAKECLASS   classdefinitionsuperclass exp let name classdefinitionname exp allslots collectslots classdefinitionslotnames exp superclass let newclass makeclass name superclass allslots definevariable name newclass env list defined class name The only tricky part here is that we have to collect all the slots from all the ancestor classes to combine with the slots declared for this particular class This is accomplished by the pro cedure collectslots see the co de

The nal sp ecial form

make class slotnamesandvalues

 Sample assignmentOb jectoriented programming 

define subclass class class or eq class class memq class classancestors class

Finally we need a way to compare two metho ds to see which one is more sp eci c We do this by lo oking at the metho d sp ecializers Method is considered to b e more sp eci c than method if for each class in the list of sp ecializers the class for method is a sub class of the class for method  See the pro cedure methodmorespecific in the attached co de

Tutorial exercise  In the example at the end of section explain how the generic function dispatch cho oses the correct say metho d when we ask the cat fluffy to say a numb er In particular what are all the applicable metho ds In what order will they app ear after they are sorted according to methodmorespecific

Classes for Scheme data

TOOL is arranged so that ordinary Scheme data ob jectsnumb ers symb ols and so onapp ear as TOOL ob jects For example any numb er is an instance of a prede ned class called number which is a class with no slots whose sup erclass is object The TOOL interpreter accomplishes this by having a sp ecial set of classes called schemeobjectclasses If a TOOL ob ject is not an ordinary instance ie an instance data structure as describ ed ab ove the interpreter checks whether it b elongs to one of the Scheme ob ject classes by applying an appropriate test For example anything that satis es the predicate number is considered to b e an instance of number See the co de for details

Initial environment and driver lo op

When the interpreter is initialized it builds a global environment that has bindings for true false nil the pre de ned classes and the initial set of generic functions listed at the end of section  The driver lo op is essentially the same as the driverloop pro cedure in chapter  of the notes One cute dierence is that this driver lo op prints values using the TOOL generic function print By de ning new metho ds for print you can change the way the interpreter prints data ob jects

Tutorial exercise  De ne a print metho d so that TOOL will print vectors which you de ned in exercise  showing their xcor and ycor

 To do in lab

When you load the co de for this problem set the entire TOOL interpreter co de attached will b e loaded into Scheme However in order to do the lab exercises you will need to mo dify only a tiny bit of it This co de has b een separated out in the le mod scm so you can edit it conveniently

 Sample assignmentOb jectoriented programming

To start the TOOL interpreter typ e initializetool  This initializes the global environment and starts the read eval print lo op To evaluate a TOOL expression typ e it after the prompt followed by ctrlx ctrle

In order to keep the TOOL interpreter simple we have not provided any mechanism for handling errors Any error such as an unb ound variable will b ounce you back into Schemes error handler To get back to TOOL quit out of the error and restart the driver lo op by typing driverloop  If you make an error that requires reinitializi ng the environment you can rerun initilializetool but this will make you lose any new classes generic functions or metho ds you have de ned

Lab exercise  Start the TOOL evaluator and try out your vector de nitions from exercise  Also check your answer to exercise  where you de ned a new print metho d for vectors How did TOOL print vectors b efore you added your own print metho d Turn in your de nitions and a brief interaction showing that they work

Lab exercise  One annoying thing ab out TOOL is that if you de ne a metho d b efore youve de ned a generic function for that metho d you will get an error For example in the rst example in section we had to explicitly evaluate

definegenericfunction legged

b efore we could evaluate

definemethod legged thing object Whoknows Otherwise the second expression would give the error that legged is unde ned Mo dify the TOOL interpreter so that if the user attempts to de ne a metho d for a generic function that do es not yet exist TOOL will rst automatically de ne the generic function One thing to consider In which environment should the name of the generic function b e b ound the global environment the environment of the evaluation some other environment There is no right answer to this questionyou are the language designer But whatever choice you make write a brief paragraph justifying your choice In particular include an example of a program for which the choice of environment matters ie where the program would have a dierent b ehavior or p erhaps give an error if the choice were dierent Hint The only pro cedure you should need to mo dify for this exercise is evaldefinemethod Turn in along with your design justi cation your mo di ed co de together with a brief interaction showing that the mo di ed interpreter works as intended

Lab exercise  Another inconvenience in TOOL is that we need to use getslot in order to obtain slot values It would b e more convenient to have TOOL automatically de ne selectors for slots For example it would b e nice to b e able to get the x and y co ordinates of a vector by typing xcor v and ycor v rather than getslot v xcor and getslot v ycor  Mo dify the interpreter to do this Namely whenever a class is de ned TOOL should automatically de ne a generic function for each of its slot names together with a metho d that returns the corresp onding slot value for arguments of that class Turn in a listing of your co de and an example showing that it works Hint The only part of interpreter you need to mo dify for this exercise is evaldefineclass

 Sample assignmentOb jectoriented programming 

 Write a clear  page description of your language extension This description should b e geared toward the user of the language It should include a simple but realistic and non trivial example of a program that involves multiple sup erclasses The example should illustrate how your language handles each of the three issues a b and c You should also explain how the language deals with each of these issues in general

 For each of design choices you illustrated in part give an alternative choice you could have made and explain briey why you think your choice is b etter If you cant think of any other choice you might have made then say so

 As carefully as you can but without actually writing any co de sp ecify the pro cedure that the evaluator should follow in cho osing which metho d to select when applying a generic function to a given set of arguments Your description should b e clear enough so that someone could implement this pro cedure based up on your sp eci cation

Optional extra credit Implement your design for multiple sup erclasses in TOOL and demon strate that it works The TOOL interpreter was designed to make this not to o dicult but it will involve a considerable numb er of small changes to the co de and is likely to b e time consuming