编写高质量代码改善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.

                                                 

 

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.    

                                                

 

 

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!

                                                  

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) ,则返回值类型为范围较大者。

 

时间: 2024-08-03 09:05:10

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

编写高质量代码改善java程序的151个建议——导航开篇

会抓紧java的进阶学习.听过一句话,大哥说过,你一个月前的代码去看下,惨不忍睹是吧.确实,人和代码一样都在成长,都在变好当中.有时候只是实现功能的编程,长进不了呀. 博客提供的好处就可以交流,讨论的学习方法你们应该知道.   在这里,我会陆陆续续的进行对<编写高质量代码改善java程序的151个建议>看法,希望大家点击交流. 正文 看这本书原因  1.项目做的只是实现功能,然而没有好好研究代码之美. 虽然在源码中看到别人代码的美丽,真的获益匪浅.但没有基础,就达不到那种水准.下面是来自我怪兽

编写高质量代码改善java程序的151个建议——[110-117]异常及Web项目中异常处理

何为异常处理? 异常处理,英文名为exceptional handling, 是代替日渐衰落的error code方法的新法,提供error code 所未能具体的优势.异常处理分离了接收和处理错误代码.这个功能理清了编程者的思绪,也帮助代码增强了可读性,方便了维护者的阅读和理解. java语言中,异常处理可以确保程序的健壮性,提高系统的可用率.但是java api 提供的异常都是比较低级的,所以有了'提倡异常封装'                                        

编写高质量代码改善java程序的151个建议——[52-57]String !about String How to use them?

Suggestion:Use the String direct value for the assignment Do u knw the String Object ? If u do some projects,u can see the String is used usually. A object is created by the key word : new.Therefore , we can create a String Obejct by :"  String str3

编写高质量代码改善C#程序的157个建议[1-3]

原文:编写高质量代码改善C#程序的157个建议[1-3] 前言 本文主要来学习记录前三个建议. 建议1.正确操作字符串 建议2.使用默认转型方法 建议3.区别对待强制转换与as和is 其中有很多需要理解的东西,有些地方可能理解的不太到位,还望指正. 建议1.正确操作字符串 字符串应该是所有编程语言中使用最频繁的一种基础数据类型.如果使用不慎,我们就会为一次字符串的操作所带来的额外性能开销而付出代价.本条建议将从两个方面来探讨如何规避这类性能开销: 1.确保尽量少的装箱 2.避免分配额外的内存空间

编写高质量代码改善C#程序的157个建议[4-9]

原文:编写高质量代码改善C#程序的157个建议[4-9] 前言 本文首先亦同步到http://www.cnblogs.com/aehyok/p/3624579.html.本文主要来学习记录一下内容: 建议4.TryParse比Parse好 建议5.使用int?来确保值类型也可以为null 建议6.区别readonly和const的使用方法 建议7.将0值设为枚举的默认值 建议8.避免给枚举类型的元素提供显式的值 建议9.习惯重载运算符 建议4.TryParse比Parse好 如果注意观察,除st

编写高质量代码改善C#程序的157个建议[C#闭包的陷阱、委托、事件、事件模型]

原文:编写高质量代码改善C#程序的157个建议[C#闭包的陷阱.委托.事件.事件模型] 前言 本文已更新至http://www.cnblogs.com/aehyok/p/3624579.html .本文主要学习记录以下内容: 建议38.小心闭包中的陷阱 建议39.了解委托的实质 建议40.使用event关键字对委托施加保护 建议41.实现标准的事件模型 建议38.小心闭包中的陷阱 首先我们先来看一段代码: class Program { static void Main(string[] arg

编写高质量代码改善C#程序的157个建议[IEnumerable&lt;T&gt;和IQueryable&lt;T&gt;、LINQ避免迭代、LINQ替代迭代]

原文:编写高质量代码改善C#程序的157个建议[IEnumerable<T>和IQueryable<T>.LINQ避免迭代.LINQ替代迭代] 前言 本文已更新至http://www.cnblogs.com/aehyok/p/3624579.html .本文主要学习记录以下内容: 建议29.区别LINQ查询中的IEnumerable<T>和IQueryable<T> 建议30.使用LINQ取代集合中的比较器和迭代器 建议31.在LINQ查询中避免不必要的迭代

编写高质量代码改善C#程序的157个建议[为类型输出格式化字符串、实现浅拷贝和深拷贝、用dynamic来优化反射]

原文:编写高质量代码改善C#程序的157个建议[为类型输出格式化字符串.实现浅拷贝和深拷贝.用dynamic来优化反射] 前言 本文已更新至http://www.cnblogs.com/aehyok/p/3624579.html .本文主要学习记录以下内容: 建议13.为类型输出格式化字符串 建议14.正确实现浅拷贝和深拷贝 建议15.使用dynamic来简化反射实现 建议13.为类型输出格式化字符串   有两种方法可以为类型提供格式化的字符串输出. 一种是意识到类型会产生格式化字符串输出,于是

编写高质量代码改善C#程序的157个建议[为泛型指定初始值、使用委托声明、使用Lambda替代方法和匿名方法]

原文:编写高质量代码改善C#程序的157个建议[为泛型指定初始值.使用委托声明.使用Lambda替代方法和匿名方法] 前言 泛型并不是C#语言一开始就带有的特性,而是在FCL2.0之后实现的新功能.基于泛型,我们得以将类型参数化,以便更大范围地进行代码复用.同时,它减少了泛型类及泛型方法中的转型,确保了类型安全.委托本身是一种引用类型,它保存的也是托管堆中对象的引用,只不过这个引用比较特殊,它是对方法的引用.事件本身也是委托,它是委托组,C#中提供了关键字event来对事件进行特别区分.一旦我们