RustBrock/Characteristics of OO Languages.md
darkicewolf50 dbdd3d8d07
Some checks failed
Test Gitea Actions / first (push) Successful in 23s
Test Gitea Actions / check-code (push) Failing after 18s
Test Gitea Actions / test (push) Has been skipped
Test Gitea Actions / documentation-check (push) Has been skipped
started ch18.1
2025-04-01 16:47:10 -06:00

2.6 KiB

Characteristics of Object-Oriented Languages

There is no consensus about what features a language must have to be considered object-oriented.

Rust is influenced by many programming paradigms, including OOP.

Arguably, OOP languages share certain common characteristics, namely objects, encapsulations and ingeritance.

Lets see what each of those means and whether Rust supports it.

Object Contain Data and Behavior

The book Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (Addison-Wesley Professional, 1994).

This is colloquially referred to as The Gang of Four book, is a catalog of object-oriented design patters.

It defines OOP as this: Object-oriented programs are made up of objects. An object packages both data and the procedures that operate on that data. The procedures are typically called methods or operations. Using this definition, Rust is object-oriented: structs and enumbs have data, and impl blocks provide methods on structs and enums.

Even though structs and enums with methods aren't called obejcts, they provide the same functionaliy accound to the Gang of Four's definition of objects.

Encapsulation that Hides Implementation Details

An aspect commonly associated with OOP is the idea of encapsulation.

This means that the implementation details of an object aren't accessible to code using that object.

Therefore, the only way to interact with an object is through its public API.

Code using the object shouldn't be able to reach into the object's internals and change data or behaviro directly.

This enables the programmer to change and refactor an object's internals without needing to change the code that uses the object.

We discussed previously how to control encapsulation in Ch7.

We can use the pub keyword to decide which modules, types, function and methods in our code should be public .

By default everything else is private.

For example, if we defined a struct AveragedCollection that has a field containing a vector of i32 values.

The struct can also have a field that contains the average of te vlaues in the vector, meaning the average doesn't have to be computed on demand whenever anyone needs it.

In other words, AveragedCollection will cache the calculated average of the values in the vector.

Meaning the average doesn't have to be computed on demand whenever it is needed.

AveragedCollection will cache the calculated average for us.

Here is the definition of the AveragedCollection struct

pub struct AveragedCollection {
    list: Vec<i32>,
    average: f64,
}