论坛首页 Java企业应用论坛

《Clean Code》总结 方法

浏览 1891 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2010-03-14   最后修改:2010-03-14
1.方法要可能的短。最好控制在几行以内。
例如:
public static String renderPageWithSetupsAndTeardowns(
    PageData pageData, boolean isSuite) throws Exception {
    if (isTestPage(pageData))
        includeSetupAndTeardownPages(pageData, isSuite);
    return pageData.getHtml();
}
在if,else,while的语句块中应该已有一个行代码(方法调用)
一个方法类的缩进应该已有一级

2.一个方法只做一件事

3.一个方法内部的代码应该在一个抽象级别。
否则代码阅读者无法区别去要步骤和周边细节。这样,很容易忽略代码的主要步骤。

4.使用具有描述性的方法名词。
不要害怕使用长的方法名,长的具有描述性的方法名比描述性的注释更有用。例如includeSetupAndTeardownPages, includeSetupPages, includeSuiteSetupPage, and includeSetupPage.

5.方法异常处理
5.1.抛出异常比使用错误码更好。
错误码很容易引起多层次的结构
if (deletePage(page) == E_OK) {
    if (registry.deleteReference(page.name) == E_OK) {
        if (configKeys.deleteKey(page.name.makeKey()) == E_OK){
            logger.log("page deleted");
        } else {
            logger.log("configKey not deleted");
        }
    } else {
        logger.log("deleteReference from registry failed");
    }
} else {
    logger.log("delete failed");
    return E_ERROR;
}

使用异常处理,可以同时处理多个错误,结构更简单
try {
    deletePage(page);
    registry.deleteReference(page.name);
    configKeys.deleteKey(page.name.makeKey());
}
catch (SomeOtherException e) {
    logger.log(e.getMessage());
}
catch (Exception e) {
    logger.log(e.getMessage());
}

5.2提取try/catch代码块为单独的方法
try/catch使代码的结构变得复杂,使错误错误处理和正常操作混在了一切。最好把try和catch的block单独放在一个方法中,例如:
public void delete(Page page) {
    try {
    deletePageAndAllReferences(page);
    }
    catch (Exception e) {
        logError(e);
    }
}
private void deletePageAndAllReferences(Page page) throws Exception {
    deletePage(page);
    registry.deleteReference(page.name);
    configKeys.deleteKey(page.name.makeKey());
}
private void logError(Exception e) {
    logger.log(e.getMessage());
}
如果关键字try出现在方法中,应该出现在很靠前的位置,catch/finally后面不应该有其他的代码

6.在一个类中,方法的排列能保证阅读代码从上到下的进行,一个方法后面跟着下一个抽象层次的方法

例子:
package fitnesse.html;

import fitnesse.responders.run.SuiteResponder;
import fitnesse.wiki.*;

public class SetupTeardownIncluder {
	private PageData pageData;
	private boolean isSuite;
	private WikiPage testPage;
	private StringBuffer newPageContent;
	private PageCrawler pageCrawler;

	public static String render(PageData pageData) throws Exception {
		return render(pageData, false);
	}

	public static String render(PageData pageData, boolean isSuite)
			throws Exception {
		return new SetupTeardownIncluder(pageData).render(isSuite);
	}

	private SetupTeardownIncluder(PageData pageData) {
		this.pageData = pageData;
		testPage = pageData.getWikiPage();
		pageCrawler = testPage.getPageCrawler();
		newPageContent = new StringBuffer();
	}

	private String render(boolean isSuite) throws Exception {
		this.isSuite = isSuite;
		if (isTestPage())
			includeSetupAndTeardownPages();
		return pageData.getHtml();
	}

	private boolean isTestPage() throws Exception {
		return pageData.hasAttribute("Test");
	}

	private void includeSetupAndTeardownPages() throws Exception {
		includeSetupPages();
		includePageContent();
		includeTeardownPages();
		updatePageContent();
	}

	private void includeSetupPages() throws Exception {
		if (isSuite)
			includeSuiteSetupPage();
		includeSetupPage();
	}

	private void includeSuiteSetupPage() throws Exception {
		include(SuiteResponder.SUITE_SETUP_NAME, "-setup");
	}

	private void includeSetupPage() throws Exception {
		include("SetUp", "-setup");
	}

	private void includePageContent() throws Exception {
		newPageContent.append(pageData.getContent());
	}

	private void includeTeardownPages() throws Exception {
		includeTeardownPage();
		if (isSuite)
			includeSuiteTeardownPage();
	}

	private void includeTeardownPage() throws Exception {
		include("TearDown", "-teardown");
	}

	private void includeSuiteTeardownPage() throws Exception {
		include(SuiteResponder.SUITE_TEARDOWN_NAME, "-teardown");
	}

	private void updatePageContent() throws Exception {
		pageData.setContent(newPageContent.toString());
	}

	private void include(String pageName, String arg) throws Exception {
		WikiPage inheritedPage = findInheritedPage(pageName);
		if (inheritedPage != null) {
			String pagePathName = getPathNameForPage(inheritedPage);
			buildIncludeDirective(pagePathName, arg);
		}
	}

	private WikiPage findInheritedPage(String pageName) throws Exception {
		return PageCrawlerImpl.getInheritedPage(pageName, testPage);
	}

	private String getPathNameForPage(WikiPage page) throws Exception {
		WikiPagePath pagePath = pageCrawler.getFullPath(page);
		return PathParser.render(pagePath);
	}

	private void buildIncludeDirective(String pagePathName, String arg) {
		newPageContent.append("\n!include ").append(arg).append(" .").append(
				pagePathName).append("\n");
	}
}


论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics