zoukankan      html  css  js  c++  java
  • [改善Java代码]别让null值和空值威胁到变长方法

    建议5:别让null值和空值威胁到变长方法

     1 public class Client {  
     2     public void methodA(String str,Integer... is){       
     3     }  
     4      
     5     public void methodA(String str,String... strs){          
     6     }  
     7      
     8     public static void main(String[] args) {  
     9           Client client = new Client();  
    10           client.methodA("China", 0);  
    11           client.methodA("China", "People");  
    12           client.methodA("China");  
    13           client.methodA("China",null);  
    14     }  
    15 } 

    两个methodA都进行了重载,现在的问题是:上面的代码编译通不过,问题出在什么地方?看似很简单哦。

    有两处编译通不过:client.methodA("China")和client.methodA("China",null),估计你已经猜到了,两处的提示是相同的:方法模糊不清,编译器不知道调用哪一个方法,但这两处代码反映的代码味道可是不同的。(The method methodA(String, Integer[]) is ambiguous for the type Client)

    KISS原则(Keep It Simple, Stupid,即懒人原则),按照此规则设计的方法应该很容易调用,可是现在在遵循规范的情况下,程序竟然出错了,这对设计者和开发者而言都是应该严禁出 现的。

    对于client.methodA("china",null)方法,直接量null是没有类型的,虽然两个methodA方法都符合调用请求,但 不知道调用哪一个,于是报错了。我们来体会一下它的坏味道:除了不符合上面的懒人原则外,这里还有一个非常不好的编码习惯,即调用者隐藏了实参类型,这是 非常危险的,不仅仅调用者需要“猜测”该调用哪个方法,而且被调用者也可能产生内部逻辑混乱的情况。对于本例来说应该做如下修改:

    1 public static void main(String[] args) {  
    2      Client client = new Client();  
    3      String[] strs = null;  
    4      client.methodA("China",strs);  
    5 } 

    也就是说让编译器知道这个null值是String类型的,编译即可顺利通过,也就减少了错误的发生。

  • 相关阅读:
    熬夜到凌晨2点半

    浏览器F12,Network中各按钮的作用
    postman收藏 -大佬玩法。
    Windows日常快捷键
    认识jmeter(一)
    web测试:test过程中接口报错 "Object reference not set to an instance of an object."
    postman-error:SyntaxError: Invalid shorthand property initializer
    mysql 表结构及基本操作
    getinstance方法(转)
  • 原文地址:https://www.cnblogs.com/DreamDrive/p/5412464.html
Copyright © 2011-2022 走看看