Lecture - Imperative Programming TT23, II
- Loose coupling/High cohesion
- Loose coupling: Different classes should not depend closely on the details of eachother
- Principle of least knowledge: assume as little as you can about other objects
- High cohesion: …
- Big idea: Polymorphism
- Some constructs in programming languages should be able to process different objects with different types
- Ad hoc polymorphism/overloading: define the same method for different types many different times
- Parametric polymorphism/generics: code can be written generically so it can handle them generically without depending on their type
- In OOP, having multiple components implement the same interface means that code can use different classes without worrying about each specific one
- Useful for debugging, since you can mock components of a system
- Inheritance
- Overriding methods in Scala works by putting
override
before thedef
- Then you use
super.<orig-method>
inside the method body to access the original -
val a : <class> : new <subclass>
. In this case,<class>
is called the “static type” and<subclass>
is called the “dynamic type”. - Can be dangerous when a subclass relies on the implementation details of a method in a the superclass (e.g. to call a method that they have overriden, to handle extra state). This is called the “fragile base class” problem.
- Overriding methods in Scala works by putting
Flashcards (GPT-4)
What does loose coupling and high cohesion mean in software design?
Loose coupling: minimal dependencies between classes; high cohesion: related code in single units.
What is polymorphism in programming?
Polymorphism allows processing different objects with different types through a single interface.
Name three types of polymorphism.
Ad hoc (overloading), parametric (generics), and subtype (OOP, same interface).
How do you override a method in Scala and access the original method?
Use override
before def
, access original with super.<orig-method>
.
In val a: <class> = new <subclass>
, what are static and dynamic types?
val a: <class> = new <subclass>
, what are static and dynamic types?<class>
: static type (compile-time); <subclass>
: dynamic type (runtime).
What is the fragile base class problem?
Subclasses relying on superclass implementation details, risking issues if superclass changes.