DCI in Rust

21 views
Skip to first unread message

Matthew Browne

unread,
May 2, 2024, 6:25:25 PMMay 2
to object-co...@googlegroups.com

I have been learning a bit about Rust, and I was able to get a pretty good DCI example working based on this existing example:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a007eb593e3e12f5b965a3db5775f691

Rust is an interesting language from an OO and DCI standpoint... It has objects but doesn't have classes or inheritance. It has "traits," which are different from the kind of traits I was referring to in my previous thread—in Rust, traits are more like interfaces, although they can optionally provide default method implementations. The interesting thing for DCI is that trait methods are only available on an object if that trait has been imported into the current file or module—not quite as good as the context automatically enforcing the privacy of role methods like in trygve, but it avoids the need to inject or un-inject role methods. I suppose it's similar to the C++ implementation in some ways, including how role-object contracts are enforced at compile-time.

Here are the improvements I made on the original example:

1. I moved the data methods (available_balance(), decrease_balance(), and increase_balance()) to the data module (they were previously defined within the context).

2. I'm still learning Rust and don't really know what I'm doing, but I managed to add a macro so that the above methods would be available both on the Account type and on the role-player traits. This causes compiler warnings about the Account.available_balance, Account.increase_balance, and Account.decrease_balance being unused...I wonder if there is a better way to do it that doesn't require the use of a macro. But the code executes just fine with my current solution, and the available_balance, increase_balance, and decrease_balance methods can be called from anywhere.

3. The role methods in the context are now private and can't be accessed outside the context.

In summary, I think Rust is a promising language for DCI programming, and BTW it compiles to WebAssembly too which means it can run in the browser. Rust also runs on every platform that LLVM supports (AKA most common platforms).

P.S. This is a good article about Rust's classless design and some of its advantages: https://www.thecodedmessage.com/posts/oop-3-inheritance/

Reply all
Reply to author
Forward
0 new messages