Learn
Best Practices
Fluent Interface

Fluent Interfaces

OOP traditionally intertwines data and logic, creating potential issues with data manipulation and access, whereas FP, with its module-centric approach, risks name collision and can compromise integrity due to the independent nature of functional modules.

Fluent Interfaces allow for method chaining to create a more readable and concise API, which can help in mitigating the issues found in OOP and FP by providing a clear and efficient way to construct object instances without mixing data with logic and avoiding module conflicts and integrity breaches.

How to Implement

// Data
struct Counter(u32);
 
// Logic
impl Counter {
    fn add(&mut self, n: u32) -> &mut Self {
        self.0 += n;
        self
    }
 
    fn times(&mut self, n: u32) -> &mut Self {
        self.0 *= n;
        self
    }
 
    fn print(&self) -> () {
        println!("Counter: {}", self.0);
    }
}
 
// Program
fn main() {
    let mut counter = Counter(0);
 
    counter.add(1).times(5).add(2).print(); // Counter: 7
}

References