Do you wrap chaining functions?

When coding in Rust it's common to have chaining functions like a().b().c().... A single function could contain more than 50~60 LOC (more than one screen on my laptop) with several these code blocks after formatting by rustfmt. (Sometimes more than 100 LOC.) Long function body seems hard to read.

Do you wrap chaining function like this ONLY to write less code in the call side?

pub async fn starred_repos(
    octocrab: &Octocrab,
    per_page: u8,
) -> Result<impl Stream<Item = Result<Repository, octocrab::Error>> + '_, Error> {
    Ok(octocrab
        .current()
        .list_repos_starred_by_authenticated_user()
        .per_page(per_page)
        .send()
        .await?
        .into_stream(octocrab))
}

pub async fn user_repos(
    octocrab: &Octocrab,
    per_page: u8,
) -> Result<impl Stream<Item = Result<Repository, octocrab::Error>> + '_, Error> {
    Ok(octocrab
        .current()
        .list_repos_for_authenticated_user()
        .per_page(per_page)
        .send()
        .await?
        .into_stream(octocrab))
}

I don't want to think about it so I rust let rustfmt do its thing.

5 Likes

Whether or not the implementation is using chaining specifically isn't something I think about. If the function is useful, make it, otherwise don't. Functions vs methods are, in general, pretty orthogonal to that.

3 Likes

If you think a block of code would benefit from a description/name put it into a well named function.

Example:

- // this is doing this
- foo.calling(bar)
+ fn do_thing() { foo.calling(bar) }
+ do_thing()
3 Likes

I agree with @erelde ; if I think a particular chain would be common, or if I want to describe specifically what it is doing, I would at least consider putting it in a function. But I wouldn't do it for aesthetic/readability reasons; if the chain is too long I assume rustfmt will put it on separate lines to make it readable.

1 Like

This is a known problem that hasn't been resolved for years. You could try to put up with it, use #[rustfmt::skip], tinker with configurations, try to change rustfmt(issues, pull requests, rfcs), use a different formatter, or use no formatter.

rustfmt is supposed to be the standard for all Rust code, but the decisions it made are far from unanimous. Deviation from the default formatting is often discouraged, but in its current state, authors cannot always be blamed for it. When in doubt, use your own judgment as well as machine-made ones to improve on the code quality.

2 Likes

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.