编写高质量代码改善java程序的151个建议——[1-3]基础?亦是基础

简介:

    The reasonable man adapts himself to the world;the unreasonable one persists in trying to adapt the world to himself. —萧伯纳

    相信自己看得懂就看得懂了,相信自己能写下去,我就开始写了.其实也简单—泥沙砖瓦浆木匠

 

Written In The Font

Today , I am writing my java notes about <编写高质量代码改善java程序的151个建议> -秦小波.

Three pieces[1-3]:

         1.Don't code by confusing letters in the constants and variables  [不要在常量和变量中出现易混淆的字母]

         2.Don't change the constants into the variable.                           [莫让常量蜕变成变量]

         3.Make the the types of ternary operators the same.                 [三元操作符的类型务必一致]

 

Don't code by confusing letters in the constants and variables

from the book:

public class Client01 {
    public static void main(String [] args)
    {
        long i = 1l;
        System.out.println("i的两倍是:"+(i+i));
    }
}

Outputs:

1
2   

(unbelieved?just ctrl c + ctrl v run the code !)

 

In my words:

    ‘1l’is not ‘11’. But we always code by the confusing things . then bebug for a long time , finally we will laught at ourselves with the computer and codes face to face.”What fucking are the coder?”lol,smile ! carm down , because u r so lucky to read this . i will tell some excemples to keep them away. away ? really away? 

 

Step 1: somthing about Coding Standards


     Constants should always be all-uppercase, with underscores to separatewords. [常量都要大写,用下划线分开]

   

 See a case from my project ITP:

package sedion.jeffli.wmuitp.constant;

public class AdminWebConstant 
{
    
    public static final String ADMIN_BASE     = "/admin";
    public static final String WEB_BASE       = ADMIN_BASE + "/web";

    /**
     * view
     */
    public static final String ADMIN_LOGIN_VIEW = WEB_BASE   + "/login";
    public static final String ADMIN_INDEX_VIEW = ADMIN_BASE + "/index/index";
    
    /**
     * 返回String状态
     */
    public static final int RESULT_SUCCESS = 1;
    public static final int RESULT_FAIL    = 0;
}

  

   Camel Case:[变量命名驼峰原则,自然你也可以选择其他的法则等]

        if u wanna do it , right now ! it can make your codes more beautiful and clean! amazing ! u learned it , keep on!!!

package sedion.jeffli.wmuitp.util;

import javax.servlet.http.HttpSession;

import sedion.jeffli.wmuitp.entity.TeacherInfo;
import sedion.jeffli.wmuitp.entity.UserLogin;

public class AdminUtil
{
    public static final String ADMIN        = "admin";
    public static final String ADMIN_ID     = "adminID";
    public static final String TEACHER_ID   = "teacherID";
    
    public static void saveAdminToSession(HttpSession session,UserLogin userLogin)
    {
        session.setAttribute(ADMIN, userLogin);
    }
    
    public static void saveAdminIDToSession(HttpSession session,UserLogin userLogin)
    {
        session.setAttribute(ADMIN_ID, userLogin.getUlId().toString());
    }
    public static UserLogin getUserLoginFromHttpSession(HttpSession session)
    {
        Object attribute = session.getAttribute(ADMIN);
        return attribute == null ? null : (UserLogin)attribute;
    }
    
    public static String getUserLoginIDFromHttpSession(HttpSession session)
    {
        Object attribute = session.getAttribute(ADMIN_ID);
        return attribute == null ? null : (String)attribute;
    }
    
}

#please remeber the camel , then u can write a nice code.

                                                  image_thumb1

 

Step 2: somthing can make your program easier to understand


    some letters should not be used with the numbers,like  l O … they are the brother of the numbers.but we can do some to avoid. like use ‘L’ , and write some notes about them.    

                                                 image3_thumb

 

 

Don't change the constants into the variable

A magical demo:

public class Client02
{
    public static void main(String [] args)
    {
        System.out.println("const can change:  "+ Const.RAND_COSNT);
    }

    //接口常量
    interface Const
    {
       public static final int RAND_COSNT = new Random().nextInt();
    }
}

#I think the demo is bad. RAND_COSNT is not a constant and we never do that.

 

what is Constants ?


    Constants are immutable values which are known at compile time and do not change for the life of the program.But if the project is too large to manage.There will be a problem.Let me show u!

                                                   constant_remake_orange_thumb1

example:

//file: A.java
public interface A
{
    String goodNumber = "0.618";
}

//file: B.java
public class B
{
    public static void main(String [] args)
    {
        System.out.println("Class A's goodNumber = " +A.goodNumber);
    }        
}

Outputs:

Class A's goodNumber = 0.618

 

Now we  change A.java –> goodNumber to “0.6180339887”



//file: A.java
public interface A
{
    String goodNumber = "0.6180339887";
}

 

javac A.java”then “java B” , we will find the outputs is the same:

Class A's goodNumber = 0.618

why??????????????????

       just see the class of B, use “ javap –c B”:

Compiled from "B.java"
public class B {
  public B();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       3: ldc           #3                  // String Class A's goodNumber = 0.618
       5: invokevirtual #4                  // Method java/io/PrintStream.printl
n:(Ljava/lang/String;)V
       8: return
}

#3: ldc #3 // String Class A's goodNumber = 0.618

ok , we see! the last interface A was already in the class B. so we can “javac B.java”to deal.

 

All in all ,

           Java Interface is usually the best place to store The Constants.

           [Java Interface 通常是常量存放的最佳地点]

              

A best way store constants : static fianl  XXX    static Object getXXX()


it shows the Java dynamic advantage and a constant principle.

//file:A.java
public class A
{
    private static final String goodNumber = "0.6180339887";
    public static String getGoodNumber()
    {
        return goodNumber;
    }
}

//file:B.java
public class B
{
    public static void main(String [] args)
    {
        System.out.println("Class A's goodNumber = " +A.getGoodNumber());
    }        
}

 
 

Make the the types of ternary operators the same.

from the book:

public class Client03 {
    public static void main(String[] args) {
        int i = 80;
        String s  = String.valueOf(i<100?90:100);
        String s1 = String.valueOf(i<100?90:100.0);
        System.out.println(" 两者是否相等:"+s.equals(s1));
    }
}

 
Outputs:
1
false

  

see the compiled code ,use “javap –c Client03”,we will see:



      23: if_icmpge     32
      26: ldc2_w        #3                  // double 90.0d
      29: goto          35
      32: ldc2_w        #5                  // double 100.0d

 

the transformation rules about ternary operators.


三元操作符类型的转换规则:

        1.若两个操作数不可转换,则不做转换,返回值为Object 类型。

        2.若两个操作数是明确类型的表达式(比如变量),则按照正常的二进制数字来转换,int 类型转换为long 类型,long 类型转换为float 类型等。

        3.若两个操作数中有一个是数字S,另外一个是表达式,且其类型标示为T,那么,若数字S 在T 的范围内,则转换为T 类型;若S 超出了T 类型的范围,则T 转换为S类型(可以参考“建议22”,会对该问题进行展开描述)。

        4.若两个操作数都是直接量数字(Literal) ,则返回值类型为范围较大者。

 

相关文章
|
2月前
|
Java
在 Java 中捕获和处理自定义异常的代码示例
本文提供了一个 Java 代码示例,展示了如何捕获和处理自定义异常。通过创建自定义异常类并使用 try-catch 语句,可以更灵活地处理程序中的错误情况。
80 1
|
2月前
|
Java
在Java中实现接口的具体代码示例
可以根据具体的需求,创建更多的类来实现这个接口,以满足不同形状的计算需求。希望这个示例对你理解在 Java 中如何实现接口有所帮助。
92 38
|
15天前
|
安全 Java 编译器
深入理解Java中synchronized三种使用方式:助您写出线程安全的代码
`synchronized` 是 Java 中的关键字,用于实现线程同步,确保多个线程互斥访问共享资源。它通过内置的监视器锁机制,防止多个线程同时执行被 `synchronized` 修饰的方法或代码块。`synchronized` 可以修饰非静态方法、静态方法和代码块,分别锁定实例对象、类对象或指定的对象。其底层原理基于 JVM 的指令和对象的监视器,JDK 1.6 后引入了偏向锁、轻量级锁等优化措施,提高了性能。
41 3
|
2月前
|
Java
java小工具util系列4:基础工具代码(Msg、PageResult、Response、常量、枚举)
java小工具util系列4:基础工具代码(Msg、PageResult、Response、常量、枚举)
58 24
|
23天前
|
前端开发 Java 测试技术
java日常开发中如何写出优雅的好维护的代码
代码可读性太差,实际是给团队后续开发中埋坑,优化在平时,没有那个团队会说我专门给你一个月来优化之前的代码,所以在日常开发中就要多注意可读性问题,不要写出几天之后自己都看不懂的代码。
57 2
|
1月前
|
Java 编译器 数据库
Java 中的注解(Annotations):代码中的 “元数据” 魔法
Java注解是代码中的“元数据”标签,不直接参与业务逻辑,但在编译或运行时提供重要信息。本文介绍了注解的基础语法、内置注解的应用场景,以及如何自定义注解和结合AOP技术实现方法执行日志记录,展示了注解在提升代码质量、简化开发流程和增强程序功能方面的强大作用。
82 5
|
1月前
|
存储 算法 Java
Java 内存管理与优化:掌控堆与栈,雕琢高效代码
Java内存管理与优化是提升程序性能的关键。掌握堆与栈的运作机制,学习如何有效管理内存资源,雕琢出更加高效的代码,是每个Java开发者必备的技能。
58 5
|
2月前
|
Java API 开发者
Java中的Lambda表达式:简洁代码的利器####
本文探讨了Java中Lambda表达式的概念、用途及其在简化代码和提高开发效率方面的显著作用。通过具体实例,展示了Lambda表达式如何在Java 8及更高版本中替代传统的匿名内部类,使代码更加简洁易读。文章还简要介绍了Lambda表达式的语法和常见用法,帮助开发者更好地理解和应用这一强大的工具。 ####
|
2月前
|
XML 安全 Java
Java反射机制:解锁代码的无限可能
Java 反射(Reflection)是Java 的特征之一,它允许程序在运行时动态地访问和操作类的信息,包括类的属性、方法和构造函数。 反射机制能够使程序具备更大的灵活性和扩展性
51 5
Java反射机制:解锁代码的无限可能
|
2月前
|
Java API Maven
商汤人像如何对接?Java代码如何写?
商汤人像如何对接?Java代码如何写?
51 5