luo.box

Some basic things

Published:

Always use half-closed search interval

Alywas use [left, right) (closed on the left and open on the right) as your search interval in algorithms like binary search or insertion point.

  1. It’s intuitive.
  2. The difference of the two ends, e.g. 4-0=4 in [4, 0) is exactly the length of the interval of the array.
  3. The adjacent interval, e.g. [0, 2) and [2, 4), the median (2) can be easily spotted.

Builder needs to be built

For the builder method pattern, if you have Foo and FooBuilder, consider adding a builder method to Foo:

struct Foo { ... }

#[derive(Default)]
struct FooBuilder { ... }

impl Foo {
    fn builder() -> FooBuilder {
        FooBuilder::default()
    }
}

impl FooBuilder {
    fn build(self) -> Foo { ... }
}

Thus, users only need to know and import Foo. source.

Focus on properties and invariants

Properties and invariants is what underlines most big and successful systems. Sketch the loop invariants before every algorithm implementation, and do property based testing.

Always use < or <=

Only use Tab

#programming