Java 代码规范
程序代码:
Java 代码规范
一:缩进
代码1:不良的风格
public class Welcome
{
public static void main(String[] args)
{
String[] greeting = new String[3];
greeting[0] = "Welcome to Core Java";
greeting[1] = "by Cay Horstmann";
greeting[2] = "and Gary Cornell";
for (String g : greeting)
System.out.println(g);
}
}
代码2:良好的风格
public class Welcome
{
public static void main(String[] args)
{
String[] greeting = new String[3];
greeting[0] = "Welcome to Core Java";
greeting[1] = "by Cay Horstmann";
greeting[2] = "and Gary Cornell";
for (String g : greeting)
System.out.println(g);
}
}
评: 代码1结构混乱,代码2结构清析
二:空格
代码1:不良的风格
public class Retirement
{
public static void main(String[] args)
{
// read inputs
Scanner in=new Scanner(System.in);
System.out.print("How much money do you need to retire? ");
double goal=in.nextDouble();
System.out.print("How much money will you contribute every year? ");
double payment = in.nextDouble();
System.out.print("Interest rate in %: ");
double interestRate=in.nextDouble();
double balance=0;
int years=0;
// update account balance while goal isn't reached
while (balance<goal)
{
// add this year's payment and interest
balance+=payment;
double interes=balance*interestRate/100;
balance+=interest;
years++;
}
System.out.println("You can retire in " + years + " years.");
}
}
代码2:良好的风格
public class Retirement
{
public static void main(String[] args)
{
// read inputs
Scanner in = new Scanner(System.in);
System.out.print("How much money do you need to retire? ");
double goal = in.nextDouble();
System.out.print("How much money will you contribute every year? ");
double payment = in.nextDouble();
System.out.print("Interest rate in %: ");
double interestRate = in.nextDouble();
double balance = 0;
int years = 0;
// update account balance while goal isn't reached
while (balance < goal)
{
// add this year's payment and interest
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
years++;
}
System.out.println("You can retire in " + years + " years.");
}
}
评:代码1运算符前后没有打上空格,代码挤压,不美观
三:语句
代码1:不良的风格
import java.util.*;
/**
* This program demonstrates a <code>do/while</code> loop.
* @version 1.20 2004-02-10
* @author Cay Horstmann
*/
public class Retirement2
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How much money will you contribute every year? ");
double payment = in.nextDouble();
System.out.print("Interest rate in %: ");
double interestRate = in.nextDouble();double balance = 0;int year = 0;
String input;
// update account balance while user isn't ready to retire
do
{
// add this year's payment and interest
balance += payment;double interest = balance * interestRate / 100;balance += interest;
year++;
// print current balance
System.out.printf("After year %d, your balance is %,.2f%n", year, balance);
// ask if ready to retire and get input
System.out.print("Ready to retire? (Y/N) ");
input = in.next();
}
while (input.equals("N"));
}
}
代码2:良好的风格
import java.util.*;
/**
* This program demonstrates a <code>do/while</code> loop.
* @version 1.20 2004-02-10
* @author Cay Horstmann
*/
public class Retirement2
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How much money will you contribute every year? ");
double payment = in.nextDouble();
System.out.print("Interest rate in %: ");
double interestRate = in.nextDouble();
double balance = 0;
int year = 0;
String input;
// update account balance while user isn't ready to retire
do
{
// add this year's payment and interest
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
year++;
// print current balance
System.out.printf("After year %d, your balance is %,.2f%n", year, balance);
// ask if ready to retire and get input
System.out.print("Ready to retire? (Y/N) ");
input = in.next();
}
while (input.equals("N"));
}
}
评:应该遵循一条语句一行代码,代码2显然要比代码1清析美观
四:自增运算符
代码1:不良的风格
public class Hello
{
public static void main(String[] args)
{
int i, j;
j = i++ + i++ + i++;
}
}
评:不要在一对顺序点之间改变同一个变量两次,会给人迷惑的感觉,并且还会带来烦人的bug
五:循环计数器
代码1:不良的风格
public class LotteryArray
{
public static void main(String[] args)
{
final int NMAX = 10;
int i, j, k;
// allocate triangular array
int[][] odds = new int[NMAX + 1][];
for ( i = 0; i <= NMAX; i++)
odds[i] = new int[i + 1];
// fill triangular array
for ( i = 0; i < odds.length; i++)
for ( j = 0; j < odds[i].length; j++)
{
/*
* compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
*/
int lotteryOdds = 1;
for ( i = 1; i <= j; i++)
lotteryOdds = lotteryOdds * (n - i + 1) / i;
odds[i][j] = lotteryOdds;
}
// print triangular array
for (int[] row : odds)
{
for (int odd : row)
System.out.printf("%4d", odd);
System.out.println();
}
}
}
代码2:良好的风格
/**
* This program demonstrates a triangular array.
* @version 1.20 2004-02-10
* @author Cay Horstmann
*/
public class LotteryArray
{
public static void main(String[] args)
{
final int NMAX = 10;
// allocate triangular array
int[][] odds = new int[NMAX + 1][];
for (int n = 0; n <= NMAX; n++)
odds[n] = new int[n + 1];
// fill triangular array
for (int n = 0; n < odds.length; n++)
for (int k = 0; k < odds[n].length; k++)
{
/*
* compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
*/
int lotteryOdds = 1;
for (int i = 1; i <= k; i++)
lotteryOdds = lotteryOdds * (n - i + 1) / i;
odds[n][k] = lotteryOdds;
}
// print triangular array
for (int[] row : odds)
{
for (int odd : row)
System.out.printf("%4d", odd);
System.out.println();
}
}
}
评:代码1中定义了 3个临时变量 i, j, k。却只用了 i, j.
多出来的 k 难免让人有点模不着头脑的感觉
六:变量命名
代码1:不良的风格
class Employee
{
public Employee(String n, double s, int year, int month, int day)
{
n = n;
s = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
// GregorianCalendar uses 0 for January
d = calendar.getTime();
}
public String getN()
{
return n;
}
public double getS()
{
return s;
}
public Date getD()
{
return d;
}
public void raiseS(double byPercent)
{
double raise = s * byPercent / 100;
s += raise;
}
private String n;
private double s;
private Date d;
}
代码2:良好的风格
class Employee
{
public Employee(String n, double s, int year, int month, int day)
{
name = n;
salary = s;
GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
// GregorianCalendar uses 0 for January
hireDay = calendar.getTime();
}
public String getName()
{
return name;
}
public double getSalary()
{
return salary;
}
public Date getHireDay()
{
return hireDay;
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
private String name;
private double salary;
private Date hireDay;
}
评:变量命名应该简短,富于描述。能让人见名知义
七:常量命名
代码1:不良的风格
public class CompoundInterest
{
public static void main(String[] args)
{
final double Startrate = 10;
final int Nrates = 6;
final int Nyears = 10;
// set interest rates to 10 . . . 15%
double[] interestRate = new double[Nrates];
for (int j = 0; j < interestRate.length; j++)
interestRate[j] = (Startrate + j) / 100.0;
double[][] balances = new double[Nyears][Nrates];
// set initial balances to 10000
for (int j = 0; j < balances[0].length; j++)
balances[0][j] = 10000;
// compute interest for future years
for (int i = 1; i < balances.length; i++)
{
for (int j = 0; j < balances[i].length; j++)
{
// get last year's balances from previous row
double oldBalance = balances[i - 1][j];
// compute interest
double interest = oldBalance * interestRate[j];
// compute this year's balances
balances[i][j] = oldBalance + interest;
}
}
// print one row of interest rates
for (int j = 0; j < interestRate.length; j++)
System.out.printf("%9.0f%%", 100 * interestRate[j]);
System.out.println();
// print balance table
for (double[] row : balances)
{
// print table row
for (double b : row)
System.out.printf("%10.2f", b);
System.out.println();
}
}
}
代码2:良好的风格
public class CompoundInterest
{
public static void main(String[] args)
{
final double STARTRATE = 10;
final int NRATES = 6;
final int NYEARS = 10;
// set interest rates to 10 . . . 15%
double[] interestRate = new double[NRATES];
for (int j = 0; j < interestRate.length; j++)
interestRate[j] = (STARTRATE + j) / 100.0;
double[][] balances = new double[NYEARS][NRATES];
// set initial balances to 10000
for (int j = 0; j < balances[0].length; j++)
balances[0][j] = 10000;
// compute interest for future years
for (int i = 1; i < balances.length; i++)
{
for (int j = 0; j < balances[i].length; j++)
{
// get last year's balances from previous row
double oldBalance = balances[i - 1][j];
// compute interest
double interest = oldBalance * interestRate[j];
// compute this year's balances
balances[i][j] = oldBalance + interest;
}
}
// print one row of interest rates
for (int j = 0; j < interestRate.length; j++)
System.out.printf("%9.0f%%", 100 * interestRate[j]);
System.out.println();
// print balance table
for (double[] row : balances)
{
// print table row
for (double b : row)
System.out.printf("%10.2f", b);
System.out.println();
}
}
}
评:常量名应该全部大写,不然给人感觉很怪异
八:case 标签
代码1:不良的风格
switch(key)
{
case 1:
direction = key;
break;
case 2:
direction = key;
break;
case 3:
direction = key;
break;
case 4:
: direction = key;
break;
}
代码2:良好的风格
switch(key)
{
case LEFT:
direction = key;
break;
case RIGHT:
direction = key;
break;
case UP:
direction = key;
break;
case DOWN:
: direction = key;
break;
}
评:代码中尽量不要出现数字,否则不去阅读代码根本不知道这个数字代表的意思。
最好用符号常量代替。
九:多重选择
代码1:不良的风格
if (key == LEFT)
direction = key;
else if (key == RIGHT)
direction = key;
else if (key == UP )
direction = key;
else if (key == DOWN)
direction = key;
代码2:良好的风格
switch(key)
{
case LEFT:
direction = key;
break;
case RIGHT:
direction = key;
break;
case UP:
direction = key;
break;
case DOWN:
: direction = key;
break;
}
评:多于3个以上的分支结构最好不要使用 if/else, 晦涩难懂,尽量 使用 switch/case代替
十:中断流程
代码1:不良的风格
for( i = 0; aResult[i]==0 && i<resultPointPos; i++ ) ;
代码2:良好的风格
for( i = 0; aResult[i]==0 && i<resultPointPos; i++ )
continue;
评:循环结构中的 空语句尽量不用使用 ;,用continue 代替,代码易读,而且不易出错。
[ 本帖最后由 BlueGuy 于 2010-8-11 22:09 编辑 ]



先试试效果, 有空再续,


很有用,谢谢!