Things I tend to forget when coding

Posted on 2023-10-02

After a few years of learning and doing programming, I now caught myself in situations where I wrote bad(-style) code because I forgot the good. The reasons may vary but one stands out: I do not really take a concept or definition seriously at the very beginning. This post is therefore a note for now me and future me.

Expressions

if block

I started my programming journey with Python. In Python’s term, if is a statement1 instead of expression. That means in Python’s if blocks, rarely did I even think about returning a value or result.

In Rust, however, since if is followed by a block, it can also act as expressions2. That is to say, it is fairly common in Rust to return a value from a if block:

// This
let x = if a != 10 { a } else { a + 1 };

// Instead of this
let mut x = 0;
if a != 10 {
    x = a;
} else {
    x = a + 1;
}

Or in Haskell3, the mandatory else branch requires that something must be returned:

doubleSmallNumber x = (if x = 10 then x else x*2) + 1

Or in Clojure4:

(if (= a 10)
  a
  (* a 2))

boolean expressions

My die-hard habit is the following:

if x != 10 {
    correct = false;
} else {
    correct = true;
}

But why not simply this:

correct = x != 10;

In many languages including Java, when an expression evaluates to a value, I should use the expression’s return value, rather than merely evaluate it.

.length v.s. len()

It’s normal to loop over an array using something like

for (int i=0; i<arr.length; i++) // do sth here

In Java the length property is static and determined at compile time.5 That means accessing its value is of O(1) time complexity.

Yet sometimes, especially for dynamical arrays, using len() method may have some overhead. Thus, it is good to store its length in a variable and use that thereafter (assuming the length doesn’t change…)

int N = someArr.len();
for (int i=0; i<N; i++) // do sth here

References


  1. https://docs.python.org/3/tutorial/controlflow.html↩︎

  2. https://doc.rust-lang.org/std/keyword.if.html↩︎

  3. https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-320003.6↩︎

  4. https://clojure.org/reference/special_forms#if↩︎

  5. https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html↩︎