20 java best practices

概述

文章皆来源于国外论坛网站Medium
单词解析来源于有道词典

文章来源: Medium

原文

20 java best practices

Some of java best practices that will help you enhance your code’s quality.

1-Favor primitives over primitive wrappers whenever possible.

Long idNumber;
long idNumber; // long takes less memory than Long

2-To check for oddity of a number the bitwise AND operator is much faster than the arithmetic modulo operator.

public boolean isOdd(int num) {
return (num & 1) != 0;
}
// best way to check the oddity of a number

3-Avoid redundant initialization (0, false, null…)
Do not initialize variables with their default initialization, for example, a boolean by default has the value false so it is redundant to initialize it with the false value.

String name = null; // redundant
int speed = 0; // redundant
boolean isOpen = false; // redundantString name;
int speed;
boolean isOpen;
// same values in a cleaner way

4-Declare class members private wherever possible and always give the most restricted access modifier.

public int age; // very bad
int age; // bad
private int age; // good

5-Avoid the use of the ‘new’ keyword while creating String

String s1 = new String("AnyString") ;
// low instantiation
// The constructor creates a new object, and adds the literal to the heapString s2 = "AnyString" ; // better
// fast instantiation
// This shortcut refers to the item in the String pool
// and creates a new object only if the literal is not in the String pool.

6-Use the concat method when concatenating possibly-empty Strings, and use + otherwise (since java 8).

NB: Before java 8, StringBuilder andStringBuffer were the best way for concatenating strings.

String address = streetNumber.concat(" ").concat(streetName)
.concat(" ").concat(cityName).concat(" ").concat(cityNumber)
.concat(" ").concat(countryName);
// streetNumber, streetName, cityName, cityNumber
// and countryName are user inputs and can be emptyString str1 = "a";
String str2 = "b";
String str3 = "c";
String concat = str1 + str2 + str3;

NB: Before java 8, StringBuilder andStringBuffer were the best way for concatenating strings.

7-Using underscores in Numeric Literals.

int myMoneyInBank = 58356823;
int myMoneyInBank = 58_356_823; // more readablelong billsToPay = 1000000000L;
long billsToPay = 1_000_000_000L; // more readable

8-Avoid using ‘for loops’ with indexes.
Do not use a for loop with an index (or counter) variable if you can replace it with the enhanced for loop (since Java 5) or forEach (since Java 8). It’s because the index variable is error-prone, as we may alter it incidentally in the loop’s body, or we may start the index from 1 instead of 0.

for (int i = 0; i < names.length; i++)
{ saveInDb(names[i]); }for (String name : names)
{ saveInDb(name); } // cleaner

9-Replace try–catch-finally with try-with-resources.

Scanner scanner = null;
try
{scanner = new Scanner(new File("test.txt"));
while (scanner.hasNext())
{System.out.println(scanner.nextLine());}}
catch (FileNotFoundException e)
{e.printStackTrace();}
finally
{if (scanner != null)
{scanner.close();}}
// error-prone as we can forget to close the scanner in the finally blocktry (Scanner scanner = new Scanner(new File("test.txt")))
{while (scanner.hasNext())
{System.out.println(scanner.nextLine());}}
catch (FileNotFoundException e)
{e.printStackTrace();}
// cleaner and more succinct

10-No vacant catch blocks
An empty catch block will make the program fail in silence and will not give any information about what went wrong.

try
{ productPrice = Integer.parseInt(integer); }
catch (NumberFormatException ex)
{ }
// fail silently without giving any feedbacktry
{ productPrice = Integer.parseInt(integer); }
catch (NumberFormatException ex)
{unreadablePrices.add(productPrice); // handle error
log.error("Cannot read price : ", productPrice );// proper and meaningful message
}

译文

20个Java的最佳实践

一些可以帮助您提高代码质量的java最佳实践。

1-尽可能的使用原语(基本数据类型)而不是原语包装器(包装类型)

Long idNumber;
long idNumber; // long 类型比Long类型占用的内存少

2-为了检查一个数字的奇数,位数与运算符比算术模数运算符快得多

public boolean isOdd(int num) {
return (num & 1) != 0;
}
// 检查一个数字的奇数的最佳方法

3-避免多余的初始化(0, false, null…)
不要用默认的初始化变量,例如,一个布尔值默认为false,所以用false值初始化它是多余的。

String name = null; // 冗余的
int speed = 0; // 冗余的
boolean isOpen = false; // 冗余的String name;
int speed;
boolean isOpen;
// 同样的值,用一种更简洁的方式

4-尽可能地声明类成员为私有,并始终给予最有限的访问修饰语

public int age; // 非常不好
int age; // 不好的
private int age; // 很好的

5-在创建字符串时避免使用’new’关键字

String s1 = new String("AnyString") ;
// 低效的实例化
// 构造函数创建一个新的对象,并将字面意思添加到堆中String s2 = "AnyString" ; // better
// 高效的实例化
// 这个快捷方式指的是字符串池中的项目,并仅在字面意思不在字符串池中时才创建一个新对象。

6-当连接可能为空的字符串时,使用concat方法,否则使用+(自java 8起)

String address = streetNumber.concat(" ").concat(streetName)
.concat(" ").concat(cityName).concat(" ").concat(cityNumber)
.concat(" ").concat(countryName);
// streetNumber, streetName, cityName, cityNumber
// and countryName 是用户输入的,且可以为空String str1 = "a";
String str2 = "b";
String str3 = "c";
String concat = str1 + str2 + str3;

在java8之前,对于字符串拼接StringBuilderStringBuffer是最好的方式

7-在数字文字中使用下划线

int myMoneyInBank = 58356823;
int myMoneyInBank = 58_356_823; // 更好的可读性long billsToPay = 1000000000L;
long billsToPay = 1_000_000_000L; // 更好的可读性

8-避免使用带有下标的’for 循环’

如果你可以用增强的for循环(从Java 5开始)或forEach(从Java 8开始)来代替它,就不要使用带有下标(或计数器)变量的for循环。这是因为下标变量很容易出错,因为我们可能会在循环的主体中偶然改变它,或者我们可能会从1而不是0开始下标。

for (int i = 0; i < names.length; i++)
{ saveInDb(names[i]); }for (String name : names)
{ saveInDb(name); } // 更清晰的

9-将try-catch-finally替换为try-with-resources。

Scanner scanner = null;
try
{scanner = new Scanner(new File("test.txt"));
while (scanner.hasNext())
{System.out.println(scanner.nextLine());}}
catch (FileNotFoundException e)
{e.printStackTrace();}
finally
{if (scanner != null)
{scanner.close();}}
// 容易出错,因为我们可能忘记在Final块中关闭扫描仪。try (Scanner scanner = new Scanner(new File("test.txt")))
{while (scanner.hasNext())
{System.out.println(scanner.nextLine());}}
catch (FileNotFoundException e)
{e.printStackTrace();}
// 更加清晰和简洁

10-catch块不能为空
一个空的catch块会使程序无声无息地失败,不会给出任何关于出错的信息。

try
{ productPrice = Integer.parseInt(integer); }
catch (NumberFormatException ex)
{ }
// 默默无闻地失败,不给予任何反馈try
{ productPrice = Integer.parseInt(integer); }
catch (NumberFormatException ex)
{unreadablePrices.add(productPrice); // 处理错误
log.error("Cannot read price : ", productPrice );//正确和有意义的信息
}

生词

  1. practices

    practice 的复数形式

    n: 实践,实践操作,做法,惯例,练习

    v: 练习,经常做,养成…的习惯,从业,执业

  2. enhance

    v: 增强,提高,改善

  3. quality

    n: 质量,品质,优质,素质,品德

    adj: 优质的,高质量的

  4. primitives

    primitive 的复数形式

    n: 原语[计算机],基元[计算机]

    adj: 远古的,原始的,粗糙的,简陋的,早期的

  5. wrappers

    wrapper的复数形式

    n: 包装纸,包装材料,封装器

  6. possible

    adj: 可能的,可能做到的,可能发生的,可能存在的

    n: 可能适合的人(事物)

  7. oddity

    n: 古怪反常的人(或事物),怪现象;怪异,反常,怪癖

  8. bitwise

    adj: (计算机)逐位,按位

  9. arithmetic

    n: 算术;演算,计算;数据统计

    adj: 算术的

  10. modulo

    prep: 以…为模

    adj: 按模的

  11. avoid

    v: 避免,防止,回避,避开,撤销,使无效

  12. redundant

    adj: 多余的,累赘的,备用的

  13. initialization

    n: [计算机]初始化;赋初值

  14. variables

    n: [数学]变量

  15. declare

    v: 宣布,声明,断言,宣称,申报,放弃击球

  16. restricted

    adj: 有限的,很小的,受制约的,受控制的

    v: 限制,限定,约束,限制

  17. modifier

    n: 修饰语,修饰成分,更改者

  18. instantiation

    n: [计算机]实例化

  19. constructor

    n: [计算机]构造函数,构造器

  20. literal

    adj: 字面上的,逐字的,缺乏想象力的,刻板的

  21. shortcut

    n: 近路,捷径,快捷方法

    v: 抄近道

  22. refer

    v: 提到,谈及(refer to),描述

  23. concatenating

    concatenate 的ing形式

    v: 把…连在一起,连接

    adj: [植物]连接的

  24. otherwise

    adv: 否则,不然,除此以外,在其他方面,不同地

    adj: 不是那样的,另外情况下

  25. underscore

    v: 强调;在…的下面划线

    n: 下划线

  26. numeric

    adj: 数值的,数字的

    n: 数;数字

  27. readable

    adj: 可读的,易读的

  28. loop

    n: 环形,环状物,循环磁带

    v: 使成环,使绕成圈,成环形运动

  29. counter

    n: 柜面,对立面,计数器,计算器

    v: 反驳,驳斥,抵制,抵消,(拳击)还击

    adv: 相反地,对立地,逆向地

    adj: 反面的,对立的

  30. prone

    adj: 有做…倾向的,易于…的,俯卧的,趴着的

    v: 使俯卧,趴着

  31. error-prone

    adj: 易于出错的

  32. alter

    v: 改变,被动,(使)变化

  33. incidentally

    adv: 偶然地,附带地,伴随地,顺便说一句

  34. instead

    adv: 代替,顶替,反而

  35. succinct

    adj: 言简意赅的,简练的

  36. vacant

    adj: (地方)空着的,无人用的,空缺的

  37. silence

    n: 寂静,无声,沉默,默不作声,保持沉默

    v: 使安静,使不说话,压制,使不再发表

  38. feedback

    n: 反馈意见,(信号返回电子音响系统所致的)噪声

  39. handle

    v: 拿,处理,应付,操纵,经营,管理

    n: 把手,拉手,柄,提手

  40. proper

    adj: 真正的,像样的,实际上的,合适的,合理的,合乎体统的

    adv: 完全地,彻底地,正确地,恰当地

    n: 特定季节(或节日)的礼仪

  41. meaningful

    adj: 有意义的,重要的,意味深长的,意在言外的,浅显易懂的

句子解析

  1. Some of java best practices that will help you enhance your code’s quality.
  • some of java best practices 名词性短语
  • will help you enhance your code’s quality 从句
  • will help 一般将来时
  • 修饰名词的成分在英语句子中称之为定语,所以后面的句子为定语从句
  1. Favor primitives over primitive wrappers whenever possible.
  • favor + 名词1 + over + 名词2 表示尽可能的使用1,而不是使用2
  • whenever possible 短语,表示无论什么时候可能的

所以上面的句子我们可以翻译为: 在可能的情况下,尽量使用基本数据类型,而不是包装类型

  1. long takes less memory than Long
  • less是little 的比较级,意思为较少的,较低的

所以句子翻译为: long获取的内存比Long少

  1. To check for oddity of a number the bitwise AND operator is much faster than the arithmetic modulo operator.
  • to check 动词不定式
  • faster fast的比较级,前面的much是加强比较的作用
  1. Do not initialize variables with their default initialization, for example, a boolean by default has the value false so it is redundant to initialize it with the false value.
  • Do not 是否定形式的谓语动词短语,表示不要做某事
  • initialize variables 初始化变量,initialize 是一个动词
  • for example 短语:例如; 用以说明或支持前面所述的观点或论点,后面引入一个或多个例子
  • by default by在这里表示通过,以…方式,与default组成介词短语,表示:在默认的情况下
  1. Avoid the use of the ‘new’ keyword while creating String
  • the use of 介词短语,表示利用,使用,后面接名词,代词,动名词,名词性从句
    the use of的用法

结束

以上文章原文皆来源于国外,为了学习英语所以进行翻译解读学习,若有错误,欢迎各位大佬指出。

20个Java的最佳实践(一)相关推荐

  1. IBM WebSphere 开发者技术期刊: 最重要的 Java EE 最佳实践

    级别: 初级 Keys Botzum, 高级技术人员 , IBM Kyle Brown, 杰出工程师, IBM Ruth Willenborg (rewillen@us.ibm.com), 高级技术人 ...

  2. java微妙_10个微妙的Java编码最佳实践

    编写和维护jOOQ(Java中内部DSL建模的SQL)时遇到过这些.作为一个内部DSL,jOOQ最大限度的挑战了Java的编译器和泛型,把泛型,可变参数和重载结合在一起,Josh Bloch可能不会推 ...

  3. java 异常 最佳实践_处理Java异常的10种最佳实践

    java 异常 最佳实践 在本文中,我们将看到处理Java异常的最佳实践. 用Java处理异常不是一件容易的事,因为新手很难理解,甚至专业的开发人员也可能浪费时间讨论应该抛出或处理哪些Java异常. ...

  4. 20个数据库设计最佳实践

    2019独角兽企业重金招聘Python工程师标准>>> 数据库设计是整个程序的重点之一,为了支持相关程序运行,最佳的数据库设计往往不可能一蹴而就,只能反复探寻并逐步求精,这是一个复杂 ...

  5. Java ConcurrentHashMap 最佳实践

    2019独角兽企业重金招聘Python工程师标准>>> Java ConcurrentHashMap 最佳实践 博客分类: java 相对于HashMap,ConcurrentHas ...

  6. 10个精妙的Java编码最佳实践

    这是一个比Josh Bloch的Effective Java规则更精妙的10条Java编码实践的列表.和Josh Bloch的列表容易学习并且关注日常情况相比,这个列表将包含涉及API/SPI设计中不 ...

  7. java 异常 最佳实践_关于JAVA异常处理的20个最佳实践

    在我们深入了解异常处理最佳实践的深层概念之前,让我们从一个最重要的概念开始,那就是理解在JAVA中有三种一般类型的可抛类: 检查性异常(checked exceptions).非检查性异常(unche ...

  8. Java 设计模式最佳实践:一、从面向对象到函数式编程

    原文:Design Patterns and Best Practices in Java 协议:CC BY-NC-SA 4.0 贡献者:飞龙 本文来自[ApacheCN Java 译文集],采用译后 ...

  9. Java 设计模式最佳实践:1~5

    原文:Design Patterns and Best Practices in Java 协议:CC BY-NC-SA 4.0 译者:飞龙 本文来自[ApacheCN Java 译文集],采用译后编 ...

  10. Java 的最佳实践

    Java 是在世界各地最流行的编程语言之一, 但是看起来没人喜欢使用它.而 Java 事实上还算是一门不错的语言,随着 Java 8 最近的问世,我决定编制一个库,实践和工具的清单,汇集 Java 的 ...

最新文章

  1. 背包思想计算方案的总数(货币系统)
  2. 【浙大出品】基于扩展FPN的小目标检测方法
  3. docker入门与实践之【04-使用dockerfile定制镜像】
  4. 后端工程师面试BAT,被问到了前端?就倒下了?【VUE面试20连问】
  5. iNeuOS工业互联平台,发布消息管理、子用户权限管理、元件移动事件、联动控制、油表饼状图和建筑类设备驱动,v3.4版本...
  6. 每日一题:leetcode90.子集贰
  7. thymeleaf随机数_SpringBoot2.0实现静态资源版本控制
  8. linux 卸载 usbmouse,8 Linux usbmouse设备驱动程序
  9. (day 48 - 双端队列的使用 ) 剑指 Offer 59 - II. 队列的最大值
  10. Beego 框架学习(一)
  11. codesmith mysql 注释_完美解决CodeSmith无法获取MySQL表及列Description说明注释的方案...
  12. 计算机设备替换法,同义词替换表的挖掘方法及装置、电子设备、计算机可读介质与流程...
  13. 那些精贵的文献资源下载网址经验总结
  14. 云计算时代,你需要了解的OpenStack云操作系统
  15. Guava 操作 集合
  16. 怎么计算机械连接的工程量,传力杆套筒工程量怎么算
  17. 速卖通商品详情API接口(商品详情页面数据接口)
  18. 艺赛旗RPA8.0-用户体验提升抢先看(一)
  19. 编程语言都代表哪些国家?
  20. Win11 pr 加速器渲染错误的解决日志

热门文章

  1. 使用Istio服务网格管理微服务
  2. 初入职场小白——CI/CD区分
  3. Java 全功能开源办公软件 | O2OA V4.1540 发布
  4. 制作图片展示效果(JavaScript)
  5. 11月12日至11月18日 区块链投融资事件回顾
  6. V-REP 线条追踪泡泡机器人教程
  7. C++ Primer学习笔记(二)
  8. 分享3款好用的电脑屏幕监控软件!
  9. springboot测试类启动无反应的问题
  10. OA系统选型,构建自己的价值判断标准