Explicit rules for readbility or abstract over the principle for expresivity

⚓ Rust    📅 2025-10-31    👤 surdeus    👁️ 6      

surdeus

Warning

This post was published 32 days ago. The information described in this article may have changed.

Hi Guys, I'm struggling to make up my mind which is better:

A

Pros:

  • Easy to read.

Cons:

  • Principle is inferred.
pub fn colour(&self, is_turing: bool, has_review: bool, tag: Option<&TagBasic>) -> Colour {
    let tag_or = |default| tag.and_then(|t| t.colour).unwrap_or(default);

    if self.is_suggested_change() {
        return tag_or(Colour::SUGGESTED_CHANGE);
    }

    if self.is_redaction() {
        return tag_or(Colour::REDACTION_DEFAULT);
    }

    if self.is_regular_manual(is_turing) {
        return tag_or(Colour::HIGHLIGHT_DEFAULT);
    }

    if is_turing {
        return if has_review {
            tag.map(|t| t.colour.unwrap_or(Colour::HIGHLIGHT_DEFAULT))
                .expect("turing highlights are always applied to tags")
        } else {
            // An Open turing suggestion.
            Colour::TURING_RESULT
        };
    }

    unimplemented!("encountered a highlight kind without a specified colour")
}

B

Pros:

  • Principle is declaraitve.

Cons:

  • Hard to read.
pub fn colour(&self, is_turing: bool, has_review: bool, tag: Option<&TagBasic>) -> Colour {
    enum Origin {
        Human(Colour),
        Machine(Colour),
    }

    // Define default fallback colours for every highlight kind:
    let origin = if self.is_suggested_change() {
        Origin::Human(Colour::SUGGESTED_CHANGE)
    } else if self.is_redaction() {
        Origin::Human(Colour::REDACTION_DEFAULT)
    } else if self.is_regular_manual(is_turing) {
        Origin::Human(Colour::HIGHLIGHT_DEFAULT)
    } else if is_turing {
        Origin::Machine(Colour::TURING_RESULT)
    } else {
        unimplemented!("encountered a highlight kind without a specified default colour")
    };

    match origin {
        // Human generated highlights get their tag colour, if they have a
        // tag, or fallback to their associated default:
        Origin::Human(default) => tag.and_then(|t| t.colour).unwrap_or(default),

        // Machine generated highlights get their tag colour, if they have
        // been reviewed, or fallback to their associated deafault:
        Origin::Machine(default) => match has_review {
            true => tag
                .map(|t|
                // NOTE: the default of a tag without a specified colour,
                //       is the highlight default.
                t.colour.unwrap_or(Colour::HIGHLIGHT_DEFAULT))
                .expect("machine generated highlight missing tag"),
            false => default,
        },
    }
}

1 post - 1 participant

Read full topic

🏷️ Rust_feed