20个Java的最佳实践(一)

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; // redundant


String 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 heap


String 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 empty


String 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 readable

long 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 block



try (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 feedback


try 
{ 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的用法

结束

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值