第一周课程备注

1.基本数据类型在测试中需要注意的点

1.1 对象相等的比较(Integer)

  • Integer,128==判断为false,equals判断为true
Integer i1 = 128;
Integer i2 = 128;
System.out.println(i1 == i2); // false
System.out.println(i1.equals(i2)); // true
  • Integer,127==判断为true,equals判断为true
Integer i1 = 127;
Integer i2 = 127;
System.out.println(i1 == i2); // true
System.out.println(i1.equals(i2)); 
  • int,127相等判断为true
int i1 = 127;
int i2 = 127;
System.out.println(i1 == i2);
  • int,128相等判断为true
int i1 = 128;
int i2 = 128;
System.out.println(i1 == i2);

1.2 其他数据类型?

  • Byte, Float, Long, Byte, String

1.3 why?

  • Integer在新建对象时,如果数据在-128到127之间时则从缓存中拿,如果数据超过此范围后则新建对象

1.4 需要注意的点

  • 开发的代码中经常有诸如status,type等数字类型的相等判断,此时需要注意判断双方的使用方式,如果是对象则使用equals
  • 在转换类型时,如String str="123",转成Integer时使用Integer.parseInt(str)
public static Integer valueOf(String s) throws NumberFormatException {
    return Integer.valueOf(parseInt(s, 10));
}
public static Integer valueOf(int i) {
    if (i >= IntegerCache.low && i <= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}
// 这里定义缓存的边界
static final int low = -128;
static final int high;
int h = 127;
  • flost精度缺失

2.if的未闭合问题

2.1 开发时常见的有问题写法

  • 写法1,只处理业务需要的数值
public void checkStatus(int status) {
    if (status == 1) {
        System.out.println("do 1");
    } else if (status == 2) {
        System.out.println("do 2");
    }
}
  • 写法2,只处理需求需要的结果
public void doHandle() {
    String errorCode = "do sth";

    if (errorCode.equals("1000")) {
        // return succes
    } else if (errorCode.equals("2000")) {
        // return fail
    }
}

2.2 问题阐述

  • 其实这样看就很简单了,如果传入的status==3时,假设给一个不存在的数据如何处理业务?
  • 处理结果时,一定是一个闭集,正确的,错误的,任何一个都不能放过

3.for

3.1 for比较推崇的写法

String[] datas = new String[10];
for (int i = 0, len = datas.length; i <; i++) {
    System.out.println(datas[i]);
}

4.方法

4.1 签名

  • 方法名要简洁清晰,见名知意,这个可以参考阿里巴巴推出的Java规范看一下
  • 方法参数不可过多,超过3个参数就要考虑使用实体进行封装
  • 方法参数即使很少,比如2个时,若参数的数据类型一致,那么就要考虑是否有混淆的危险,比如 addUser(String name,String address), 如果不小心很容易传乱,这样的方法设计也不够友好

你可能感兴趣的:(第一周课程备注)