Object Oriented Design Practices

Priyanka Saxena
2 min readOct 31, 2020

Part 2

  • Polymorphism
  • Object Composition
  • What to test?

Polymorphism

In OOP paradigm, polymorphism is the ability of multiple objects to respond to the same message i.e. the message can take multiple forms. It can be implemented in multiple forms-

  • Duck Typing: In dynamically typed languages, duck typing suggests that for a method to be called on an object, the object type (class) is immaterial as long as the method is defined for that object. Think of these as across class interfaces.
  • Inheritance: Think of this as delegation where sub-classes delegate messages that it doesn’t understand to it’s super-class. Super-class contains abstract (general) behaviour which is less likely to change, any added functionality which is prone to changes is defined in the sub-class. One way to decouple sub-class and parent-class is to implement hook methods for initialisation in the super-class.

Object Composition

Has-a relationships between objects are modelled by combining objects via composition. Unlike inheritance, where there exists automated delegation of messages, in composition this interaction must be explicitly defined. Inheritance is used when most of the code of superclass is to be reused, an is-a relationship. Duck types model a behaves-like-a relationship.

The aim is to identify the correct relationship between objects considering design implications.

What to test?

For any object, the public method’s it defines correspond to incoming messages that it’ll receive. This public interface is tested using assertions to verify the functionality. Use mocks/stubs for depending classes.

Private methods in ideal scenarios should not be tested.

Outgoing messages to other classes fall into two categories: queries or commands. Queries are messages which have no side effects outside of its method, and are not tested. While commands require tests based on behaviour, and not on state.

Duck types should’ve role based tests. Subclass is tested separately to behave like a superclass, and for its incoming messages.

Source: Agile Ruby Design

--

--