1 Clean Code

After reading the Ch. 1, Clean Code from Robert Martin’s book, one thing especially impressed and resonated me.

That is to use annotations when it is necessary. A few years ago, I would not comment any unless the codes were so messy that even I at that point could not understand what I was coding after minutes. At that time, I felt like only green hands need extra explanation, and good codes should explain how they work themselves.

For example, bad codes use unnecessary comments like this:

// check to see if the employee is eligible for full benefit
if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)){}

Obviously, the latter can clearly express the purpose of itself.

But now I gradually realize that sometimes comments are necessary cause the expressiveness of codes is limited.

Among the necessity clarification of comments in the chapter, I most agree with “Comment to Explain Intent” and “The Importance of Amplifying What Seems Unreasonable”[1]. Because what to do is easy to express by naming, but why it is not intuitive, especially when it involves professional knowledge and algorithms. In addition, some codes that feel “not so elegant” at first may have special wishes, so such codes should be commented to explain why this is the case. For example, in order to improve the performance of the critical path, the reliability of some codes may be sacrificed. readability.


2 code-smells

The third chapter of this book –  Bad Code Smells was very inspiring to me. Because I also like to think about whether there are these “bad smells” in my code after writing the code-I always hope that my code is clean and elegant-and then think about how to adjust my codes. I like the word in the chapter that “Code has many bad smells, and repetition is the worst kind”[1]. I’ve been trying to avoid duplicate code when programming and I found that it is easy to tell some replicate

codes, but there are cases that are difficult for programmers to detect. For instance, when there are two similar functions in two irrelevant classes, we are likely to ignore them.

Faced with this situation, we can first extract the method, and then move the method to the newly created class to eliminate duplication.

Before:

class App1 {
    val last3 = scores.sort().take(3)
}

class App2 {
    val last10 = scores.sort().take(10)
}

After:

class App1 {
          val last3 = Seqs.lastN(scores, 3)
      }

      class App2 {
          val last10 = Seqs.lastN(scores, 10)
      }

      object Seqs { // new util
          def lastN[E](seq: Seq[E], n: Int)
: Seq[E] = {
                  seq.sort().take(n)
          }
      }

Although it looks like there is more code in this example, the code is actually more readable and maintainable because the same function is extracted for easy refactoring.