← All posts
Oct 23, 2017

Some thoughts about coding

While browsing code these days, reading some wonderful pieces and some awful lines, some thoughts came into my mind.

Ben Cao · 2 min read · 0 comments

While browsing code these days, reading some wonderful pieces and some awful lines, some thoughts came into my mind.

Let’s start from some code smells first.

Smell 1 — Hide complexity/detail in a bad way

Case 1:

check_point!(:beauty)

What does it mean here? I have no choice but follow to the actual check_beauty method to see what happens. How about change it to:

should_have!(:perfect_shape)
should_not_have!(:big_mouth)
should_be!(:tender)
should_not_be!(:angry)

It’s inefficient to switch between different stack levels when reading code, human brain isn’t designed for that

Case 2:

if user_active?
  send_promotion_about_beauty_product
end

Send beauty promotion to all users? Sounds like a huge waste. In fact, here is send_promotion_about_beauty_product:

def send_promotion_about_beauty_product
  return unless user_female?
  # do send stuff
end

What if we shift the guard condition a level up:

if user_active? && user_female?
  send_promotion_about_beauty_product
end

Looks better?

Smell 2 — Expose complexity/detail in a bad way

Case 1:

def charge!(users, amount)
  users.each do |user|
    if user.active? && !user.paid?
      user.balance = user.balance - amount
      user.orders.create!(:amount => amount, :created_at => Time.now)
      user.send_order_email
     end
  end
end

The logic is a bit verbose, too many details are there, some we don’t really care that much.

What if:

def charge!(users, amount)
  users.each do |user|
    if user.active? && !user.paid?
      user.create_charge_order(amount)
    end
  end
end

def create_charge_order(amount)
  self.balance = self.balance - amount
  self.orders.create!(:amount => amount, :created_at => Time.now)
  self.send_order_mail
end

This make charge! method much more clear, and leave details to their own methods.

Conclusion

You might have noticed that all I’m talking here is all hide/expose complexity?

According to my understanding, good code is an elegant expressing of the concept in your mind, for each level(Class, public method, private helper method) the complexity/detail has been exposed to the most proper level, no more no less.

With this principle in mind, the most difficult tasks for coding are now answering those questions:

  • Which level is most appropriate for putting info the concept?
  • Does this Class have the proper responsibility, isn’t it handling too much or too few?
  • Any separation needed for that complex Class or method?

So finally coding is becoming an art. Just as how a beauty dresses, too much is not fashion but also too few is also not appropriate.


Originally published on Medium on October 23, 2017.

No comments yet. Be the first.

Optional. Leave it blank to post as Anonymous.