this post was submitted on 13 Aug 2024
31 points (100.0% liked)

Rust

5953 readers
13 users here now

Welcome to the Rust community! This is a place to discuss about the Rust programming language.

Wormhole

[email protected]

Credits

  • The icon is a modified version of the official rust logo (changing the colors to a gradient and black background)

founded 1 year ago
MODERATORS
31
Strategy Pattern in Rust (programming.dev)
submitted 2 months ago* (last edited 2 months ago) by [email protected] to c/[email protected]
 

Hey there, I'm currently learning Rust (coming from object-oriented and also to some degree functional languages like Kotlin) and have some trouble how to design my software in a Rust-like way. I'm hoping someone could help me out with an explanation here :-)

I just started reading the book in order to get an overview of the language as well.

In OOP languages, I frequently use design patterns such as the Strategy pattern to model interchangeable pieces of logic.

How do I model this in Rust?

My current approach would be to define a trait and write different implementations of it. I would then pass around a boxed trait object (Box<dyn MyTrait>). I often find myself trying to combine this with some poor man's manual dependency injection.

This approach feels very object oriented and not native to the language. Would this be the recommended way of doing things or is there a better approach to take in Rust?

Thanks in advance!

top 19 comments
sorted by: hot top controversial new old
[–] [email protected] 18 points 2 months ago (1 children)

I agree with the other suggestions so far, to wit:

1.dyn is fine, when you need it. People will give you a lot of guff about performance but vtable lookup on a dyn is no less performant than the same thing in C++ (in higher level languages almost every call is dynamically dispatched and those are used for plenty of serious, performant work).

  1. Use enums more.

  2. Use traits and generic functions

And I would add a couple of other thoughts.

For some DI type work, you can use cargo's Features to define custom build flags. You can then put variants on the same code (usually implementing a trait) in different modules and use conditional compilation on the Features to swap out which code is used. This is like a compile-time strategy pattern. I use it for testing, but also to swap out databases (using a local in-memory to test and a real one in prod) and to swap out graphical backends on my roguelike (compiles to OpenGL on windows but Metal on my Mac).

You'll probably want to learn Rust's macro system sooner than later as well. Sometimes a macro is better than a function when you need to generically operate over several types (function argument overloading, in other languages) or work on something in a general but well-structured way (tree walking for example).

[–] [email protected] 5 points 2 months ago

Thanks for your input! I'll have a look at both build flags and macros for sure! For my specific problem enums will do just fine I guess, but having an overview about the possibilities helps a lot!

[–] [email protected] 11 points 2 months ago (1 children)

Traits like std::io::Write are essentially Strategy pattern. Take a look at how that’s used. You’re doing it mostly how I would, except for the Box. Generally it’s preferred to use generic functions/types in Rust instead of dynamic dispatch, i.e. have a fn do_something<T: MyTrait>(imp: T) instead of a fn do_something(imp: &dyn MyTrait).

[–] [email protected] 6 points 2 months ago

Thanks for the advice! I didn't know generic functions were preferred. But it makes perfect sense if you think about it.

[–] [email protected] 9 points 2 months ago (1 children)

For a direct replacement, you might want to consider enums, for something like

enum Strategy {
    Foo,
    Bar,
}

That's going to be a lot more ergonomic than shuffling trait objects around, you can do stuff like:

fn execute(strategy: Strategy) {
    match strategy {
        Strategy::Foo => { ... }
        Strategy::Bar => { ... }
}

If you have known set of strategy that isn't extensible, enums are good. If you want the ability for third party code to add new strategies, the boxed trait object approach works. Consider also the simplest approach of just having functions like this:

fn execute_foo() { ... }
fn execute_bar() { ... }

Sometimes, Rust encourages not trying to be too clever, like having get vs get_mut and not trying to abstract over the mutability.

[–] [email protected] 2 points 2 months ago (1 children)

Thanks for the explanation! I think just using an enum will do perfectly well in my case.

[–] [email protected] 2 points 2 months ago (1 children)

To expand on why generics are preferred, just in case you haven't seen these points yet: the performance downsides of Box<dyn MyTrait> are,

  • methods use dynamic dispatch in this case
  • requires heap allocation

There is also a possible type theory objection which is that normally there is a distinction between types and traits. Traits are not types themselves, but instead define sets of types with shared behavior. (That's why the same feature in Haskell is called a "type class", because it defines a class of types that have something in common.) But dyn turns a trait into a type which undermines the type/trait distinction. It's useful enough to justify being in the language, but a little unsettling from a certain perspective.

[–] [email protected] 3 points 2 months ago (1 children)

That makes sense, thanks again! I think dynamic dispatch is not as much of a performance issue in my case, yet you're totally right not to waste resources that aren't actually needed. Keeping things on the stack if possible is also a good thing.

I'll definitely need to read more about Rusts type system but your explanation was already very helpful! I think this might be why my initial approach felt unnatural - it works but is quite cumbersome and with generics there seems to be a more elegant approach.

[–] [email protected] 4 points 2 months ago

Yeah the performance differences don't matter in most cases. Rust makes it tempting to optimize everything because the language is explicit about runtime representations. But that doesn't mean that optimizing is the best use of your time.

[–] [email protected] 8 points 2 months ago (1 children)

There's nothing wrong with using dyn if the problem calls for it. In most cases it's more idiomatic to use an enum to represent something like a strategy, but if your strategies are complicated entities in themselves, a trait is probably the right approach.

[–] [email protected] 1 points 2 months ago

Thanks for your reply!

[–] [email protected] 6 points 2 months ago (1 children)

I spent like a week on this last month. Usually you use enumeration, but I wanted to allow client code to define their own strategies. I tried the Box<dyn MyTrait> pattern because some of my strategies were composed of other strategies, and I wanted to clamp down on generic types. But I kept running into weirder and weirder compiler errors. Always asking for an additional restriction on the base trait. X, must be Copy, must be Send, must be Sized, must be 'static. On and on. My experience is if I'm getting a bunch of those then I'm off the Golden Path. So I just embraced the verbosity of using generics and its easy. Yes its more code but its better code.

[–] [email protected] 3 points 2 months ago

Always asking for an additional restriction on the base trait.

Some of these restrictions are reasonable, some you need to avoid. Without dyn the compiler just figures out whether those properties are congruent, with dyn you need to choose those properties explicitly.

must be Copy, must be Send, must be Sized, must be 'static

  • Send is typically reasonable and typically can be just added to the list.
  • Sized - not sure. Idea of dyn things typically relies on unsized things (and Box and friends to get back to the Sized world).
  • 'static - if you are OK at allocating here and there (i.e. not optimising for performance hard), limiting to 'static world (i.e. without other lifetimes and inner references) can be reasonable.
  • Sync is needed rarely, usually Send is enough.
  • Copy bound is typically too much, unless the data is very simple. Probably you need a .clone() and/or Arc somewhere.
  • Unpin can also be just added as needed, unless you are dealing with async and optimising allocations.

On and on.

The list of things that can be added in ... part of dyn Trait + ... is finite, so this "on and on" won't go forever. So after some time the trait definition and main consumers are expected to stabilise.

I’m off the Golden Path

dyn road is indeed a thinner and somewhat winding road compared to main, easy way of 'static + Sized things. But when it is really necessary (i.e. you need dynamically construct the strategies from parts, or you need to attach more strategies from plugins, or you want to avoid big bloated executables), there is little way around it.

So I just embraced the verbosity of using generics and its easy. Yes its more code but its better code.

If it works without dyn then probably it's OK to leave it that way.

Each of those dyn, async, impl<'a>, Pin, unsafe, macro_rules! things bump Rust experience a step right on Easy-Normal-Hard-Nightmare scale.

[–] [email protected] 2 points 2 months ago (1 children)

Minor nit: Kotlin is decidedly not a functional language.

Design patterns in OOP exist purely to solve the problems created by OOP itself. If you have a language with proper ADTs and higher order functions, the need for traditional design patterns disappear since the problems they solve are first-class features baked into the language.

The first-class replacement for the Strategy pattern (and many other patterns such as the Visitor pattern) is sum types (called enums in Rust).

[–] [email protected] 3 points 2 months ago (1 children)

Truth has been spoken.

Except that Kotlin is functional (just like Rust, C++, Visual Basic, JavaScript,...). It is, however, not Pure Functional (like Haskell or Lean4 would be - if you haven't checked out Lean4, I can recommend it, great fun).

(Sauce: https://en.wikipedia.org/wiki/List_of_programming_languages_by_type#Functional_languages)

[–] [email protected] 4 points 2 months ago (1 children)

That list also counts Java and C# as "functional languages". I wouldn't take it too seriously. Ocaml, Scala, F#, etc. are impure functional languages. Kotlin absolutely is not. Having a couple of features you might find in functional languages does not make a language functional. Kotlin is still very much an OOP-based language. It's basically a somewhat nicer Java.

[–] [email protected] 3 points 2 months ago (1 children)

I know, from a mathematics standpoint it does not make sense, but from how the term is used nowadays in programming it does: Those languages allow to compose functions, pass functions as parameters, return functions, etc.

[–] [email protected] 3 points 2 months ago (1 children)

A language is not functional just because it supports higher order functions. Technically C even supports them (even though the ergonomics and safety of them are terrible). Would you call C a functional programming language? Obviously not. Rust is also not a functional language, even though it comes closer than most OO/imperative languages.

Kotlin and plenty of other OO languages have borrowed some ideas from functional languages in recent years because those ideas are useful. That doesn't make them functional languages. If Kotlin were a functional language, then it wouldn't need libraries like arrow to try to make doing FP in Kotlin even (kind of) possible.

Hallmarks of FP (beyond higher-order functions), in no particular order:

  • Organization around functions as the fundamental unit of code
  • Code primarily defined in terms of expressions and data transformations rather than statements manipulating object state (so languages that have big blocks of imperative statements like Kotlin don't count)
  • A general orientation around pure functions, even if they vary on the degree to which they enforce purity
  • Explicit parameter passing being the standard and preferred way of providing data to functions, rather than methods operating on implicit state
  • First class support for function composition (method chaining doesn't count)
  • Pattern matching and destructuring as a first-class and ubiquitous concept (what Kotlin does have is a joke comparatively and no one would actually call it that)
  • For statically-typed functional languages, first class support for algebraic data types (Kotlin has sealed classes which can kind of be used to try to emulate it, but it's pretty awkward in comparison and requires you to write very OO-ish code to use)

There are some minor exceptions, such as Clojure lacking pattern matching, but on the whole functional languages generally fit these descriptions.

[–] [email protected] 2 points 2 months ago

Points that I would gladly agree upon - but it seems the Wikipedia authors don't.

I am not knowledgeable enough to draw a definite line what counts as functional and what doesn't - so I chose to go with whatever Wikipedia says... Even though I dislike it.