Listoflectures TDDA69DataandProgramStructure ObjectOrientedProgramming andtypesystems CyrilleBerger 1IntroductionandFunctionalProgramming 2ImperativeProgrammingandDataStructures 3Parsing 4Evaluation 5ObjectOrientedProgrammingandtype 6Macrosanddecorators systems 7VirtualMachinesandBytecode 8GarbageCollectionandNativeCode 9DistributedComputing 10DeclarativeProgramming 11LogicProgramming 12Summary 2/56 Lecturecontent ObjectOrientedProgramming Object-OrientedConcepts Implementation Revisitingthevisitorpattern ObjectOrientedProgramming Exceptions Typesystem 3/56 Non-structuredProgramming ProgramOrganizingTechniques Themainprogramdirectlyoperates onglobaldata Non-structuredProgramming Program StructuredProgramming mainprogram/data Impracticalwhentheprogramgets sufficientlylarge Thesamestatementsequencemust becopiedifitisneededseveraltimes ModularProgramming Object-OrientedProgramming 5 ProceduralProgramming ModularProgramming Combineasequenceofstatementsintoa procedurewithcallsandreturns Themainprogramcoordinatescallstoprocedures andhandsoverappropriatedataasparameters Program mainprogram/data Procedure1 Procedure2 6 Proceduresofacommonfunctionalityaregrouped togetherintoseparatemodules. Themainprogramcoordinatescallstoproceduresin separatemodulesandhandsoverdataasparameters. Program mainprogram/data Module1data+data1 Procedure3 Procedure1 Tasksareacollectionofstates,structuresand procedures 7 Procedure2 Module2data+data2 Procedure3 8 LimitationsofStructuredandModularProgramming Unrestrictedaccesstoglobaldata Globaldata1 Procedure1 Globaldata2 Procedure2 Procedure3 Globaldata3 Object-OrientedConcepts Procedure4 Attributesandbehaviorsare seperated Notextensible 9 WhatisObject-OrientedProgramming? WhatisanObject? Real-worldobjectsarecomposedof attributesandbehaviors Amodelingtechnique Itisanaturaltechnique Attributes:color,size,... Behaviors:accelerate,brake,... Theworldismadeofobjects:house,tree,car, computer... Programobjects Allowtodescribeaprogram beforeitiswritten Attributesarestates/variables Behaviorsarefunctions 11 12 Object-OrientedConcepts Class Anobjectisaspecificinstance(iethiscar, thiscomputer...) Aclassisatypeofobject(ieacar,a computer...) Class Inheritance Encapsulation Polymorphism Itisablueprintofobject Theclassdefines: Thedefaultsetofvariables Thedefaultsetoffunctions Aninitialisationfunction(calledconstructor Theobjectisaninstanceofaclass Itpointstoaspecificmemorylocationwiththeactualvalues forvariables 13 ClassCar 14 Inheritance classCar: Someclasseshavecommonpart attributes: Audiisacar,Volvoisacar,butVolvoandAudi aretwodifferenttypeofcars colorcanbered,green,blue... speedfrom0tomax_speed max_speedandmax_accelerationareconstant Inheritanceallowstodefineaclass intermofanothersuper-class Sub-classes functions: accelerateincreasespeedwithmax_acceleration brakedecreasespeedwithmax_acceleration object: canaddnewvariablesandfunctions overridevariablesandfunctionsfromthe super-class red_audi:={color:'red',max_speed:200, max_acceleration:10} blue_volvo:={color:'blue',max_speed:180, max_acceleration:7} 15 16 InheritancefromtheclassCar Encapsulation Encapsulationistheabilitytohide variables classCar:color,speed, max_speedandmax_acceleration classAudi:classCarwith max_speed:=200and max_acceleration:=10 classVolvo:classCarwith max_speed:=180and max_acceleration:=7 Threecommonlevelsofhiding: Private:onlyaccessibletotheobject Protected:onlyaccessibletotheobjectandthrough inheritance Public:accessibletotheworld 17 18 TheadvantagesofObject-OrientedProgramming Polymorphism polymorphismistheabilitytoappear inmanyforms Itistheabilitytocallafunctiononan objectthatwillexecutedifferentcode fordifferentobjects Forexample,ashapeclasswithan areafunctionandtriangle,square... Itisonewayofcreatinggenericcode 19 Codereusability Codecansharedinthesuperclass Polymorphismallowtodefineinterfaces Inheritenceclarifiesthe relationshipamongprogram elements Encapsulationallowmodularity andcontrolonaccesstovariables 20 ImplementingObject-OrientedProgramming (Almost)anyimperative programminglanguagecanbe madetosupportobject-oriented programming Implementation Forinstance,firstC++compilerwascompiling toCandmanyobjectsystemshavebeen addedtoC 22 Definingmembers:variables Definingmembers:functions Allyouneedisadictionnary InJavaScript/ECMAScript: Allmostallyouneedistosavelambdas obj={value:1.0,dosomething:function(){return42;}} obj={value:1.0,name:'someobject'} console.log(obj.value) console.log(obj['value']) Buthowtoaccessthevariables? Youeitherneedtopassapointertothe object InPython classTest def__init__(self): self.value=1.0 self.name='someobject' obj=Test() print(obj.value) console.log(obj.__dict__['value']) Implicitely,likeinJavaScript/ECMAScript: obj={value:1.0,getValue:function(){returnthis.value;}} Explicitely,likeinPython: classTest def__init__(self): self.value=1.0 defgetValue(self): returnself.value InC: typedefstruct{floatvalue;constchar*name}Object; Objectobj={1.0,"someobject"}; 23 24 Convenientobjectcreation Whataboutclasses? Withdictionnarywehaveobjects Foraclass,allweneedisaconstructor Anewoperator operator: function__new(constructor) { varargs=[{}]; for(vari=1;i< arguments.length;++i) { args.push(arguments[i]) } constructor.apply(null,args); returnargs[0]; } function__construct_car(self,color,max_speed,max_acceleration) { self.color=color self.speed=0.0 self.max_speed=max_speed self.max_acceleration=max_acceleration self.accelerate=function(){self.speed=Math.min(self.max_speed, self.speed+self.max_acceleration)} self.decelerate=function(){self.speed=Math.max(0,self.speedself.max_acceleration)} } __new(create_car,'red', 200,10) varobj={}; __construct_car(obj,'red',200,10) Aclassdefinitionfunction: functiondefine_class(constructor) { returnfunction() { varargs=[constructor]; for(vari=0;i< arguments.length;++i) { args.push(arguments[i]) } return__new.apply(null,args) } } Car= define_class(__construct_car) Car('red',200,10) 25 26 TheofficialwayinJavaScript/ECMAScript Inheritence functionCar(color,max_speed,max_acceleration) { this.color=color ... } Car.prototype.accelerate=function(){this.speed= Math.min(this.max_speed,this.speed+this.max_acceleration)} Car.prototype.decelerate=... functionAudi(color) { Car.call(color,200,10) } Audi.prototype=Object.create(Car.prototype) red_audi=newAudi('red') red_audi.accelerate() Forinheritance,allweneedisto callthesuperclassconstructor Audi=define_class(function(self,color) { __construct_car(self,color,200,10) }) Audi('blue') 27 28 Whataboutencapsulation? Whataboutpolymorphism? (Ab)usingenvironment Justoverwritefunctioninthechildclass functionCar(color,max_speed,max_acceleration) { this.getColor=function(){returncolor} ... } functionShape() { this.area=function(){throw'Error';} } functionSquare(width,height) { Shape.call(this) this.area=function(){returnwidth*height} } Square.prototype=Object.create(Shape.prototype) Andforprotected functionCar(color,max_speed, max_acceleration,protected={}) { protected.color=color ... } functionAudi(color) { varprotected={} Car.call(color,200,10,protected) this.getColor=function(){returnprotected.color} } Audi.prototype=Object.create(Car.prototype) 29 30 Object-OrientedAbstractSyntaxTree AnValueclass classValue: def__init__(self,value): self.value=value Revisitingthevisitorpattern AnOperatorclass classOperator: def__init__(self,a,b): self.a=a self.b=b Anadditionclass classAddition(Operator): def__init__(self,a,b): super().__init__(a,b) ... 32 Example Visitor defevaluate(node): ifnotisinstance(node,list): returnnode elifnode[0]=='+': returnevaluate(node[1][0]) +evaluate(node[1][1]) elifnode[0]=='-': returnevaluate(node[1][0]) -evaluate(node[1][1]) elifnode[0]=='*': returnevaluate(node[1][0]) *evaluate(node[1][1]) elifarray[0]=='/': returnevaluate(node[1][0]) /evaluate(node[1][1]) else: raiseError() ['+'[1 ['*'[4 ['/'[5 ['+'[23] ]]]]]]] Addition.new(1, Multiplication.new(4, Division.new(5, Addition.new(2,3)))) defevaluate(node): ifisinstance(node,Value): returnnode.value elifisinstance(node,Addition): returnevaluate(node.a) +evaluate(node.b) elifisinstance(node,Substraction): returnevaluate(node.a) -evaluate(node.b) elifisinstance(node,Multiplication): returnevaluate(node.a) *evaluate(node.b) elifisinstance(node,Division): returnevaluate(node.a) /evaluate(node.b) else: raiseError() 33 OrientedObjectvisitor(1/2) classVisitor: defvisitValue(self,node): returnnode.value defvisitAddition(self,node): returnnode.a.accept(self)+node.b.accept(self) defvisitSubstraction(self,node): returnnode.a.accept(self)-node.b.accept(self) defvisitMultiplication(self,node): returnnode.a.accept(self)*node.b.accept(self) defvisitDivision(self,node): returnnode.a.accept(self)/node.b.accept(self) 35 34 OrientedObjectvisitor(2/2) classValue: ... defaccept(self,visitor): returnvisitor.visitValue(self) classAddition: ... defaccept(self,visitor): returnvisitor.visitAddition(self) 36 Whyusethevisitorpatternatall? Easywaytoextendclasses Foraninterpreter: Avisitorforevaluating Avisitortoconverttoadifferentprogramming language Avisitortogeneratebytecode ... Exceptions 37 SoftwareExceptions Controlflowandexceptions Exceptionsareeventsthataffect thecontrolflowofaprogram. Anexceptionallowstoreturnfrom afunctionorastatmentatany point,withanytypeandonany numberoflevels. Exceptionneedtobecaught. try: a() rescueException: print('rescued') 39 defa(): b() print('Nevercalled') defb(): throwException() 40 Whatareexceptionsusedfor? www.govote.at206533 start Exceptionforerrorhandling Mostcommonuseofexceptionis forerrorhandling Moreconvenientthanreturninga value(whichisnotpossibleina constructor) 41 Exceptionforexitingadoubleloop 42 Breakandreturnstatement Howtoimplementthe'break'and'return'statement? WhileStatement.new(...,[...BreakStatement.new]) Usingareturnvalue? try: foriinrange(0,10): forjinrange(0,40): ifi*j==300: throwException('doublebreak') except: pass classEvalVisitor: defvisitBreakStatement(self,node): returnfalse defvisitWhileStatement(self,node): while(node.condition.accept(self)): ifnotvisitChildren(node): break; returntrue defvisitChildren(self,node): for(childinnode.children): if(notchild.accept(self) returnfalse returntrue Verysimilartoerrorchecking 43 44 Usingexceptionforbreakandreturn Instead,letsuseexceptions: Andhowtoimplementexceptionintheinterpreter? Usingexceptions... classEvalVisitor: defvisitBreakStatement(self,node): throwBreakException() defvisitWhileStatement(self,node): try: while(node.condition.accept(self)): visitChildren(node) rescueBreakException: pass defvisitChildren(self,node): for(childinnode.children): child.accept(self) classEvalVisitor: defvisitThrowStatement(self,node): throwInterpretedException(node.exceptionType) defvisitTryCatchStatement(self,node): try: visitChildren(node.body) exceptInterpretedExceptionasie: ifie.type==node.exceptionType: visitChildren(node.catch) else: throwie 45 46 Whatisatypesystem? Typesystem Atypesystemdefineshowatype isassociatedtoavariable Variablesarestoredasbitsin memory Atypegivemeaningtoasetof bits Inaprogram,avalueis associatedtoatleastonetype 48 Type-Checking Static-typechecking Static-typechecking Allowforoptimization Typesarecheckedatcompilationfromstaticanalysis Usuallyvariableshaveasingletype Polymorphismallowsfordynamicity Supportfromdowncasting Noneedtocheckfortypesatruntime Programverification Dynamic-typechecking Canworkbetterthanunit-tests Typesarecheckedatruntime Thetypeofavariablecanchange if(almostalwaystrue){/*validcode*/} else{/*typeinvalidcode*/} Soft-typechecking Butdowncastingcannotbeverifiedwithstatic checking Notypeisspecifiedforvariables Typesareinferred Gradualtyping Allowbothtospecifyandnotspecifythetype Unchecked Example:machinecode 49 Static-typevsDynamic-type 50 Gradual-typechecking Trade-off Thenumberofactualerrorsfound throughstatictypingisdebatable Dynamictypingallowsforfaster developmentandfaster compilation defgreeting(name:str)->str: return'Hello'+name greeting(10) greeting('Cyrille') defgreeting(name:str)->str: return'Hello'+name greeting(10) greeting('Cyrille') 51 52 Implementingstatic-typing WithanASTvisitor! Insteadofreturningavalue,returnatype Implementingdynamic-typing classEvalVisitor: defdoArithmetic(self,op,node): a=node.a.accept(self) b=node.b.accept(self) if(a.type==b.type): returnop(a,b) elif(a.type.canConvert(b.type)): returnop(a.convert(b.type),b) elif(b.type.canConvert(a.type)): returnop(a,b.convert(a.type)) else: throwExecutionError('Invalidtypes') defvisitAddition(node): returnself.doArithmetic(operators.add,node) classStaticTypeCheckerVisitor: defvisitValue(self,node): returnnode.type defcheckArithmetic(self,typeA,typeB): if(typeA==typeB): returntypeA elif(typeA.canConvert(typeB)): returntypeB elif(typeB.canConvert(typeA)): returntypeA else: throwCompilationError('Invalidtypes') defvisitAddition(self,node): returnself.checkArithmetic(node.a.accept(self),node.b.accept(self) defvisitAssignment(self,node): typeVariable=environment.getVariable(node.variableName).type typeValue=node.value.accept(self) if(typeVariable!=typeValue and!typeValue.canConvert(typeVariable)): throwCompilationError('Invalidtypes') returntypeVariable 53 54 StrongvsWeaktyping Conclusion Alanguageissaidtobestrongly typedwhenitrequiresexplicitely casting Object-orientedconceptandhow toimplementthem Improvedpatternvisitor Exceptionsandhowtousethem inaninterpreter Theimplicationofatypesystems Example:ADA Alanguageissaidtobeweakly typedwhenitallowscertinsnonexplicitcasting Forinstance,fromintegerstofloatingpoints 55 56/56