其他分享
首页 > 其他分享> > 第二部分:理论六

第二部分:理论六

作者:互联网

第二部分:理论六

理论六

如何理解“KISS 原则”?

代码行数越少就越“简单”吗?

检查输入的字符串ipAddress 是否是合法的 IP 地址:

// 第一种实现方式: 使用正则表达式
public boolean isValidIpAddressV1(String ipAddress) {
	if (StringUtils.isBlank(ipAddress)) return false;
	String regex = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
		+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
		+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
		+ "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
	return ipAddress.matches(regex);
}
// 第二种实现方式: 使用现成的工具类
public boolean isValidIpAddressV2(String ipAddress) {
	if (StringUtils.isBlank(ipAddress)) return false;
	String[] ipUnits = StringUtils.split(ipAddress, '.');
	if (ipUnits.length != 4) {
		return false;
	}
	for (int i = 0; i < 4; ++i) {
		int ipUnitIntValue;
		try {
			ipUnitIntValue = Integer.parseInt(ipUnits[i]);
		} catch (NumberFormatException e) {
			return false;
		}
		if (ipUnitIntValue < 0 || ipUnitIntValue > 255) {
			return false;
		}
		if (i == 0 && ipUnitIntValue == 0) {
			return false;
		}
	}
	return true;
}
// 第三种实现方式: 不使用任何工具类
public boolean isValidIpAddressV3(String ipAddress) {
	char[] ipChars = ipAddress.toCharArray();
	int length = ipChars.length;
	int ipUnitIntValue = -1;
	boolean isFirstUnit = true;
	int unitsCount = 0;
	for (int i = 0; i < length; ++i) {
		char c = ipChars[i];
		if (c == '.') {
			if (ipUnitIntValue < 0 || ipUnitIntValue > 255) return false;
			if (isFirstUnit && ipUnitIntValue == 0) return false;
			if (isFirstUnit) isFirstUnit = false;
			ipUnitIntValue = -1;
			unitsCount++;
			continue;
		}
		if (c < '0' || c > '9') {
			return false;
		}
		if (ipUnitIntValue == -1) ipUnitIntValue = 0;
		ipUnitIntValue = ipUnitIntValue * 10 + (c - '0');
	}
	if (ipUnitIntValue < 0 || ipUnitIntValue > 255) return false;
	if (unitsCount != 3) return false;
	return true;
}

代码逻辑复杂就违背 KISS 原则吗?

KMP 字符串匹配算法:

// KMP algorithm: a, b 分别是主串和模式串;n, m 分别是主串和模式串的长度。
public static int kmp(char[] a, int n, char[] b, int m) {
	int[] next = getNexts(b, m);
	int j = 0;
	for (int i = 0; i < n; ++i) {
		while (j > 0 && a[i] != b[j]) { // 一直找到 a[i] 和 b[j]
			j = next[j - 1] + 1;
		}
		if (a[i] == b[j]) {
			++j;
		}
		if (j == m) { // 找到匹配模式串的了
			return i - m + 1;
		}
	}
	return -1;
}

// b 表示模式串,m 表示模式串的长度
private static int[] getNexts(char[] b, int m) {
	int[] next = new int[m];
	next[0] = -1;
	int k = -1;
	for (int i = 1; i < m; ++i) {
		while (k != -1 && b[k + 1] != b[i]) {
			k = next[k];
		}
		if (b[k + 1] == b[i]) {
			++k;
		}
		next[i] = k;
	}
	return next;
}

如何写出满足 KISS 原则的代码?

YAGNI 跟 KISS 说的是一回事吗?

标签:代码,return,int,第二,ipUnitIntValue,KISS,false,部分,理论
来源: https://www.cnblogs.com/sleepday/p/15366232.html