请忍住,编程中别自作聪明

人人都有很高的欲望在编程中表现自己的聪明。你想卖弄一下,用你高超的技巧写出一段最奇巧的代码。它让你得到少有的成就感。然而,我发现,对于大多数人来说,这对于一个项目的长期维护工作来说并不是一件好事。

比如像Ruby这样的语言,非常的灵活强大,使用这种语言耍聪明非常容易。而就像人们常说的更大的能力伴随的是更大的责任。所以,下面有一些对年轻程序员的谏言:在你的个人项目,娱乐项目中写出最奇巧的代码,以此来满足你的成就感,但在给客户做的项目中,你有责任让代码通俗易懂,请写出常规的代码。

temptation-to-be-clever

下面是一个小例子,比较奇巧的代码和常规代码的区别。

奇巧的代码

  def address_is_empty?(customer)
    [:street, :city, :state, :zip].any?{|method| customer.send(method).nil? || customer.send(method).squish.empty? }

  end

常规代码

  def address_is_empty?(customer)

    [customer.street, customer.city, customer.state, customer.zip].any?{|prop| prop.nil? || prop.squish.empty? }

  end

你能理解吗?

[英文原文:Resisting the temptation to be clever ]
分享这篇文章:

6 Responses to 请忍住,编程中别自作聪明

  1. sailtsao says:

    这”奇巧”代码不难懂啊,不懂的话只能说ruby没学好…
    话说常规代码多打了这么多的customer,累不累啊…这样的代码一点都不符合ruby的宗旨–“让程序员能少打一个字母就少打一个字母”

  2. scriptfans says:

    典型的代码坏味道……这段算法本该是customer对象的职责,直接在Customer类里面去实现会比较好(严格说来,抽象出一个Address类更合适):
    class Customer
    def initialize(address)
    @address
    end

    def address_is_empty?
    @address.empty?
    end
    end

    class Address
    attr_accessor :street, :city, :state, :zip
    def empty?
    instance_variables.all? do |key|
    value = instance_variable_get(key)
    value.blank? || value == ’empty’
    end
    end
    end

  3. scriptfans says:


    class Customer
    def initialize(address)
    @address = address
    end

    def address_is_empty?
    @address.empty?
    end
    end

    class Address
    attr_accessor :street, :city, :state, :zip

    def empty?
    instance_variables.all? do |key|
    value = instance_variable_get(key)
    value.blank? || value == 'empty'
    end
    end
    end

发表评论

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据