天天看点

【Java基础】方法

Num1:检查参数的有效性

绝大多数的方法和构造器对于传递给它们的参数值都会有某些限制。比如:索引值必须是非负数,对象引用不能为

null

等等。这些都很常见,你应该在文档中清楚地指明所有这些限制,并在方法体的开头处检查参数,以强制施加这些限制。

示例代码:

public BigInteger mod(BigInteger m){       	if(m.signum()<=0){     		throw new ArithmeticException("Modulus <= 0"+m);       	}     }           

Num2:慎用重载

看个问题代码:

public class CollectionClassifier {     	public static String classify(Set<?> s) {     		return "Set";     	}     	public static String classify(List<?> lst) {     		return "List";     	}     	public static String classify(Collection<?> c) {     		return "Unknown Collection";     	}     	public static void main(String[] args) {     		Collection<?>[] collections = { new HashSet<String>(),     				new ArrayList<BigInteger>(),     				new HashMap<String, String>().values() };     		for (Collection<?> c : collections)     			System.out.println(classify(c));     	}     }           

这个代码最终的三个结果是:“Unknown Collection”,为何会这样的呢,是方法被重载了,而要调用哪个重载方法是在编译时做出决定的。

可以因覆盖来代替试试。

class Wine {     	String name() {     		return "wine";     	}     }     class SparklingWine extends Wine {     	@Override     	String name() {     		return "sparkling wine";     	}     }     class Champagne extends SparklingWine {     	@Override     	String name() {     		return "champagne";     	}     }     public class Overriding {     	public static void main(String[] args) {     		Wine[] wines = { new Wine(), new SparklingWine(), new Champagne() };     		for (Wine wine : wines)     			System.out.println(wine.name());     	}     }           

输出的结果是:

wine,sparkling wine,champagne

Num3:慎用可变参数

示例代码

public class Varargs {     	// Simple use of varargs - Page 197     	static int sum(int... args) {     		int sum = 0;     		for (int arg : args)     			sum += arg;     		return sum;     	}     	// The WRONG way to use varargs to pass one or more arguments! - Page 197     	// static int min(int... args) {     	// if (args.length == 0)     	// throw new IllegalArgumentException("Too few arguments");     	// int min = args[0];     	// for (int i = 1; i < args.length; i++)     	// if (args[i] < min)     	// min = args[i];     	// return min;     	// }     	// The right way to use varargs to pass one or more arguments - Page 198     	static int min(int firstArg, int... remainingArgs) {     		int min = firstArg;     		for (int arg : remainingArgs)     			if (arg < min)     				min = arg;     		return min;     	}     	public static void main(String[] args) {     		System.out.println(sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));     		System.out.println(min(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));     	}     }           

Num4:返回零长度的数组或者集合,而不是Null

有时候有人会认为:

null

返回值比零长度数组更好,因为它避免了分配数组所需要的开销。这种观点是站不住脚的。

原因如下:

1,在这个级别上担心性能问题是不明智的。

2,对于不返回任何元素的调用,每次都返回同一个零长度数组是有可能的,因为零长度数组是不可变的,而不可变对象有可能被自由地共享。

简而言之,返回类型为数组或集合的方法没理由返回

null

,而不是返回一个零长度的数组或集合。