Effective Java 45 Minimize the scope of local variables
2014-04-08 19:45 小郝(Kaibo Hao) 阅读(438) 评论(0) 编辑 收藏 举报Principle
- The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used.
-
Nearly every local variable declaration should contain an initializer.
Note
If a variable is initialized by a method that throws a checked exception, it must be initialized inside a try block. If the value must be used outside of the try block, then it must be declared before the try block.
-
prefer for loops to while loops
Advantage
- The loops are completely independent, so there's no harm in reusing the element (or iterator) variable name.
-
It's much less likely that you'll make the cut-and-paste error, as there's no incentive to use different variable names in the two loops.
// Preferred idiom for iterating over a collection
for (Element e : c) {
doSomething(e);
}
// No for-each loop or generics before release 1.5
for (Iterator i = c.iterator(); i.hasNext(); ) {
doSomething((Element) i.next());
}
Use this idiom below if the loop test involves a method invocation that is guaranteed to return the same result on each iteration.
for (int i = 0, n = expensiveComputation(); i < n; i++) {
doSomething(i);
}
It has two loop variables, i and n, both of which have exactly the right scope. The second variable, n, is used
to store the limit of the first, thus avoiding the cost of a redundant computation on every iteration.
-
Keep methods small and focused .
If you combine two activities in the same method, local variables relevant to one activity may be in the scope of the code performing the other activity. To prevent this from happening, simply separate the method into two: one
for each activity.
Summary
By minimizing the scope of local variables, you increase the read-ability and maintainability of your code and reduce the likelihood of error.
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ThreeJs-16智慧城市项目(重磅以及未来发展ai)
· .NET 原生驾驭 AI 新基建实战系列(一):向量数据库的应用与畅想
· Browser-use 详细介绍&使用文档
· 软件产品开发中常见的10个问题及处理方法
· Vite CVE-2025-30208 安全漏洞