写bug-free 的code

一个算法题目 写的没有bug,是件不easy的事情

必需要考虑全面,事实上就是你算法过程中,每一个变量是否适用,你的算法是在什么样的前提以下展开的

这个和參数检查是另外一件事情。參数检查被说的好像是一个必需要做的过程。事实上这个跟详细实现由关系

假设详细实现无关參数,那就不须要做什么參数检查

例如说 非常多时候都要检查传入參数是不是null,假设函数要取这个地址的值。那必需要检查这个指针是否是null,这跟參数检查无关

举个样例

Implement strStr()

 

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

这个是leetcode上面的一个题目。咱们就写最暴力的方法。可是做到bug-free也不是要非常细致的

我第一次的代码是 


    public String strStr(String haystack, String needle) {
        		for (int i = 0; i < haystack.length(); i++) {
				for(int j = 0;j<needle.length();j++){
					if(haystack.charAt(i+j) == needle.charAt(j)){
						if(j == needle.length() -1)
							return haystack.substring(i);
						else
							continue;
					}else{
						break;
					}
				}
				
		}
		return null;
    }

这个错误是考虑不全面,事实上在写i+j 时候就该考虑 i+j 是不是越界了。

看我的第二次代码

   public String strStr(String haystack, String needle) {	
                if(haystack == null || haystack.length() == 0){
			return null;
		}
		if(needle == null || needle.length() == 0){
			return haystack;
		}
		for (int i = 0; i < haystack.length(); i++) {
				for(int j = 0;j<needle.length();j++){
					if(i + j >= haystack.length()) return null;
					if(haystack.charAt(i+j) == needle.charAt(j)){
						if(j == needle.length() -1)
							return haystack.substring(i);
						else
							continue;
					}else{
						break;
					}
				}
				
		}
		return null;}

这次差点儿就是正确了,可是还是没过,把最開始那两句调整了位置。就过去了。最后代码例如以下。



    public String strStr(String haystack, String needle) {
        		if(needle == null || needle.length() == 0){
			return haystack;
		}
        if(haystack == null || haystack.length() == 0){
			return null;
		}

		for (int i = 0; i < haystack.length(); i++) {
				for(int j = 0;j<needle.length();j++){
					if(i + j >= haystack.length()) return null;
					if(haystack.charAt(i+j) == needle.charAt(j)){
						if(j == needle.length() -1)
							return haystack.substring(i);
						else
							continue;
					}else{
						break;
					}
				}
				
		}
		return null;
        
    }


通过这个样例。我认为写代码时候着急不得,把变量的适用条件都考虑清楚了,前后关系都要想清楚了


原文地址:https://www.cnblogs.com/zhchoutai/p/7295196.html