Ruby and duck typing: design by contract impossible?

后端 未结 8 1553
别那么骄傲
别那么骄傲 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:29

    Method Validation via duck-typing:

    i = {}
    => {}
    i.methods.sort
    => ["==", "===", "=~", "[]", "[]=", "__id__", "__send__", "all?", "any?", "class", "clear", "clone", "collect", "default", "default=", "default_proc", "delete", "delete_if", "detect", "display", "dup", "each", "each_key", "each_pair", "each_value", "each_with_index", "empty?", "entries", "eql?", "equal?", "extend", "fetch", "find", "find_all", "freeze", "frozen?", "gem", "grep", "has_key?", "has_value?", "hash", "id", "include?", "index", "indexes", "indices", "inject", "inspect", "instance_eval", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "invert", "is_a?", "key?", "keys", "kind_of?", "length", "map", "max", "member?", "merge", "merge!", "method", "methods", "min", "nil?", "object_id", "partition", "private_methods", "protected_methods", "public_methods", "rehash", "reject", "reject!", "replace", "require", "respond_to?", "select", "send", "shift", "singleton_methods", "size", "sort", "sort_by", "store", "taint", "tainted?", "to_a", "to_hash", "to_s", "type", "untaint", "update", "value?", "values", "values_at", "zip"]
    i.respond_to?('keys')
    => true
    i.respond_to?('get_files_in')  
    => false
    

    Once you've got that reasoning down, method signatures are moot because you can test them in the function dynamically. ( this is partially due to not being able do do signature-match-based-function-dispatch, but this is more flexible because you can define unlimited combinations of signatures )

     def get_files_in(directories)
        fail "Not a List" unless directories.instance_of?('List')
     end
    
     def example2( *params ) 
        lists = params.map{|x| (x.instance_of?(List))?x:nil }.compact 
        fail "No list" unless lists.length > 0
        p lists[0] 
     end
    
    x = List.new
    get_files_in(x)
    example2( 'this', 'should', 'still' , 1,2,3,4,5,'work' , x )
    

    If you want a more assurable test, you can try RSpec for Behaviour driven developement.

提交回复
热议问题