Skip to content
ImagineWorld

Anti-Pattern: Designing for Object Orientation

node_idnode-book_design-patterns-and-best-practices-in-rust_chapter-02-anti-pattern-designing-for-object-orientation
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num2
chapter_titleAnti-Pattern: Designing for Object Orientation
pillar_membershipJ — architecture_design_craft
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 2 — Anti-Pattern: Designing for Object Orientation

Section titled “Chapter 2 — Anti-Pattern: Designing for Object Orientation”

Anti-Pattern: Designing for Object Orientation

Section titled “Anti-Pattern: Designing for Object Orientation”

In this chapter, we will be discussing an anti-pattern: trying to design for object orientation in Rust. Anti-patterns are coding solutions that people commonly use in their code but that turn out to be unhelpful or even counterproductive. These problematic approaches may seem beneficial at first but ultimately lead to code that is difficult to maintain, inefficient, or prone to errors. What is unique here is that we will be discussing how a solid design pattern in one context can be an anti-pattern in a different one.

We will deal with common issues caused by treating Rust as if it were an object-oriented (OO) language such as Rust or C++ and explore common errors from this kind of thinking. We will learn why OO design patterns cause issues when used in Rust and don’t really work as they should. We will also look at situations where some OO techniques are helpful or even necessary.

First, we will dig into why Rust may appear to be similar to familiar OO languages, but that similarity is deceptive. We were introduced to this in the previous chapter, but now we will look at it in detail, to understand crucial differences.

Next, we will dive into our first trick to try to work with Rust like an OO language: misusing traits. We will see that while traits resemble abstract classes or Rust interfaces, they function quite differently in many ways, in the context of the language.

The next trick we will cover is trying to use the Deref trait to try to simulate inheritance. We’ll see that this is not a successful strategy and that it can have bad consequences.

We’ll also discuss the use, or more correctly misuse, of generics to simulate more traditional class patterns. While this is possible, and can sometimes work, usually this is a recipe for disaster, which starts out looking promising but ends up being unworkable.

Finally, we will discuss the use of enums for an OO-like design. We’ll see that they are actually an excellent tool for that purpose, in some situations, but that overusing that technique is not a solution either.

We will also continue our calculator project that we began working on in the previous chapter. We’ll start building an OO-centric design, and see how it seems to be working at first, but it becomes increasingly messy. We’ll also see how, if we fight with the language, we get unnatural, unreliable code.

In this chapter, we’re going to cover the following main topics:

  • Why is Rust not an OO language?
  • Misusing traits
  • Using Deref to simulate inheritance
  • Using generic types to act like classes
  • Using enums where they don’t make sense

The source code for the exercises can be found on GitHub at https://github.com/PacktPublishing/Design-Patterns-and-Best-Practices-in-Rust. The repository is organized by chapter. The relevant exercises for this chapter can be found at https://github.com/PacktPublishing/Design-Patterns-and-Best-Practices-in-Rust/tree/main/ch2/.

In the previous chapter, we introduced the topic of Rust appearing to be an OO language but being subtly, but very significantly, different. In this section, we will explore this in much more detail.

What makes Rust so different that many OO techniques will not work? Why, if it is so different, does it look so much like an OO language? What can we learn from these differences that we can apply to working in Rust?

As we saw earlier, Rust can initially appear to support OO programming. This impression isn’t accidental. Rust has many features that bear a surface-level resemblance to OO constructs from familiar languages. When experienced developers first encounter Rust code, these similarities create a natural inclination to apply familiar OO patterns.

Traits, for instance, look remarkably like Rust interfaces or C++ abstract classes. They define method signatures that types must implement. Structs can have methods attached via impl blocks, making them appear like classes with encapsulated behavior. The Drop trait provides cleanup functionality that seems equivalent to destructors in C++ or finalizers in garbage-collected languages. Rust’s syntax uses familiar words such as struct and self that reinforce these apparent parallels.

These surface similarities create a compelling illusion: if Rust has structs, methods, and cleanup mechanisms, why not use inheritance patterns, polymorphism hierarchies, and other OO design approaches? Looking at a screen full of Rust code, it would be natural to see object orientation throughout.

However, this is deceptive. If we try to use these features and constructs in the same way that we are accustomed to using them in a language such as Python or C#, things will seem to work, even if it is a bit awkward in places, but later our choices will make things very difficult for us. But why will these choices make things difficult, and what should we do about that? Let’s look at that.

When I first began working with Rust, one of the first things I thought was, “Why are they calling classes structs?” It seemed clear that these “structs” had methods and fields and constructors and encapsulation and many, or even all, of the things that you would expect from a class. The syntax was a bit different, and there did not appear to be any inheritance, but the differences did not seem significant. It felt like there were “classes” in the language, but, for some reason, they had been called “structs.”

C was one of the first languages I learned, but Rust structs did not seem much like the simple structs in C that just collect fields together. They were more like C++ structs, which are almost identical to C++ classes. So, the decision to use the word struct in Rust seemed aesthetic and arbitrary.

I understood why the word struct was chosen only after working with Rust for a while: Rust structs are not classes, and the word struct is much more accurate for describing Rust data structures.

One of the biggest differences is inheritance. While it has become less popular recently as a technique, it is the core of polymorphism in OO languages. It is common to structure entire systems around class hierarchies. Much of the architecture of the system then proceeds from that class hierarchy. Thinking in terms of class-based polymorphism is very natural in many popular languages, and the design of the languages themselves supports this.

However, Rust doesn’t support this model, but more significantly, it doesn’t support this way of thinking. While it is possible, as we discuss later in this chapter, to use traits for polymorphism, and while traits do permit some things that look like inheritance, if you begin down the road of treating these features as if they are inheritance, you will often find yourself either entirely blocked by Rust’s lack of true inheritance or on a path to more and more unwieldy designs that are painful to maintain or even understand.

Class hierarchies are hierarchical. They define data and behaviors at the root of the hierarchy, and then add to them or refine them at each level of the hierarchy. Rust structs don’t work that way. You can’t extend or modify their definition by creating children of the struct. A Rust struct is what it is.

Traits appear to have a kind of inheritance, but they are much more accurately thought of as contracts. A struct that implements a trait follows that contract, and traits that appear to inherit from a different trait are more correctly understood to be adding the terms of that trait’s contract to their own.

We run into barriers, or create messy designs, when we try to treat structs as classes by designing for inheritance, because we can’t form real hierarchies. We can draw a diagram and begin to code thinking in a hierarchical way, but to realize these designs, we need to laboriously work around the fact that Rust doesn’t work that way. This may seem extremely clear, but it is extremely easy to think hierarchically without even realizing it.

We will see examples of this throughout the book, beginning in this chapter.

Polymorphism is built into the essence of classes in most modern OO languages. There is an inherent expectation that child classes are interchangeable with their parents and siblings. The language infrastructure is designed to make this effortless and transparent.

In Rust, things are different. After working in Rust for a while, you will become very aware that Rust types have sizes, because the compiler will remind you of this fact often. Different types are different things, as far as the compiler is concerned, and if the compiler can’t determine what specific type it is dealing with, it will want to have a word with you. To be able to use two structs interchangeably, you must take extra specific and explicit steps (which we will discuss) to make that happen, and we need to follow specific rules and stay within explicit boundaries.

In Rust, it is not possible to substitute types transparently. In some specific circumstances, it is possible to, for example, declare a function parameter to be of type impl Traitname, and then call the function with a struct that implements that trait, but that is really syntactic sugar for a generic type – the actual type is still known at compile time. To work with a truly polymorphic value, to store a trait in a struct, or call a function with a type unknown at compile time, we must be explicit and use Box<dyn Traitname>. Using a boxed trait like this is sometimes exactly what we need. But Rust requires us to affirmatively choose: we must choose to pay the cost of storing on the heap, of doing dynamic dispatch at runtime, and of managing the dynamic reference.

Even though we understand Rust’s rules, that can feel cumbersome and arbitrary. Can’t Rust help us out with something so simple and common?

As with class hierarchies, this is not just a difference in implementation; it requires a difference in thinking. It is very possible, and sometimes an excellent decision, to leverage Rust’s unique way of expressing polymorphism. But it is not a natural and central feature of the language. Therefore, we have a clue that it should not be a reflexive and unexamined aspect of our designs.

While working with languages such as Python or C++, relying on polymorphism can become automatic. That is why it is so jarring when the Rust compiler complains, and so annoying when we must seemingly bend over backward to get our code to compile and work. For Rust, patterns like this, so fundamental that we don’t even think of them as patterns, need to be used carefully and sparingly. In the next section, we will see why. In Chapters 9–12, we will discuss patterns that are more aligned with the language.

Note: A word about C++ C++ is interesting to mention here. Modern C++ coding style has changed considerably over many years, but thinking about how the language was used in the past and how it was originally designed can be enlightening. Like Rust, C++ provides choices about polymorphism. Classes can be declared virtual or not, meaning that they can provide runtime polymorphism, or not. We can assign a reference to an object to a variable typed as a reference to a parent class, or overwrite a parent-typed object with a child type. What is different is that, while we can make these choices, in C++ the compiler does not do much to enforce them. Worse, because there is no unusual syntax to call attention to (and be explicit about) what we are doing, we can make a bad choice and not notice. People will say, “You get used to it”; I used to say that myself. But after working with Rust, I have come to appreciate its clear, explicit syntax and compiler enforcement, which have helped me avoid many late evenings hunting for bugs.

The borrow checker prevents object patterns

Section titled “The borrow checker prevents object patterns”

One aspect of OO design is so fundamental, it isn’t really even considered to be an OO paradigm at all. When we design systems using OO patterns, we don’t even realize it is there while we are using it – that is, the free movement of objects.

We can create class hierarchies and designs to leverage polymorphism to make our objects have proper behavior wherever they are used. But this only becomes truly useful when we can use our objects everywhere. If we create an object instance of a known type and then call a method on it a few lines later, that works, and it may look clean and work properly, but we’re not fully using the expressiveness and flexibility of OO patterns. Where it really helps us is when an object from somewhere else can be doing things that, in this section of the code, we don’t even have to know about.

One of the reasons that OO design has been so successful is that it allows us to create systems of very high complexity with many, many pieces that are understandable and maintainable. But to do that, typically, objects travel around the system freely. We don’t really think about that, but it is crucial to the way we think about designing with objects.

In Rust, as we know, we certainly can move data in the form of things such as structs and enums around the system. But, as we also know, that movement is not exactly free. A very significant topic of this book, which we will cover in detail, is understanding and thinking about the flow of data and its central role in designing for Rust. Understanding how your data flows is crucial for any system design, but Rust has a distinct twist: Rust as a language has specific rules about how, where, and when data can be shared (which can influence how data flows through your code). The borrow checker enforces this, and we need to follow its rules. Because of this, it is vital to think carefully about the design of that flow.

The reason “object-oriented” design is called that is because the design of the objects in the system takes center stage in the design of the system itself. OO design teaches the habit of starting from the basis of sound design of the objects in the system. The data flow follows from that design, and is in service to it. This can work, and data flow can be less of a concern, because we can count on the languages that we use to allow data to flow (mostly) freely.

This is a crucial element to the way that most modern OO design works. However, this becomes a recipe for disaster when designing in Rust, because the borrow checker makes us think much more carefully about the movement and sharing of data.

Pulling it together: types are not objects

Section titled “Pulling it together: types are not objects”

Thinking about collections of data in terms of the abstraction of objects is the most fundamental element of what we think of as OO design. It is the one element that unites all of the disparate languages, frameworks, models, and patterns that make up object orientation: they all deal in objects.

The object is an amazingly useful abstraction. I will not recount its history, but it took the world by storm (maybe a slow storm at first), for excellent reasons. Being able to model a collection of data and code in this way has been extraordinarily useful.

At first glance, Rust seems to be following OO practice. We may not call structs or enums objects, but they are collections of data, and their impl blocks allow us to group specific code with specific data structures. They allow (and enforce) encapsulation. Their model of construction and destruction is a bit unorthodox, but it also fits in this framework. Clearly, this one aspect of Rust does follow the OO model, right?

Yes, it does, but it also doesn’t.

What is at issue is that objects, in an OO sense, come with a set of expectations. It is true that, by the preceding definition, we can call a struct or an enum in Rust an object, but they are objects only in this loose sense. We have to be very careful not to allow all of the things that we have learned to associate with “objects,” or even “instances,” with these Rust data structures.

Rust works with types that represent data in memory. These types share some superficial (and some very intentional) characteristics with objects as we know them from OO languages. But it is tempting to mistake that resemblance for a deeper reality. Rust is not OO. It will be very helpful to orient yourself away from objects.

In this section, we discussed the reasons that Rust really isn’t an OO programming language. We discussed the ways in which Rust structs, while similar in some ways to classes, are not really like classes. We also discussed Rust traits, and how they don’t really model inheritance. We examined polymorphism in Rust and why it is so different from what we see in OO languages. Finally, we talked about the flow of data and how OO languages really depend on its free movement.

In the next section, we will talk in more depth about traits and polymorphism, and how trying to misuse them to implement familiar patterns can lead to a messy solution.

In this section, we will discuss Rust traits and how they can be prone to being misused when designing in Rust. Traits exist to provide contracts that structs can fulfil, which adds expressiveness and flexibility to the language. However, we will see why they are not a substitute for interfaces or abstract classes in the OO sense.

As we discussed in the previous section, Rust traits, while similar to interfaces or pure abstract classes, do not actually provide or represent the same kind of type hierarchy as classes, and polymorphism using traits is more circumscribed and less convenient and natural in Rust. It is tempting to reach for traits as a way to model inheritance, or to try to use them to design systems that center dynamic polymorphism, but they are not usually the optimal way to design in Rust, or to create solutions to challenges we will encounter.

In the previous chapter, we began creating the Bad Calculator project. Let’s examine how we can try to use traits to represent an inheritance model, and how that works or doesn’t work.

We can begin thinking about how to model the key components of our calculator. We’re leaning into OO, so we’ll think about this in terms of objects.

Calculators take operands, such as numbers and expressions, and perform operations, such as addition and subtraction, on them. Let’s just think about operators for a moment. They can be unary operators, such as negation or square root, or they can be binary operators, such as addition and subtraction. Operators have precedence, so multiplication happens before addition. We should probably keep the operands on a stack because we don’t know how many there are. Finally, operators should have some kind of “apply” action that performs the operation on the operands.

For now, we’ll ignore the Operand type. We only need to be able to get its value as a number.

Let’s try to model that:

Figure 2.1: Bad Calculator UML diagram 1

[figure outside: Figure 2.1]

Here, we’ve made a straightforward object hierarchy. We have an abstract Operator class that has two abstract subclasses, UnaryOperator and BinaryOperator, to cover the kinds of operations that our calculator implements. This is classic OO design, with a clear hierarchy of more and more specific classes until we arrive at our bottom layer of concrete classes that represent the actual operations themselves. Each layer defines methods specific to what that class represents. We also have an operand type that represents the values that our operators consume.

That seems to cover it. We don’t have abstract classes (or any classes), but we can use traits, and we can have getters for precedence and symbol.

Let’s try coding it. First, we will create the base traits:

trait Operand {
fn evaluate(&self) -> f64;
}
trait Operator {
fn precedence(&self) -> u8;
fn symbol(&self) -> char;
fn push_operand(&mut self, operand: Box<dyn Operand>);
fn pop_operand(&mut self) -> Box<dyn Operand>;
fn apply(&mut self) -> Box<dyn Operand>;
}

That’s not bad. There are already a lot of Box<dyn> types showing up, and we are just beginning, which is a bit concerning, but let’s continue.

Next, we will code the sub-traits. We’ll be clever here. We can make an apply method in each of these traits that does the work of popping the operands, so all we need to do in the implementations is provide the operation-specific apply logic for the operation:

trait UnaryOperator : crate::Operator {
fn apply_unary(&self, operand: Box<dyn Operand>) -> Box<dyn Operand>;
fn apply(&mut self) -> Box<dyn Operand> {
let operand = self.pop_operand();
self.apply_unary(operand)
}
}
trait BinaryOperator: Operator {
fn apply_binary(&self, operand1: Box<dyn Operand>, operand2: Box<dyn Operand>) -> Box<dyn Operand>;
fn apply(&mut self) -> Box<dyn Operand> {
let operand2 = self.pop_operand();
let operand1 = self.pop_operand();
self.apply_binary(operand1, operand2)
}
}

Lots of Box<dyn>, but it’s working.

Now all we have to do is write the concrete structs that implement our traits. So, maybe we can do this?

struct AdditionOperator {
stack: Vec<Box<dyn Operand>>
}
impl BinaryOperator for AdditionOperator {
fn precedence(&self) -> u8 {
0
}
fn symbol(&self) -> char {
'+'
}
fn push_operand(&mut self, operand: Box<dyn Operand>) {
self.stack.push(operand);
}
fn pop_operand(&mut self) -> Box<dyn Operand> {
self.stack.pop().unwrap()
}
fn apply_binary(&self, operand1: Box<dyn Operand>, operand2: Box<dyn Operand>) -> Box<dyn Operand> {
todo!()
}
}

It seems not:

error[E0407]: method `precedence` is not a member of trait `BinaryOperator`
--> src/main.rs:42:5
|
42 | / fn precedence(&self) -> u8 {
43 | | 0
44 | | }
| |____^ not a member of trait `BinaryOperator`
[Deleting similar errors for each method from "Operator"]

Oh! There actually isn’t any such thing as a sub-trait. Operator is just a trait bound of BinaryOperator. You have to define the operator methods in an impl block for Operator. OK, so we can’t do this that way. That’s OK. We’ll implement Operator also:

impl BinaryOperator for AdditionOperator {
fn apply_binary(&self, operand1: Box<dyn Operand>, operand2: Box<dyn Operand>) -> Box<dyn Operand> {
todo!()
}
}
impl Operator for AdditionOperator {
fn precedence(&self) -> u8 {
0
}
fn symbol(&self) -> char {
'+'
}
fn push_operand(&mut self, operand: Box<dyn Operand>) {
self.stack.push(operand);
}
fn pop_operand(&mut self) -> Box<dyn Operand> {
self.stack.pop().unwrap()
}
}

Will that work?

error[E0046]: not all trait items implemented, missing: `apply`
--> src/main.rs:47:1
|
13 | fn apply(&mut self) -> Box<dyn Operand>;
| ---------------------------------------- `apply` from trait
...
47 | impl Operator for AdditionOperator {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `apply` in implementation

That compiles.

Now we can actually implement addition in AdditionOperator. We’ll need a concrete Operand type to work with, so we’ll create one:

struct Value(f64);
impl Operand for Value {
fn evaluate(&self) -> f64 {
self.0
}
}

Now we can make addition work:

impl BinaryOperator for AdditionOperator {
fn apply_binary(&self, operand1: Box<dyn Operand>, operand2: Box<dyn Operand>) -> Box<dyn Operand> {
let inner_operand1 = operand1.evaluate();
let inner_operand2 = operand2.evaluate();
let result = inner_operand1 + inner_operand2;
Box::new(Value(result))
}
}

That compiles. It’s also messy and confusing. We also have to do this for every operator. We have one operation, and it’s already several screens full of confusing code.

We’ve been trying to use OO principles to make something clear and simple where we don’t have to worry about the inner workings of things and don’t have to re-implement everything many times, but now we have the opposite.

Traits are not interfaces or abstract classes. Box<dyn> is not a neat, simple solution to emulate OO polymorphism. We can’t really treat Rust structs like classes.

But maybe there is a way to improve this.

Did you notice that in the apply_binary implementation, we could do this?

let inner_operand2 = operand2.evaluate();

operand2 is a box, which contains a reference to the inner operand, but we called evaluate on the box directly, not on the referenced value. For emphasis, we could rewrite that as this:

let inner_operand2 = operand2.as_ref().evaluate();

We were able to call the trait method directly on the boxed trait because Rust allows us to use automatic dereferencing. That will work for any type that implements the Deref trait, as the box does here.

The Deref trait helped us out here. Maybe it can help us more. In the next section, we’ll discuss trying to use the Deref trait to clean up our code.

Using Deref as a poor substitute for inheritance

Section titled “Using Deref as a poor substitute for inheritance”

We have seen, in the previous section, how traits are not a substitute for inheritance-based polymorphism. In this section, we will talk about a different strategy to recreate the effects of class-based inheritance: using the Deref trait.

One of the ergonomic features in Rust is automatic dereferencing. Because of the extremely explicit nature of types in Rust, and because of the many smart pointer types, Rust makes it simple to use reference types directly, in many circumstances, without having to manually dereference them.

Rust provides the Deref trait so that you can create your own custom pointer types. The goal is to allow you to use your new custom pointer as if it were the thing that the custom pointer is referencing. It makes the reference transparent, making the code clearer and easier to read.

But Deref doesn’t know or care what it is dereferencing, or even whether it is even dereferencing anything at all. It knows that it is called on self and that it returns something. What that something is doesn’t matter.

This leads us to our next trick. One thing that we could do to make the code cleaner and promote reuse is to reduce redundant code in our operators (and everywhere else). In OO designs, we put code like that in base classes. Rust doesn’t have those. What if there were some trick that we could use to do the same thing?

Deref is a possible answer to this.

One thing that is clear in looking at our Bad Calculator is that, currently, we are not adhering to don’t repeat yourself (DRY) principles. Currently, we have only one operator, but what happens when we implement subtraction, multiplication, and division?

We will be rewriting code unnecessarily each time. It would be helpful if we could find a way to reduce that.

To use one example, we will need to create the operand stack over and over in our new operators. Because this is an example, it may not seem like much, but in a real-world application, there could be much more code, over many individual implementations, that we not only need to write but also document for the next implementor.

We could create an OperandStack type to help us, and change AdditionOperator to use it:

struct OperandStack(Vec<Box<dyn Operand>>);
impl OperandStack {
fn new() -> Self {
Self(Vec::new())
}
fn push_operand(&mut self, operand: Box<dyn Operand>) {
self.0.push(operand);
}
fn pop_operand(&mut self) -> Box<dyn Operand> {
self.0.pop().unwrap()
}
}
struct AdditionOperator {
pub stack: OperandStack
}
impl AdditionOperator {
fn new() -> Self {
Self { stack: OperandStack::new() }
}
}

Now we can use it like this:

let mut addition_operator = AdditionOperator::new();
addition_operator.stack.push_operand(some_operand);
let popped_operand = addition_operator.stack.pop_operand();

That’s somewhat helpful, and it would be even more helpful if OperandStack were doing much more within its implementation, but what we would like is for push and pop to be included in the operator’s API directly.

If we implement the Deref and DerefMut traits on AdditionOperator, and we have each return a reference to the OperandStack struct, then we should be able to use automatic dereferencing to improve the situation. What if we did something like this?

impl Deref for AdditionOperator {
type Target = OperandStack;
fn deref(&self) -> &Self::Target {
&self.stack
}
}
impl DerefMut for AdditionOperator {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.stack
}
}

Now we can call OperandStack’s methods directly on AdditionOperator:

addition_operator.push_operand(some_operand);
let popped_operand = addition_operator.pop_operand();

That does seem like an improvement, but we now have to implement Deref and DerefMut on every operator, so we’re not following DRY.

We can try making the implementation generic over all operators. We will need to make a getter for stack, which will now be something that every operator has to implement and also becomes something that is included in the operator API. It would look like this:

trait Operator {
fn precedence(&self)-> u8;
fn symbol(&self)-> char;
fn push_operand(&mut self, operand: Box<dyn Operand>);
fn pop_operand(&mut self)-> Box<dyn Operand>;
fn apply(&mut self)-> Box<dyn Operand>;
fn stack(&self)-> &OperandStack;
fn stack_mut(&mut self)-> &mut OperandStack;
}
impl<T: Operator> Deref for T {
type Target = OperandStack;
fn deref(&self)-> &Self::Target {
self.stack()
}
}
impl<T: Operator> DerefMut for T {
fn deref_mut(&mut self)-> &mut Self::Target {
self.stack_mut()
}
}

Unfortunately, that doesn’t compile:

error[E0210]: type parameter `T` must be used as the type parameter for some local type (e.g., `MyStruct<T>`)
--> src/main.rs:110:6
|
110 | impl<T: Operator> Deref for T where T: Operator {
| ^ type parameter `T` must be used as the type parameter for some local type
|
= note: implementing a foreign trait is only possible if at least one of the types for which it is implemented is local
= note: only traits defined in the current crate can be implemented for a type parameter

This can be solved by creating a local wrapper type. But consider where we are now. We are making the code increasingly difficult to work with and increasingly difficult to understand in order to be able to use this trick.

Let’s step back.

When we were implementing Deref only for AdditionOperator, did that compile?

error[E0046]: not all trait items implemented, missing: `push_operand`, `pop_operand`
--> src/main.rs:63:5
|
20 | fn push_operand(&mut self, operand: Box<dyn Operand>);
| ------------------------------------------------------ `push_operand` from trait
21 | fn pop_operand(&mut self) -> Box<dyn Operand>;
| ------------------------------------------------------ `pop_operand` from trait
...
63 | impl Operator for AdditionOperator {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ missing `push_operand`, `pop_operand` in implementation

Our Operator trait doesn’t know about the Deref trick. We could delete push and pop from the trait, but then those operations would not be generic for all operators.

This all can be made to work, but we have been fighting with the compiler and the code for a while now, with the purpose of making the code clearer, easier to work with, and easier to understand.

What we have done is make the code more confusing, more difficult to read, more difficult to work with, and dependent on fragile tricks to work.

Let’s consider one more thing.

What if we add more methods to our OperandStack? Suppose we add a clear method. Now it looks something like this:

impl OperandStack {
fn new() -> Self {
Self(Vec::new())
}
fn push_operand(&mut self, operand: Box<dyn Operand>) {
self.0.push(operand);
}
fn pop_operand(&mut self) -> Box<dyn Operand> {
self.0.pop().unwrap()
}
fn clear(&mut self) {
self.0.clear();
}
}

We added a function to the API of the OperandStack, and, in context, the purpose of the new method is perfectly understandable.

But now, this compiles:

addition_operator.clear();

In this context, we don’t know what clear does, but we probably don’t want to do that to our AdditionOperator.

We are spending considerable time and effort to make our code worse.

Deref does an excellent job of making smart pointer types easy and ergonomic to use. Because it is so convenient, it is tempting to use it to try to add OO-style code reuse by making composition look like inheritance. But it is much less helpful than it seems, and it comes at a cost of creating behavior that future coders will be surprised by, and potentially exposing harmful interfaces. It is not a reliable way to get the code reuse we were seeking, and it is not a pattern that we should be using.

We will discuss productive ways to use traits in our design in Chapter 6, Structural Patterns: Connecting and Aggregating, and later in Chapter 10, Patterns That Leverage the Type System.

In the next section, we will try to use generic types as a stand-in for classes and see that it is not a simple fix for our design.

We’ve tried some ways to model class hierarchies and objects in Rust and found that they cause more issues than they solve and produce awkward code. However, Rust is a flexible language, with many features that allow many ways to accomplish things. Maybe we can find a different way to model our class hierarchies.

Generic types in Rust, when properly used, provide an extremely expressive and effective tool for designing and architecting systems and applications. They are at the core of many of the most useful patterns and techniques, and they make it possible to create robust and flexible code that is very compact and readable. Can they help us build something like a class hierarchy?

Let’s try this with our calculator. In a traditional OO approach, we might model operations with a class hierarchy:

Figure 2.2: Operation class hierarchy

[figure outside: Figure 2.2]

Here, we’ve made the operations implement a trait called OperationType, which has a calculate() method. Operation is now a struct with a type parameter that has a trait bound of OperationType.

Let’s code it! First, we can define some operations using structs and a trait that should work for any operation:

trait OperationType {
fn calculate(&self, left: f64, right: f64) -> f64;
fn precedence(&self) -> u8;
}
struct Add;
impl OperationType for Add {
fn calculate(&self, left: f64, right: f64) -> f64 {
left + right
}
fn precedence(&self) -> u8 {
1
}
}
struct Multiply;
impl OperationType for Multiply {
fn calculate(&self, left: f64, right: f64) -> f64 {
left * right
}
fn precedence(&self) -> u8 {
2
}
}

Now we can try using generics to emulate a base class:

struct Operation<T: OperationType> {
symbol: String,
op_type: T,
}
impl<T: OperationType> Operation<T> {
fn new(symbol: String, op_type: T) -> Self {
Operation { symbol, op_type }
}
fn evaluate(&self, left: f64, right: f64) -> f64 {
self.op_type.calculate(left, right)
}
fn get_precedence(&self) -> u8 {
self.op_type.precedence()
}
}

We’ll also make a main() function to try it out:

fn main() {
let add_op = Operation::new("+".to_string(), Add);
let mul_op = Operation::new("*".to_string(), Multiply);
println!("5 {} 3 = {}", add_op.symbol, add_op.evaluate(5.0, 3.0));
println!("5 {} 3 = {}", mul_op.symbol, mul_op.evaluate(5.0, 3.0));
}

That seems to work! It compiles and works as we would expect.

Are there issues with this? What if we want to parse an expression such as 2 + 3 * 4 and store all the operations in a vector to process them by precedence?

fn main() {
let add_op = Operation::new("+".to_string(), Add);
let mul_op = Operation::new("*".to_string(), Multiply);
println!("5 {} 3 = {}", add_op.symbol, add_op.evaluate(5.0, 3.0));
println!("5 {} 3 = {}", mul_op.symbol, mul_op.evaluate(5.0, 3.0));
// Attempt to create a vector of different operations
let operations: Vec<Operation> = vec![add_op, mul_op];
}

Does that work? Let’s see:

Terminal window
> cargo build
Compiling calculator v0.1.0
error[E0107]: missing generics for struct `Operation`
--> src/main.rs:43:25
|
43 | let operations: Vec<Operation> = vec![add_op, mul_op];
| ^^^^^^^^^ expected 1 generic argument
|
note: struct defined here, with 1 generic parameter: `T`
--> src/main.rs:20:8
|
20 | struct Operation<T: OperationType> {
| ^^^^^^^^^ -
help: add missing generic argument
|
43 | let operations: Vec<Operation<T>> = vec![add_op, mul_op];
| +++

Operation needs a type argument. That’s OK! We can use the wildcard, _, and the compiler will infer the type:

let operations: Vec<Operation<_>> = vec![add_op, mul_op];

Does that work?

Terminal window
> cargo build
Compiling calculator v0.1.0
error[E0308]: mismatched types
--> src/main.rs:43:51
|
43 | let operations: Vec<Operation<_>> = vec![add_op, mul_op];
| ^^^^^^ expected `Operation<Add>`, found `Operation<Multiply>`
|
= note: expected struct `Operation<Add>`
found struct `Operation<Multiply>`

What happened here?

For the Rust compiler, Operation isn’t really a concrete type; it’s just a type in combination with its type argument. Operation<Add> and Operation<Multiply> are concrete Rust types, but there’s no real type that is a “generic” Operation. When the compiler saw Operation<_>, it did what we were expecting and inferred the type, but what it inferred was that the type on the left was Vec<Operation<Add>>, because that’s the first Operation it saw. When it then saw Operation<Multiply>, it couldn’t compile the code, because it can’t be stored in Vec<Operation<Add>>.

Unlike OO languages, Rust doesn’t have runtime type information for generics. This means you cannot have a collection of different Operation<T> types, which is exactly what we’d need for our calculator to handle mixed operations.

Generics can do many things, but misusing them to emulate an OO style doesn’t work.

In Chapter 10, Patterns That Leverage the Type System, we will cover the amazing TypeState pattern, which is an excellent way to use generics and harmonizes with Rust.

In the next section, we will be discussing the use of enums to create sound designs, and the overuse of enums to create bad ones.

In this section, we will discuss the use of enums to represent designs with an OO flavor. Sometimes this is extremely effective and idiomatic! But enums can be misused and overused in ways that are harmful to the design of the system or application. We will explore each of these, the positives and the negatives, in turn.

Rust enums are an amazing feature of the language. Whether they are called enums (in Rust), algebraic types (in Scala or Haskell), type unions (in Python or TypeScript), or sum types, they represent an incredible, expressive tool that allows for clear, simple, and elegant designs.

They are also an excellent way to express what we may think of as OO models and constructs, in an idiomatic way.

To illustrate this, let’s start over with our Bad Calculator and make it “not so bad.”

Rust enums actually have several features that have an OO flavor, if you think about it in that way:

  • Enums carry and encapsulate their own data
  • Enums allow many subtypes under the umbrella of one supertype
  • Enums make it simple to select behavior based on their type
  • Enums provide a way to reuse code within one implementation

But they are also different from what we think of as OO:

  • Enum variants do not have their own methods. They have one impl block for the type.
  • Enums require us to match on the variant everywhere they are used.
  • Enum variants don’t have a universal data layout or structure. Each variant is an independent type.

We can rethink our calculator with enums in mind.

Since we are not currently worried about operands (we will get to those), we will create a simple Value type that just holds an f64 value:

struct Value(f64);
impl Value {
fn evaluate(&self) -> f64 {
self.0
}
}

This code just contains the numerical value and allows us to retrieve it using the evaluate method.

Now we will consider the operators. We had so much difficulty and wrote so much code to create one of these earlier. Let’s implement it using an enum. We will make one variant for each operator, and we will keep the operand values directly in each variant struct:

enum Operator {
Addition { lhs: Value, rhs: Value },
Subtraction { lhs: Value, rhs: Value },
Multiplication { lhs: Value, rhs: Value },
Division { lhs: Value, rhs: Value },
Negation { operand: Value },
}

That is quite a bit simpler! In only a few lines, we’ve defined all of the operators and handled the storage of their operands.

Now we need to consider the methods required by each operator. We had the following:

  • An apply method that performed the calculation
  • A precedence method that returned a u8 representing the operator precedence
  • A symbol method that returned the character that we use to represent the operator in the interface

How much code will we need to implement these methods? How will we implement them?

Rust has a built-in pattern for that: we can match on the variant type and perform whatever actions we like in each of the match cases.

We can have the apply pattern match on each variant and bind variables to the values they contain. Then we can perform whatever calculations are needed.

We can write our precedence and symbol methods similarly, but we can ignore the contained values and collapse variants that produce the same result into one case each.

Here’s how we could code that:

impl Operator {
fn apply(&self) -> Value {
let inner = match self {
Operator::Addition { lhs, rhs } => lhs.evaluate() + rhs.evaluate(),
Operator::Subtraction { lhs, rhs } => lhs.evaluate() - rhs.evaluate(),
Operator::Multiplication { lhs, rhs } => lhs.evaluate() * rhs.evaluate(),
Operator::Division { lhs, rhs } => lhs.evaluate() / rhs.evaluate(),
Operator::Negation { operand } => -operand.evaluate(),
};
Value(inner)
}
fn precedence(&self) -> u8 {
match self {
Operator::Addition { .. } | Operator::Subtraction { .. } => 0,
Operator::Multiplication { .. } | Operator::Division { .. } => 1,
Operator::Negation { .. } => 2,
}
}
fn symbol(&self) -> char {
match self {
Operator::Addition { .. } => '+',
Operator::Subtraction { .. } => '-',
Operator::Multiplication { .. } => '*',
Operator::Division { .. } => '/',
Operator::Negation { .. } => '-',
}
}
}

When we consider how much code and how much complexity we had to create for just one operator in the previous implementation, it is surprising how few lines can accomplish five different operators with implementations for all of their methods.

This version is very simple to use. We can create values and operators natively and simply, and then call apply to get a result:

let addition = Operator::Addition { lhs: Value(2.0), rhs: Value(3.0) };
let subtraction = Operator::Subtraction { lhs: Value(5.0), rhs: Value(1.0) };
let negation = Operator::Negation { operand: Value(-7.0) };
println!("Addition result: {}", addition.apply().evaluate());
println!("Subtraction result: {}", subtraction.apply().evaluate());
println!("Negation result: {}", negation.apply().evaluate());

In our previous implementation, we did have an Operand type that could contain more than just a Value type (though we didn’t actually make any additional Operand types). For completeness, let’s add that. We’ll use an enum (with one variant, for now) to represent operands:

enum Operand {
Value(f64)
}
impl Operand {
fn evaluate(&self) -> f64 {
match self {
Operand::Value(v) => *v
}
}
}

We also need to change the implementation of Operator to use the new Operand type. It’s just a search and replace (and one change where we create the value we’re returning):

enum Operator {
Addition { lhs: Operand, rhs: Operand },
Subtraction { lhs: Operand, rhs: Operand },
Multiplication { lhs: Operand, rhs: Operand },
Division { lhs: Operand, rhs: Operand },
Negation { operand: Operand },
}
impl Operator {
fn apply(&self) -> Operand {
let inner = match self {
Operator::Addition { lhs, rhs } => lhs.evaluate() + rhs.evaluate(),
Operator::Subtraction { lhs, rhs } => lhs.evaluate() - rhs.evaluate(),
Operator::Multiplication { lhs, rhs } => lhs.evaluate() * rhs.evaluate(),
Operator::Division { lhs, rhs } => lhs.evaluate() / rhs.evaluate(),
Operator::Negation { operand } => -operand.evaluate(),
};
Operand::Value(inner)
}
// [The "precedence" and "symbol" methods don't change]
}

With only a fraction of the code needed to (badly) implement one operator, our not-so-bad calculator has managed to implement five operators. We did this without sacrificing any of the principles that we use OO design to uphold.

We were able to do that because we didn’t try to make Rust act like an OO language. We leveraged features and patterns natural to the language, and we achieved dramatically different results.

“But,” I hear you say, “this is supposed to be a chapter about anti-patterns. How are enums misused in Rust? How and when do enums not make sense?”

That is an excellent question!

Let’s consider what we accomplished: we took an OO class hierarchy-based model, and we replaced it with an enum-based approach, combining the flexibility of an algebraic data type with a functional, pattern-matching approach to the methods.

We did amazing things with enums, so let’s see if we can overdo it!

One thing that may already be bothering you is the precedence and symbol methods. They work this way, but do we really need to match on the variants like that? Couldn’t we leverage the fact that the variants are already holding data and store even more data? That way, our methods could just return the value and would not have to match.

The first step is easy – we just need to add precedence and symbol to the data in each variant:

enum Operator {
Addition { lhs: Operand, rhs: Operand, precedence: u8, symbol: char },
Subtraction { lhs: Operand, rhs: Operand, precedence: u8, symbol: char },
Multiplication { lhs: Operand, rhs: Operand, precedence: u8, symbol: char },
Division { lhs: Operand, rhs: Operand, precedence: u8, symbol: char },
Negation { operand: Operand, precedence: u8, symbol: char },
}

Now we just need to initialize the data to the correct values. How will we do that? It would not be practical to have to specify these values each time we create a new instance of an operator.

We can create a new function to be the constructor. Maybe we needed to do that anyway. That should not be difficult.

As parameters, we need the operands and some way to specify what we are creating. There could be one or two operands, so we can either send in an array or slice of operands, or have the second one be optional. For the specification of what we are creating, we could perhaps use a string. The alternative would be a second enum that needs to be kept in sync with the Operator enum, which sounds worse.

Let’s try that:

fn new(operator_type: String, operand1: Operand, operand2: Option<Operand>) -> Self {
match operator_type.as_str() {
"add" => Operator::Addition { lhs: operand1, rhs: operand2.unwrap(), precedence: 0, symbol: '+' },
"sub" => Operator::Addition { lhs: operand1, rhs: operand2.unwrap(), precedence: 0, symbol: '-' },
"mul" => Operator::Division { lhs: operand1, rhs: operand2.unwrap(), precedence: 1, symbol: '*' },
"div" => Operator::Division { lhs: operand1, rhs: operand2.unwrap(), precedence: 1, symbol: '/' },
"neg" => Operator::Negation { operand: operand1, precedence: 2, symbol: '-' },
_ => panic!("Unknown operator")
}
}

Look carefully at the match arms. The "sub" case creates Operator::Addition and "mul" creates Operator::Division. Since apply() dispatches on the enum variant rather than the symbol field, subtraction silently performs addition and multiplication silently performs division. The compiler cannot catch this because each variant’s fields have identical types. This is precisely the kind of silent, hard-to-diagnose bug that stringly-typed interfaces invite: the code compiles, the tests might even pass for simple cases, but the results are wrong.

We’re now matching on a string when we didn’t have to, while also handling invalid parameters at runtime. We also need to update the apply method to deal with the existence of these parameters. In other words, we’re matching, but in a different place and for a worse reason.

That is one way to misuse enums.

But there is a much more ambitious way to do that.

In our not-so-bad calculator, we used an enum to represent what had previously required one level of inheritance in the Bad Calculator. But what if we want to represent more levels of inheritance?

Imagine a calculator that not only performs arithmetic operations but also handles text manipulation and date calculations. We might try to represent all these operations in a single Operator enum. We can create sub-enums for different sub-types, one for normal numbers, one for text, and one for dates:

enum ArithmeticOperator {
Addition { lhs: f64, rhs: f64 },
Subtraction { lhs: f64, rhs: f64 },
// ...
}
enum TextOperator {
Concatenate { lhs: String, rhs: String },
SubString { operand: String, bounds: Range<usize> },
// ...
}
enum DateOperator {
AddDays { lhs: Instant, rhs: Duration },
SubtractDays { lhs: Instant, rhs: Instant },
// ...
}
enum Operator {
Arithmetic(ArithmeticOperator),
Text(TextOperator),
Date(DateOperator),
}

We should probably change this to use one Operand type. It needs to cover all of these different data types:

enum Operand {
NumericValue(f64),
StringValue(String),
RangeValue(Range<usize>),
InstantValue(Instant),
DurationValue(Duration),
}

We’ve now covered examples of all of our different types. We have sub-enums for each kind of calculation. Now all we have to do is write apply.

Writing one apply method for everything with cascading match expressions seems like it may not be very readable. So, we can write sub-apply functions:

impl ArithmeticOperator {
fn apply(&self) -> Operand {
match self {
ArithmeticOperator::Addition {lhs, rhs} => todo!(),
ArithmeticOperator::Subtraction {lhs, rhs} => todo!(),
}
}
}
impl TextOperator {
fn apply(&self) -> Operand {
match self {
TextOperator::Concatenate {lhs, rhs} => todo!(),
TextOperator::SubString {operand, bounds} => todo!(),
}
}
}
impl DateOperator {
fn apply(&self) -> Operand {
match self {
DateOperator::AddDays {lhs, rhs} => todo!(),
DateOperator::SubtractDays { lhs, rhs} => todo!(),
}
}
}
impl Operator {
fn apply(&self) -> Operand {
match self {
Operator::Arithmetic(a) => a.apply(),
Operator::Date(d) => d.apply(),
Operator::Text(t) => t.apply()
}
}
}

This works, but now we have taken the relatively clean patterns we were using and made something that is very difficult to work with.

In an actual OO class hierarchy, we can package different pieces together and use polymorphism to ensure that only types that go together are used together. In this tiered mess, it’s difficult to reason about the code and difficult to know that the correct types of operands will be sent to the correct operators. We have to make this work at runtime and handle errors at each level.

Here, as before, trying to use OO thinking leads us to an unworkable design.

To solve something like this, a more idiomatic approach would be to build each calculator as its own module within the Rust application, keeping like types together through the module system. We will cover the topic of leveraging modules in Chapter 5, Creational Patterns: Making Things, and Chapter 9, Architectural Patterns.

In this chapter, we discussed the anti-pattern of trying to apply OO design in Rust. We examined how, though it may seem natural to use familiar OO patterns, and may even work to some extent, these patterns are not a path to successfully designing and building systems and applications in Rust.

First, we explored the reasons why while Rust can seem so much like an OO language, it really isn’t, and mistaking it for one can lead to bad designs and messy code.

Then we used our Bad Calculator project to try out using Rust traits as a stand-in for interfaces or pure abstract classes, and how this appeared at first to be a workable solution, but became less and less so as we built the application.

We next tried using the Deref trait to try to recreate the benefits of inheritance in our code, but discovered that this trick doesn’t pay off.

After that, we tried using generics to simulate a base class, and found that, while it seemed to work, it didn’t really.

Finally, we explored using enums for designs similar to some familiar OO patterns, and discovered that they are quite useful and idiomatic for this purpose, when used in their proper place, but that it is possible to overuse them when they do not make sense.

By understanding why OO design patterns do not work effectively in Rust, and by learning to identify when we are using OO design without being aware of it, we will be able to structure our code from the beginning to work with the language and the compiler rather than fighting them (which is a topic we will cover in Chapter 4, Don’t Fight the Borrow Checker). We also have a foundation for understanding the reason for, and value of, Rust-specific design patterns as we move forward.

In the next chapter, we will focus on the very common anti-pattern of using clone and Rc<T> to avoid having to worry about the borrow checker. This seems like a very easy solution to managing our data, but we will see that it is much less helpful than it appears. We will also continue our Bad Calculator project. We’ll see the effects of papering over errors with clone and Rc<T> in practice, and talk about how we could have approached things differently.