Composition

Written around 2023-12-18

Work in progress.

Inheritance

Most object-oriented languages have a concept of inheritance. Inheritance happens from parent objects onto multiple child objects. Through inheritance, child objects can extend the functionality of a parent object. They can also override functionality in the parent object.

However, it is necessary to be aware of the introduction of “coupling” when using inheritance. Inheritance may introduce complexity. See the chapter on inheritance in Clean Code.

Composition

The alternative to inheritance is composition. Composition is all about splitting your program in smaller parts and re-assembling them gradually. Composition allows for easier re-use.

Structs

The way composition works in Rust, is using a combination of structs (declared with keyword struct) and implementations (declared with keyword impl). Structs bundle smaller objects into a kind of product types. A single product type has a number of named fields, each with their own type. A struct is a bit like a data class in Python or a named list in R. The addition of implementations in impl blocks, makes them more like classes in Java, Python, C++ or JavaScript. In Rust, however, there is a syntactic separation between the fields of the class and the implementations.

Traits

When the function signatures of functions declared inside impl blocks become repetitive, it might be necessary to start using traits. Traits stick a name of groups of functions that are commonly implemented inside impl blocks.

In general a trait specifies constraints between (one or more) types.