API naming convensions

Let's say you have an API that allows an object to call a closure to modify itself if a predicate is fulfilled:

impl Something {
  fn foo(self, pred: bool, f: F) -> Self
  where
    F: FnOnce(Self) -> Self
 {
    if pred {
      f(self)
    } else {
      self
    }
  }
}

What would you call foo? map_if()? But is it idiomatic to call it a "map" if it maps Self -> Self?

(Asking what's idiomatic for Rust).

Is there an official guide for API naming conventions in std?

I think the naming chapter of the api guidelines is what you are looking for, though it doesn't cover how you should name foo.

I wouldn't be too concerned about using map as part of the function name, because f(Self) -> Self is still a mapping.

There's one thing though that got me thinking recently, after reading this blog post by matklad: pushing ifs up. I'm not sure if I 100% agree that pushing ifs up is always a good idea, but it certainly applies to your example. Maybe in your case it would be better to move the if statement to the caller?

2 Likes

@H2CO3 convinced me not long ago that if there are two valid options, then there's no reason to pick only one, and this is one of those cases: I have an option where the caller can make the branch, and another where the method can make the branch.

The place where the second comes in handy is when using the Builder pattern [that chains ownership], and you want to allow the caller to make compact object initializations that may sometimes be conditional.

Basically this:

let bldr = Builder::new("something")
  .attr("Hello", "World");
let bldr = if condition {
  bldr.attr("Something", "else")
} else {
  bldr
};
let obj = bldr.build();

.. can be expressed as:

let obj = Builder::new("something")
  .attr("Hello", "World")
  .attr_if(condition, "Something", "else")
  .build();

(This is a very minimal example; the ones I actually work with become massive unwieldy hair-balls if I don't use the _if construct).

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.