Simula and Smalltalk (Presentation)
Simula and Smalltalk (Presentation)
Simula67
Firstobjectorientedlanguage Designedforsimulation
SimulaandSmalltalk
JohnMitchell
Laterrecognizedasgeneralpurposeproglanguage
Briefhistory
NorwegianComputingCenter
Designers:Dahl,Myhrhaug,Nygaard Simula1in1966(strictlyasimulationlanguage) Generallanguageideas
InfluencedbyHoare Hoares sideasondatatypes Addedclassesandprefixing(subtyping)toAlgol60
ComparisontoAlgol60
Addedfeatures
classconcept referencevariables(pointerstoobjects) passbyreference char text, char, text I/O coroutines Changeddefaultparpassingfrompassbyname somevarinitializationrequirements own(=Cstatic)variables stringtype(infavoroftexttype)
Nygaard
OperationsResearchspecialistandpoliticalactivist Wantedlanguagetodescribesocialandindustrialsystems Allowordinarypeopletounderstandpolitical(?)changes
Removed
DahlandMyhrhaug
Maintainedconcernforgeneralprogramming
ObjectsinSimula
Class
Aprocedurethatreturnsapointertoitsactivationrecord
Example:Circlesandlines
Problem
Findthecenterandradiusofthecircle passingthroughthreedistinctpoints,p,q, andr p r q
Object
Activationrecordproducedbycalltoaclass
Solution
DrawintersectingcirclesCp,Cqaroundp,q andcirclesCq,Craroundq,r(Picture assumesCq=Cq) Drawlinesthroughcircleintersections Theintersectionofthelinesisthecenter ofthedesiredcircle. Errorifthepointsarecolinear.
Memorymanagement
Objectsaregarbagecollected
userdestructorsconsideredundesirable
ApproachinSimula
Methodology
Representpoints,lines,andcirclesasobjects. Equipobjectswithnecessaryoperations.
SimulaPointClass
classPoint(x,y);realx,y; formal p is pointer to Point begin booleanprocedureequals(p);ref(Point)p; ifp=/=nonethen equals:=abs(x p.x)+abs(y p.y)<0.00001 realproceduredistance(p);ref(Point)p; ifp==nonethenerrorelse distance:=sqrt((x p.x)**2+(y p.y)**2); end***Point*** p: newPoint(1.0,2.5); q: newPoint(2.0,3.5); ifp.distance(q)>2then...
uninitialized ptr has value none
Operations
Point
equality(anotherPoint):boolean distance(anotherPoint):real(neededtoconstructcircles)
Line
parallelto(anotherLine):boolean(toseeiflinesintersect) meets(anotherLine):REF(Point)
Circle
intersects(anotherCircle):REF(Line)
pointer assignment
Representationofobjects
p access link real x real y proc equals p q proc distance 1.0 2.5 code for equals code for distance
Simulalineclass
classLine(a,b,c);reala,b,c; begin booleanprocedureparallelto(l);ref(Line)l; ifl=/=nonethenparallelto:=... ref(Point)proceduremeets(l);ref(Line)l; beginrealt; ifl=/= / noneand d~ ~parallelto(l) ll lt (l)th then... end; reald;d:=sqrt(a**2+b**2); ifd=0.0thenerrorelse begin d:=1/d; a:=a*d;b:=b*d;c:=c*d; end; end***Line***
Local variables
line determined by ax+by+c=0
Procedures
DerivedclassesinSimula
Aclassdeclmaybeprefixedbyaclassname
classA AclassB AclassC BclassD
Subtyping
Thetypeofanobjectisitsclass Thetypeassociatedwithasubclassistreatedasa subtypeofthetypeassocwithsuperclass Example:
class l A(); A( ) ... AclassB();... ref(A)a: newA() ref(B)b: newB() a:=b/*legalsinceBissubclassofA*/ ... b:=a/*alsolegal,butruntimetest*/
Mainobjectorientedfeatures
Classes Objects Inheritance(classprefixing) Subtyping Virtualmethods
Afunctioncanberedefinedinsubclass Combinescodeofsuperclasswithcodeofsubclass
FeaturesabsentfromSimula67
Encapsulation
Alldataandfunctionsaccessible;noprivate,protected
Self/SupermechanismofSmalltalk
Inner Inspect/Qua
runtimeclass/typetests
Classvariables Exceptions
NotfundamentallyanOOfeature...
SimulaSummary
Class
procedure"thatreturnsptrtoactivationrecord initializationcodealwaysrunasprocedurebody
Smalltalk
Majorlanguagethatpopularizedobjects DevelopedatXeroxPARC
Smalltalk76,Smalltalk80wereimportantversions
Objects:closurecreatedbyaclass Encapsulation
protectedandprivatenotrecognizedin1967 addedlaterandusedasbasisforC++
Objectmetaphorextendedandrefined
Used U dsomeideas id from f Simula, Si l but b verydifferent diff lang l Everythingisanobject,evenaclass Alloperationsaremessagestoobjects Veryflexibleandpowerfullanguage
SimilartoeverythingisalistinLisp,butmoreso Example:objectcandetectthatithasreceivedamessageit doesnotunderstand,cantrytofigureouthowtorespond.
Subtyping:determinedbyclasshierarchy Inheritance:providedbyclassprefixing
Motivatingapplication:Dynabook
ConceptdevelopedbyAlanKay Smallportablecomputer
Revolutionaryideainearly1970s
Atthetime,aminicomputer wassharedby10people, storedinamachineroom.
Smalltalklanguageterminology
ObjectInstanceofsomeclass ClassDefinesbehaviorofitsobjects SelectorNameofamessage MessageSelector S l t t together th with ithparameter t values l MethodCodeusedbyaclasstorespondtomessage InstancevariableDatastoredinobject SubclassClassdefinedbygivingincremental
modificationstosomesuperclass
Whatwouldyoucomputeonanairplane?
InfluenceonSmalltalk
Languageintendedtobeprogramminglanguageand operatingsysteminterface Intendedfornonprogrammer Syntaxpresentedbylanguagespecificeditor
Example:Pointclass
Classdefinitionwrittenintabularform
class name super class class l var instance var Point Object pi i x y
Classmessagesandmethods
Threeclassmethods newX:xvalueY:yvalue|| ^selfnewx:xvalue y:yvalue newOrigin|| ^selfnewx:0 y:0 initialize|| pi< 3.14159 Explanation - selector is mix-fix newX:Y: e.g, Point newX:3 Y:2 - symbol ^ marks return value - new is i method th d in i all ll classes, l inherited from Object - | | marks scope for local decl - initialize method sets pi, called automatically - <- is syntax for assignment
class messages and methods names and code for methods... instance messages and methods names and code for methods...
Instancemessagesandmethods
Fiveinstancemethods Explanation x:xcoordy:ycoord|| set x,y coordinates, x< xcoord e.g, pt x:5 y:3 y< ycoord moveDx:dxDy: y dy y|| move point i t by b given i amount t x< dx+x y< dy+y x||^x return hidden inst var x y||^y draw|| return hidden inst var y ...codetodrawpoint... draw point on screen
Runtimerepresentationofpoint
to superclass Object Point class Point object class x y 3 2 Method dictionary
Detail: class method shown in dictionary, but lookup procedure distinguishes class and instance methods
Template x y
Inheritance
Definecoloredpointsfrompoints
class name super class class var instance var color class messages and methods newX:xv Y:yv C:cv code instance messages and methods color draw | | ^color code override Point method new method ColorPoint Point new instance variable
Runtimerepresentation
Point object 2 3 Point class Template x y Method dictionary newX:Y: draw move ColorPoint class Template x y color Method dictionary newX:Y:C: color draw ...
This is a schematic diagram meant to illustrate the main idea. Actual implementations may differ.
EncapsulationinSmalltalk
Methodsarepublic Instancevariablesarehidden
Notvisibletootherobjects
pt txi isnot tallowed ll dunless l xi isamethod th d
Objecttypes
Eachobjecthasinterface
Setofinstancemethodsdeclaredinclass Example:
Point{x:y:, x:y: moveDx:Dy:, moveDx:Dy: x, x y, y draw} ColorPoint{x:y:,moveDx:Dy:,x,y,color,draw}
Butmaybemanipulatedbysubclassmethods
Thislimitsabilitytoestablishinvariants Example:
Superclassmaintainssortedlistofmessageswithsome selector,sayinsert Subclassmayaccessthislistdirectly,rearrangeorder
Thisisaformoftype
Namesofmethods, doesnotincludetype/protocolof arguments
Objectexpressionandtype
Sendmessagetoobject
pdrawpx:3y:4
Subtyping
Relationbetweeninterfaces
Supposeexpressionmakessense
pmsg:pars OKifmsgisininterfaceofp
SubtypingandInheritance
Subtypingisimplicit
Notapartoftheprogramminglanguage Importantaspectofhowsystemsarebuilt
Inheritance I h it is i explicit li it
Usedtoimplementsystems Noforcedrelationshiptosubtyping
Subtyping
Ifinterfaceissuperset,thenasubtype Example:ColorPointsubtypeofPoint Sometimescalledconformance
CollectionHierarchy
Collection
at: isEmpty, size, includes: ,
SmalltalkFlexibility
MeasureofPLexpressiveness:
Canconstructsofthelanguagebedefinedinthe languageitself? Examples:
Lispcond:Lispallowsuserdefined specialforms MLdatatype:sufficienttodefinepolymorphiclists, equivalenttobuiltinlisttype MLoverloading:limitation,sincenotavailableto programmer C/C++:???
Indexed Updatable
at:Put:
Set
add: remove:
Dictionary Array
replaceFrom:to:with: associationAt:
Sorted collection
sortBlock:
Subtyping Inheritance
Smalltalkisexpressiveinthissense
M h ld b i i i h
Smalltalkbooleansandblocks
BooleanvalueisobjectwithifTrue:ifFalse:
Classboolean withsubclassesTrue andFalse TrueifTrue:B1ifFalse:B2executes B1 FalseifTrue:B1ifFalse:B2 executes B2
SelfandSuper
Integer SmallInt LargeInt g
Exampleexpression
i<jifTrue:[iadd1]ifFalse:[jsubtract1] i<jisbooleanexpression,producesboolean object argsareblocks,objectswithexecutemethods
Sincebooleansandblocksareverycommon
Ingallstest
DanIngalls:principaldesignerSmalltalksystem
GraceMurrayHopperawardforSmalltalkand BitmapgraphicsworkatXeroxPARC 1987ACMSoftwareSystemsAwardwithKay Kay, Goldberg
Smalltalkintegeroperations
Integerexpression
xplus:1times:3plus:(yplus:1)print
Properties
Alloperations i areexecuted d b bysending di messages Ifxisfromsomenewkindofinteger,expression makessenseaslongasxhasplus,times,print methods.
Actually,compilerdoessomeoptimization. Butwillreverttothisifxisnotbuiltininteger.
Proposedtestforobjectoriented
Canyoudefineanewkindofinteger,putyournew integersintorectangles(whicharealreadypartof thewindowsystem),askthesystemtoblackena rectangle,andhaveeverythingwork? Smalltalkpasses,C++failsthistest
CostsandbenefitsoftrueOO
WhyispropertyofIngallstestuseful?
Everythingisanobject Allobjectsareaccessedonlythroughinterface Makesprogramsextensible
SmalltalkSummary
Class
createsobjectsthatsharemethods pointerstotemplate,dictionary,parentclass
Whatisimplementationcost?
Everyintegeroperationinvolvesmethodcall
Unlessoptimizingcompilercanrecognize manycases
Isthisworthit?
Oneapplicationwhereitseemsuseful? Oneapplicationwhereitseemstoocostly? Are there other issues? Security? (wait for Java final
Subtyping:implicit,nostatictypesystem Inheritance:subclasses,self,super
SingleinheritanceinSmalltalk76,Smalltalk80
Rubywww.rubylang.org
Rubyisacomplete,full,pureobjectorientedlanguage
AlldatainRubyareobjects,inthesenseofSmalltalk Example:thenumber1isaninstanceofclassFixnum
ExampleRubyclass
class Song @@plays = 0 def initialize(name, artist, duration) @name = name @artist = artist @duration = duration @plays = 0 end def play @plays += 1 @@plays += 1 "This song: #@plays plays. Total #@@plays plays." end end
Veryflexible
Canaddmethodstoaclass,oreventoinstanceduringruntime Closures Automaticsmallinteger(Fixnum)largeinteger(Bignum)conversion
Singleinheritance only
Rubyfeaturessingleinheritanceonly,*onpurpose* Modulesarecollectionsofmethods
Aclasscanimportamoduleandgetsallitsmethods
see http://www.rubycentral.com/book/