Ruby and duck typing: design by contract impossible?

后端 未结 8 1538
别那么骄傲
别那么骄傲 2020-12-14 09:16

Method signature in Java:

public List getFilesIn(List directories)

similar one in ruby

def get_fi         


        
8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 09:31

    While I love static typing when I'm writing Java code, there's no reason that you can't insist upon thoughtful preconditions in Ruby code (or any kind of code for that matter). When I really need to insist upon preconditions for method params (in Ruby), I'm happy to write a condition that could throw a runtime exception to warn of programmer errors. I even give myself a semblance of static typing by writing:

    def get_files_in(directories)
       unless File.directory? directories
          raise ArgumentError, "directories should be a file directory, you bozo :)"
       end
       # rest of my block
    end
    

    It doesn't seem to me that the language prevents you from doing design-by-contract. Rather, it seems to me that this is up to the developers.

    (BTW, "bozo" refers to yours truly :)

提交回复
热议问题