Java 较小的方法
按照Bob Martin叔叔在“Clean Code”中给出的指导原则,我试图使我的方法更小 他给出的一个建议是,包含trys的方法应该调用不涉及异常情况的其他方法 我的问题是命名 通常,当我的方法只包含try表达式时,剩下的就不多了,方法的名称完美地描述了它所做的事情,除了异常 您使用什么约定来命名异常方法将调用的“非异常”方法 举个例子,这是我正在研究的一种方法:Java 较小的方法,java,refactoring,methods,coding-style,Java,Refactoring,Methods,Coding Style,按照Bob Martin叔叔在“Clean Code”中给出的指导原则,我试图使我的方法更小 他给出的一个建议是,包含trys的方法应该调用不涉及异常情况的其他方法 我的问题是命名 通常,当我的方法只包含try表达式时,剩下的就不多了,方法的名称完美地描述了它所做的事情,除了异常 您使用什么约定来命名异常方法将调用的“非异常”方法 举个例子,这是我正在研究的一种方法: private void generateAndAttachDocumentFromTemplate(File template
private void generateAndAttachDocumentFromTemplate(File templateFile) {
try {
File generatedDocument = generateDocumentFromTemplate(templateFile);
if (generatedDocument != null) {
attachDocument(generatedDocument, container);
attachmentsPanel.reload();
SystemControl.openDocument(generatedDocument);
}
} catch (Exception ex) {
Notifier.notifyIT(App.user().getEmail(), ex);
Dialogs.complain("Can\'t Generate Document");
}
}
您可以使用“Impl”约定
private void generateAndAttachDocumentFromTemplate(File templateFile) {
try {
generateAndAttachDocumentFromTemplateImpl(File templateFile);
} catch (Exception ex) {
Notifier.notifyIT(App.user().getEmail(), ex);
Dialogs.complain("Can\'t Generate Document");
}
一些备选方案:
方法
doMethod
method
method0
“非例外”方法应该是
private
我使用约定(我想他在书中建议了这一约定),其中有methodName和tryMethodName。任何时候一个方法都有dothis和dothat()这是一个糟糕的方法。
方法应该做一件事,而且只能做一件事。不管它们有多小。我只会调用方法“doGenerateAndAttachDocumentFromTemplate”。“Impl”通常意味着“接口的实现”。非常好。虽然在我的应用程序中,我没有遵循那个特定的约定,所以它是有效的。事实上,我更喜欢“做”约定。“Impl”约定已经有了明确的含义,这是一个很好的观点。我首先担心分层、“单响应性”和可变静态。我也担心这一点。这是一个遗留系统,我正在一块一块地重构。你可以在MS.NET中找到这种方法,即Parse vs TryParseMust没有找到它。我喜欢这个。谢谢。那么,捕获异常的方法会被称为“try\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu。我使用methodName来调用tryMethodName,因为我认为这样读起来更好。因此tryMethodName包含导致异常的代码,而方法名处理异常