Listoflectures IntroductionandFunctionalProgramming ImperativeProgrammingandDataStructures 3 Environment 4 Evaluation 5 ObjectOrientedProgrammingandtypesystem 6 Macrosand 7 VirtualMachinesandBytecode 8 GarbageCollectionandNativeCode 9 DistributedComputing 10 Logic 11 Guestlecture 12 Summary 1 TDDA69DataandProgramStructure ObjectOrientedProgramming andtypesystem CyrilleBerger 2 2/54 Lecturegoal Lecturecontent Object-orientedandtype ObjectOrientedProgramming conceptsandconscequenceforprogram interpretation Object-OrientedConcepts Implementation Revisitingthevisitorpattern Exceptions Type 3/54 4/54 ProgramOrganizingTechniques Non-structuredProgramming StructuredProgramming ObjectOrientedProgramming ModularProgramming Object-OrientedProgramming 6 Non-structuredProgramming ProceduralProgramming Themainprogramdirectlyoperates onglobadata Combineasequenceofstatementsinto aprocedurewithcallsandreturns Themainprogramcoordinatescallsto proceduresandhandsoverappropriatedataas Program mainprogram/data Program mainprogram/data Impracticalwhentheprogramgets sufficientlylarge Thesamestatementsequencemust becopiedifitisneededseveraltimes Procedure1 Procedure2 Procedure3 Tasksareacollectionofstates,structures andprocedures 7 8 ModularProgramming LimitationsofStructuredandModularProgramming Unrestrictedaccesstoglobal Proceduresofacommonfunctionalityaregrouped togetherintoseparatemodules. Themainprogramcoordinatescallstoproceduresin separatemodulesandhandsoverdataasparameters. Globaldata1 Program Procedure1 mainprogram/data Module1data+data1 Procedure1 Procedure2 Globaldata2 Procedure2 Procedure3 Globaldata3 Procedure4 Attributesandbehaviorsare seperated Not Module2data+data2 Procedure3 9 10 WhatisObject-OrientedProgramming? Object-OrientedConcepts Amodelingtechnique Itisanaturaltechnique Theworldismadeofobjects:house,tree,car, computer... Allowtodescribeaprogram beforeitiswritten 12 WhatisanObject? Object-OrientedConcepts Class Inheritance Encapsulation Polymorphism Real-worldobjectsarecomposed ofattributesandbehaviors Attributes:color,size,... Behaviors:accelerate,brake,... Program Attributesarestates/variables Behaviorsarefunctions 13 14 Class ClassCar classCar: Anobjectisaspecificinstance(iethiscar, thiscomputer...) Aclassisatypeofobject(ieacar,a computer...) attributes: colorcanbered,green,blue... speedfrom0tomax_speed max_speedandmax_accelerationareconstant functions: Itisablueprintofobject Theclassdefines: accelerateincreasespeedwithmax_acceleration brakedecreasespeedwithmax_acceleration Thedefaultsetofvariables Thedefaultsetoffunctions Aninitialisationfunction(calledconstructor object: red_audi:={color:'red',max_speed:200, max_acceleration:10} blue_volvo:={color:'blue',max_speed:180, max_acceleration:7} Theobjectisaninstanceofaclass Itpointstoaspecificmemorylocationwiththeactualvalues forvariables 15 16 Inheritance InheritancefromtheclassCar classCar:color,speed, max_speedandmax_acceleration classAudi:classCarwith max_speed:=200and max_acceleration:=10 classVolvo:classCarwith max_speed:=180and max_acceleration:=7 Someclasseshavecommonpart Audiisacar,Volvoisacar,butVolvoandAudi aretwodifferenttypeofcars Inheritanceallowstodefineaclass intermofanothersuper-class Sub-classes canaddnewvariablesandfunctions overridevariablesandfunctionsfromthe super-class 17 Encapsulation 18 Polymorphism polymorphismistheabilitytoappear inmanyforms Itistheabilitytocallafunctiononan objectthatwillexecutedifferentcode fordifferentobjects Forexample,ashapeclasswithan areafunctionandtriangle,square... Itisonewayofcreatinggenericcode Encapsulationistheabilityto hidevariables Threecommonlevelsof Private:onlyaccessibletotheobject Protected:onlyaccessibletotheobjectandthrough inheritance Public:accessibletotheworld 19 20 TheadvantagesofObject-OrientedProgramming Codereusability Codecansharedinthesuperclass Polymorphismallowtodefineinterfaces Inheritenceclarifiesthe relationshipamongprogram elements Encapsulationallowmodularity andcontrolonaccessto variables Implementation 21 ImplementingObject-OrientedProgramming (Almost)anyimperative programminglanguagecanbe madetosupportobject-oriented programming Definingmembers:variables Allyouneedisa InJavaScript/ obj={value:1.0,name:'someobject'} console.log(obj.value) console.log(obj['value']) Forinstance,firstC++compilerwascompiling toCandmanyobjectsystemshavebeen addedtoC 23 In classTest def__init__(self): self.value=1.0 self.name='someobject' obj=Test() print(obj.value) console.log(obj.__dict__['value']) 24 Definingmembers:functions Allmostallyouneedistosave Whataboutclasses? Withdictionnarywehaveobjects Foraclass,allweneedisaconstructor obj={value:1.0,dosomething:function(){return42;} Buthowtoaccessthevariables Youeitherneedtopassapointerto theobject functioncreate_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)} 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 Forinheritance,allweneedistocallthesuperclass constructor functioncreate_audi(self,color): create_audi(self,color,200,10) 25 26 Whataboutencapsulation? ClassinJavaScript/ECMAScript functionCar(color,max_speed,max_acceleration) { this.color=color ... } Car.prototype.accelerate=function(){self.speed= Math.min(self.max_speed,self.speed+self.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() (Ab)usingenvironment functionCar(color,max_speed,max_acceleration) { this.getColor=function(){returncolor} ... } 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) 27 28 Whataboutpolymorphism? Justoverwritefunctioninthechildclass functionShape() { this.area=function(){throw'Error';} } functionSquare(width,height) { Shape.call(this) this.area=function(){returnwidth*height} } Square.prototype=Object.create(Shape.prototype) Revisitingthevisitorpattern 29 Example Object-OrientedAbstractSyntaxTree ['+'[1 ['*'[4 ['/'[5 ['+'[23] ]]]]]]] Addition.new(1, Multiplication.new(4, Division.new(5, Addition.new(2,3)))) AnValueclass classValue: def__init__(self, value): self.value=value AnOperatorclass classOperator: def__init__(self,a, b): self.a=a self.b=b Anadditionclass class Addition(Operator): def__init__(self,a,b): ...super().__init__(a,b) 31 32 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() 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): 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(2/2) 34 Whyusethevisitorpatternatall? classValue: ... defaccept(self,visitor): return visitor.visitValue(self) classAddition: ... defaccept(self,visitor): returnvisitor.visitAddition(self) Easywaytoextend Foraninterpreted: Avisitorforevaluating Avisitortoconverttoadifferentprogramming language Avisitortogeneratebytecode ... 35 36 SoftwareExceptions Exceptionsareeventsthataffect thecontrolflowofaprogram. Anexceptionallowstoreturnfrom afunctionorastatmentatany point,withanytypeandonany numberoflevels. Exceptionneedtobecaught. Exceptions 38 Whatareexceptionsusedfor? Controlflowandexceptions www.govote.at217195 try: a() rescueException: print('rescued') defa(): b() print('Nevercalled') defb(): throwException() 39 40 Exceptionforerrorhandling Exceptionforexitingadoubleloop Mostcommonuseofexceptionis forerrorhandling Moreconvenientthanreturninga value(whichisnotpossibleina constructor) try: foriinrange(0,10): forjinrange(0,40): ifi*j==300: throwException('doublebreak') except: pass 41 Breakandreturnstatement 42 Usingexceptionforbreakandreturn Instead,letsuse Howtoimplementthe'break'and'return'statement? WhileStatement.new(...,[...BreakStatement.new]) Usingareturnvalue? 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: 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 Andhowtoimplementexceptionintheinterpreter? Usingexceptions... classEvalVisitor: defvisitThrowStatement(self,node): throwInterpretedException(node.exceptionType) defvisitTryCatchStatement(self,node): try: visitChildren(node.body) exceptInterpretedExceptionasie: ifie.type==node.exceptionType: visitChildren(node.catch) else: throwie Typesystem 45 Type-Checking Whatisatypesystem? Atypesystemdefineshowatype isassociatedtoavariable Variablesarestoredasbits inmemory Atypegivemeaningtoaset ofbits Inaprogram,avalueis associatedtoatleastone type Static-typechecking Typesarecheckedatcompilationfromstatic analysis Usuallyvariableshaveasingletype Polymorphismallowsfordynamicity Supportfromdowncasting Dynamic-typechecking Typesarecheckedatruntime Thetypeofavariablecanchange Unchecked Example:machinecode 47 48 Static-typechecking Static-typevsDynamic-type Allowforoptimization Trade-off Thenumberofactualerrorsfound throughstatictypingisdebatable Dynamictypingallowsfor fasterdevelopmentandfaster compilation Noneedtocheckfortypesatruntime Programverification Canworkbetterthanunit-tests if(almostalwaystrue){/*validcode*/} else{/*typeinvalidcode*/} Butdowncastingcannotbeverifiedwithstatic checking 49 Implementingstatic-typing 50 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) WithanASTvisitor! Insteadofreturningavalue,returnatype 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 51 52 StrongvsWeaktyping Conclusion Alanguageissaidtobestrongly typedwhenitrequiresexplicitely casting Object-orientedconceptandhow toimplementthem Improvedpatternvisitor Exceptionsandhowtouse theminaninterpreter Theimplicationofatype Example:ADA Alanguageissaidtobeweakly typedwhenitallowscertinsnonexplicitcasting Forinstance,fromintegerstofloatingpoints 53 54/54