成人午夜激情影院,小视频免费在线观看,国产精品夜夜嗨,欧美日韩精品一区二区在线播放

Java開發人員的十大戒律

2010-08-28 10:51:27來源:西部e網作者:

10 Commandments for Java Developers
By Aleksey Shevchenko

Go to page: 1  2  Next  

There are many standards and best practices for Java Developers out there. This article outlines ten most basic rules that every developer must adhere to and the disastrous outcomes that can follow if these rules are not followed.

1. Add comments to your code. – Everybody knows this, but somehow forgets to follow it. How many times have you "forgotten" to add comments? It is true that the comments do not literally contribute to the functionality of a program. But time and time again you return to the code that you wrote two weeks ago and, for the life of you, you cannot remember what it does! You are lucky if this uncommented code is actually yours. In those cases something may spark your memory. Unfortunately most of the time it is somebody else's, and many times the person is no longer with the company! There is a saying that goes "one hand washes the other." So let's be considerate to one another (and ourselves) and add comments to your code.

2. Do not complicate things. – I have done it before and I am sure all of you have. Developers tend to come up with complicated solutions for the simplest problems. We introduce EJBs into applications that have five users. We implement frameworks that an application just does not need. We add property files, object-oriented solutions, and threads to application that do not require such things. Why do we do it? Some of us just do not know any better, but some of us do it on purpose to learn something new, to make it interesting for ourselves. For those who do not know any better, I recommend reaching out to the more experienced programmers for advice. And to those of us that are willing to complicate the design of an application for personal gains, I suggest being more professional.

3. Keep in Mind – "Less is more" is not always better. – Code efficiency is a great thing, but in many situations writing less lines of code does not improve the efficiency of that code. Let me give you a "simple" example:

if(newStatusCode.equals("SD") && (sellOffDate == null || 
todayDate.compareTo(sellOffDate)<0 || (lastUsedDate != null && 
todayDate.compareTo(lastUsedDate)>0)) || 
(newStatusCode.equals("OBS") && (OBSDate == null || 
todayDate.compareTo(OBSDate)<0))){
		newStatusCode = "NYP";
}

How easy is it to figure out what this "if" condition is doing? Now imagine that whoever wrote this code, did not follow rule number 1 – Add comments to your code.

Wouldn't it be much easier if we could separate this condition into two separate if statements? Now, consider this revised code:

if(newStatusCode.equals("SD") && (sellOffDate == null || 
todayDate.compareTo(sellOffDate)<0 || (lastUsedDate != null && 
todayDate.compareTo(lastUsedDate)>0))){
		newStatusCode = "NYP";
}else 
if(newStatusCode.equals("OBS") && (OBSDate == null || 
todayDate.compareTo(OBSDate)<0))
{
		newStatusCode = "NYP";
}

Isn't it much more readable? Yes, we have repeating statements. Yes, we have one extra "IF" and two extra curly braces, but the code is much more readable and understandable!

4. No hard coding please. – Developers often forget or omit this rule on purpose because we are, as usual, crunched for time. But maybe if we had followed this rule, we would not have ended up in the situation that we are in. How long does it take to write one extra line of code that defines a static final variable?

Here is an example:

public class A {
	
		public static final String S_CONSTANT_ABC = "ABC";
	
		public boolean methodA(String sParam1){
			
			if (A.S_CONSTANT_ABC.equalsIgnoreCase(sParam1)){
				return true;
			}		
			return false;
		}
}

Now every time we need to compare literal "ABC" with some variable, we can reference A.S_CONSTANT_ABC instead of remembering what the actual code is. It is also much easier to modify this constant in one place rather then looking for it though out all of the code.

5. Do not invent your own frameworks. – There are literally thousands of frameworks out there and most of them are open-source. Many of these frameworks are superb solutions that have been used in thousands of applications. We need to keep up to date with the new frameworks, at least superficially. One of the best and most obvious examples of a superb widely used framework is Struts. This open source web framework is a perfect candidate to be used in web-based applications. Please do not come up with your own version of Struts, you will die trying. But you must remember rule number 3 – Do not complicate things. If the application that you are developing has 3 screens – please, do not use Struts, there isn't much "controlling" required for such an application.

6. Say no to Print lines and String Concatenations. – I know that for debugging purposes, developers like to add System.out.println everywhere we see fit. And we say to ourselves that we will delete these later. But we often forget to delete these lines of code or we do not want to delete them. We use System.out.println to test, why would we be touching the code after we have tested it? We might remove a line of code that we actually need! Just so that you do not underestimate the damage of System.out.println, consider the following code:

public class BadCode {
	public static void calculationWithPrint(){
		double someValue = 0D;
		for (int i = 0; i < 10000; i++) {
			System.out.println(someValue = someValue + i);
		}	
	}
	public static void calculationWithOutPrint(){

			double someValue = 0D;
			for (int i = 0; i < 10000; i++) {
				someValue = someValue + i;
			}
		
	}
	public static void main(String [] n) {
		BadCode.calculationWithPrint();
		BadCode.calculationWithOutPrint();
	}
}

In the figure below, you can observe that method calculationWithOutPrint() takes 0.001204 seconds to run. In comparison, it takes a staggering 10.52 seconds to run the calculationWithPrint() method.

(If you would like to know how to produce a table like this, please read my article entitled "Java Profiling with WSAD" Java Profiling with WSAD )

The best way to avoid such CPU waste is to introduce a wrapper method that looks something like this:

public class BadCode {
	
		public static final int DEBUG_MODE = 1;
		public static final int PRODUCTION_MODE = 2;
	
	public static void calculationWithPrint(int logMode){	
		double someValue = 0D;
		for (int i = 0; i < 10000; i++) {
			someValue = someValue + i;
			myPrintMethod(logMode, someValue);
		}
	}
			
	public static void myPrintMethod(int logMode, double value) {
		if (logMode > BadCode.DEBUG_MODE) {	return; }
		System.out.println(value);	
	}
	public static void main(String [] n) {
		BadCode.calculationWithPrint(BadCode.PRODUCTION_MODE);
		}
}

String concatenation is another CPU waster. Consider example below:

public static void concatenateStrings(String startingString) {
		for (int i = 0; i < 20; i++) {
			startingString = startingString + startingString;
		}
	}
	
	public static void concatenateStringsUsingStringBuffer(
String startingString) {
		StringBuffer sb = new StringBuffer();
		sb.append(startingString);
			for (int i = 0; i < 20; i++) {
				sb.append(sb.toString());
			}
}

In the following figure you can see that the method that uses StringBuffer takes .01 seconds to execute where as the methods that use string concatenation takes .08 seconds to execute. The choice is obvious.

7. Pay attention to the GUI. – No matter how absurd it sounds; I repeatedly observe that GUI is as important to the business clients as functionality and performance. The GUI is an essential part of a successful application. Very often IT management tends to overlook the importance of GUI. Many organizations save money by not hiring web designers who have experience in design of "user-friendly" applications. Java developers have to rely on their own HTML skills and their limited knowledge in this area. I have seen too many applications that are "computer friendly" rather then "user friendly". Very rarely I have seen developers that are proficient in both software development and GUI development. If you are this unlucky Java developer who has been assigned to create an application interface, you should follow these three rules:

  1. Do not reinvent the wheel. Look for existing applications that have similar interface requirements.
  2. Create a prototype first. This is a very important step. The clients like to see what they are going to get. It is better for you also because you are going to get their input before you go all out and create an application interface that will leave the clients cold.
  3. Put the user's hat on. In other words, inspect the application requirements from the user's perspective. For example, a summary screen can be created with paging and without. As a software developer, it might be temping for you to omit paging from the application because it is so much less complicated. But, from the client's perspective, it might not be the best solution because the summary results can hold hundreds of rows of data.

8. Always Prepare Document Requirements. – Every business requirement must be documented. This could be true in some fairy tale, but it is far from that in the real world. No matter how time-pressed your development is, no matter how tight the deadlines, you must always make sure that every business requirement is documented.

9. Unit-test. Unit-test. Unit-test. – I am not going to go into any details as to what is the best way to unit-test your code. I am just going to say that that it must be done. This is the most basic rule of programming. This is one rule that, above all, cannot be omitted. It would be great if your fellow developer could create and execute a test plan for your code, but if that is not possible, you must do it yourself. When creating a unit test plan, follow these basic rules:

  1. Write the unit test before writing code for class it tests.
  2. Capture code comments in unit tests.
  3. Test all the public methods that perform an "interesting" function (that is, not getters and setters, unless they do their getting and setting in some unique way).

10. Remember – quality, not quantity. - Do not stay late (when you do not have to). I understand that sometimes production problems, urgent deadlines, and unexpected events might prevent us from leaving work on time. But, managers do not appreciate and reward their employees because they stay late on regular basis, they appreciate them because they do quality work. If you follow the rules that I outline above, you will find yourself producing less buggy and more maintainable code. That is the most important part of your job.

    Conclusion

    In this article I covered ten critical rules for Java Programmers. It is not merely important to know these rules, it is also important to follow them. Hopefully, these rules will help all of us become better programmers and professionals.

    About the Author

    Aleksey Shevchenko has been working with object-oriented languages for over seven years. He is now implementing enterprise IT solutions for Wall Street and the manufacturing and publishing industries.

     

    Java開發人員的十大戒律

     
     
    Java開發者來說,有許多的標準和最佳實踐。本文列舉了每一個開發人員必須遵從的十大基本法則;如果有了可以遵從的規則而不遵從,那么將導致的是十分悲慘的結局。
     
    1.    在你的代碼里加入注釋
    每個人都知道這點,但不知何故忘記了遵守。算一算有多少次你“忘記”了添加注釋?這是事實:注釋對程序在功能上沒有實質的貢獻。但是,你需要一次又一次的回到你兩個禮拜之前寫的代碼上來,可能一輩子都是這樣,你一定記不住這些代碼為什么會這樣。如果這些代碼是你的,你還比較的幸運。因為它有可能讓你回憶起。但是不幸的是,很多時間,這些代碼是別人的,而且很有可能他已經離開了公司。
     
    2.    不要讓事情復雜化
    我以前就這么干過,而且我相信所有的人都這么干過。開發人員常常為一個簡單的問題而提出一個解決方案。我們為僅僅只有5個用戶的應用而引入EJBs。我們為一個應用使用框架而它根本不需要。我們加入屬性文件,面向對象的解決方案,和線程到應用中,但是它根本不需要這些。為什么我們這樣做?我們中的一些人是因為不知道怎么做更好,但是還有一些人這樣做的目的是為了學習新的知識,從而使得這個應用對于我們自己來說做得比較有趣。
     
    3.    牢牢記住——“少即是多(less is more)”并不永遠是好的
    代碼的效率是一偉大的事情,但是在很多情況下,寫更少的代碼行并不能提高該代碼的效率。請讓我向你展示一個簡單的例子。
    if(newStatusCode.equals("SD") && (sellOffDate == null || 
    todayDate.compareTo(sellOffDate)<0 || (lastUsedDate != null && 
    todayDate.compareTo(lastUsedDate)>0)) || 
    (newStatusCode.equals("OBS") && (OBSDate == null || 
    todayDate.compareTo(OBSDate)<0))){
                            newStatusCode = "NYP";
    }
    我想問一句:說出上面的那段代碼的if條件想干什么容易嗎?現在,我們再來假設無論是誰寫出這段代碼,而沒有遵從第一條規則——在你的代碼里加入注釋。
    如果我們把這個條件分到兩個獨立的if陳述句中,難道不是更簡單一些嗎?現在,考慮下面的修正代碼:
    if(newStatusCode.equals("SD") && (sellOffDate == null || 
    todayDate.compareTo(sellOffDate)<0 || (lastUsedDate != null && 
    todayDate.compareTo(lastUsedDate)>0))){
                            newStatusCode = "NYP";
    }else 
    if(newStatusCode.equals("OBS") && (OBSDate == null || 
    todayDate.compareTo(OBSDate)<0))
    {
                            newStatusCode = "NYP";
    }
    難道它不是有了更好的可讀性?是的,我們重復了陳述條件。是的,我們多出了一個多余的“IF”和兩對多余的括弧。但是代碼有了更好的可讀性和可理解性。
     
    4.    請不要有硬代碼
    開發人員常常有意識的忘記或者忽視這條規則,原因是我們,和一般時候一樣,在趕時間。如果我們遵從這條規則,我們可能會趕不上進度。我們可能不能結束我們的當前狀態。但是寫一條額外的定義靜態常量的代碼行又能花費我們多少時間呢?
    這里有一個例子。
                   public class A {
                   
                                   public static final String S_CONSTANT_ABC = "ABC";
                   
                                   public boolean methodA(String sParam1){
                                                  if(A.S_CONSTANT_ABC.equalsIgnoreCase(sParam1)){
                                                                 return true;
                                                  }                             
                                                  return false;
                                   }
                   }
    現在,每一次我們需要和某一些變量比較字符串“ABC”的時候,我們只需要引用S_CONSTANT_ABC而不是記住實際的代碼是什么。它還有一個好處是:更加容易在一個地方修改常量,而不是在所有的代碼中尋找這個代碼。
     
    5.    不要發明你自己的frameworks
    已經推出了幾千種frameworks,而且它們中的大多數是開源的。這些frameworks中間有很多是極好的解決方案,被應用到成千上萬的應用中。你們需要跟上這些新frameworks的步伐,最起碼是膚淺的。在這些極好的、應用廣泛的frameworks中間,一個最好的、最直接的例子是Struts。在你所能想象到的frameworks中,這個開源的web frameworks對于基于web的應用是一個完美的候選者。但是你必須記住第二條規則——不要讓事情復雜化。如果你開發的應用只有三個頁面—請,不要使用Struts,對于這樣一個應用,沒有什么“控制”請求的。
     
    6.    不要打印行和字符串相加
    我知道,為了調試的目的,開發人員喜歡在每一個我們認為適合的地方添加System.out.println,而且我們會對我們自己說,會在以后刪掉這些代碼的。但是我們常常忘掉刪去這些代碼行,或者我們根本就不想刪掉它們。我們使用System.out.println來測試,當我們測試完成以后,為什么我們還能接觸到它們呢?我們可能刪掉一行我們實際需要的代碼,僅僅是因為你低估了System.out.println所帶來的傷害,考慮下面的代碼:
    public class BadCode {
     public static void calculationWithPrint(){
          double someValue = 0D;
          for (int i = 0; i < 10000; i++) {
               System.out.println(someValue = someValue + i);
          }   
     }
     public static void calculationWithOutPrint(){
     
               double someValue = 0D;
               for (int i = 0; i < 10000; i++) {
                    someValue = someValue + i;
               }
         
     }
     public static void main(String [] n) {
          BadCode.calculationWithPrint();
          BadCode.calculationWithOutPrint();
     }
    }
    在下面的表格中,你能夠看到calculationWithOutPrint()方法的運行花了0.001204秒。相比較而言,運行calculationWithPrint()方法花了令人驚訝的10.52秒。
    \
    (如果你不知道怎么得到一個像這樣的表格,請參閱我的文章“Java Profiling with WSAD Java Profiling with WSAD
    避免這樣一個CPU浪費的最好方法是引入一個包裝器方法,就象下面這樣
    public class BadCode {
                   
                                   public static final int DEBUG_MODE = 1;
                                   public static final int PRODUCTION_MODE = 2;
                   
                   public static void calculationWithPrint(int logMode){           
                                   double someValue = 0D;
                                   for (int i = 0; i < 10000; i++) {
                                                  someValue = someValue + i;
                                                  myPrintMethod(logMode, someValue);
                                   }
                   }
                                                  
                   public static void myPrintMethod(int logMode, double value) {
                                   if (logMode > BadCode.DEBUG_MODE) {             return; }
                                   System.out.println(value);     
                   }
                   public static void main(String [] n) {
                                   BadCode.calculationWithPrint(BadCode.PRODUCTION_MODE);
                                   }
    }
    在下面的圖中,你將看到,使用了StringBuffer的那個方法只花了0.01秒來執行,而那個使用了字符串相加的方法卻花了0.08秒來運行。選擇是顯而易見的。
    \
     
    7.   關注GUI
    不管這聽起來有多么可笑,我都要再三地說明:GUI對于商業客戶來說和功能和性能一樣重要。GUI是一個成功的系統的必要的一部分。(但是),IT雜志常常傾向于忽視GUI的重要性。很多機構為了省錢而不雇用那些在設計“用戶友好”GUI方面有豐富經驗的設計人員。Java開發人員不得不依賴他們自己的HTML知識,但是他們在這方面的知識十分有限。我看到過很多這樣的應用:它們是“計算機友好”,而不是“用戶友好”我很少很少能看到有開發人員既精通軟件開發,又精通GUI開發。如果你是那個不幸的開發人員,被分配去開發用戶接口,你應該遵從以下的三條原則:
    一、不要重復發明輪子。尋找有相似用戶接口需求的已經存在的系統。
    二、首先創建一個原型。這是非常重要的步驟。客戶喜歡看看他們將要得到什么。這對你來說也是很好的,因為在你全力以赴而做出一個將要使用戶生氣的用戶接口之前,你就得到了它們的反饋。
    三、戴用戶的帽子。換一句話說,站在用戶的視角檢查應用的需求。例如,一個總結頁面到底要不要分頁。作為一個軟件開發者,你傾向于在一個系統中忽視分頁,因為這樣使得你有比較少的開發復雜性。但是,這對于從一個用戶的視角來說卻不是最好的解決方案,因為小結的數據將會有成百上千個數據行。
     
    8.   永遠準備文檔化的需求
    每一個業務需求都必須文檔化。這可能在一些童話故事里才能成真,但是在現實世界卻不可能。不管時間對于你的開發來說是多么緊迫,也不管交付日期馬上就要到來,你永遠都必須清楚,每一個業務需求是文檔化的。
     
    9.   單元測試、單元測試、單元測試
    我將不會深入地討論哪些什么是把你的代碼進行單元測試的最佳方法的細節問題。我將要說的是單元測試必須要做。這是編程的最基本的法則。這是上面所有法則中最不能被忽略的一個。如果你的同事能為你的代碼創建和測試單元測試,這是最好不過的事。但是如果沒有人為你做這些事,那么你就必須自己做。在創建你的單元測試計劃的時候,遵從下面的這些規則:
    一、在寫代碼之前就寫單元測試用例。
    二、在單元測試里寫注釋。
    三、測試一切執行“interesting”功能的公有方法(“interesting”的意思是非setters或getters方法,除非它們通過一種特殊的方式執行set和get方法)。
     
    10.             記住—質量,而不是數量。
    不要在辦公室里呆得太晚(當你不必呆的太晚的時候)。我理解有時,產品的問題、緊迫的最終期限、意想不到的事件都會阻止我們按時下班。但是,在正常情況下,經理是不會賞識和獎賞那些下班太晚的員工的,他賞識他們是因為他們所做產品的質量。如果你遵從了我上面給出的那些規則,你將會發現你的代碼更加少的bug,更加多的可維護性。而這才是你的工作的最重要的部分。
     
    總結
    在這篇文章里,我給出了針對Java開發人員的十個重要的規則。重要的不僅僅是知道這些規則,在編碼的過程中遵從這些規則更為重要。希望這些規則能夠幫助我們成為更好的編程人員和專業人員。
     
    關于作者
    Aleksey Shevchenko在面向對象方面的編程有著七年以上的經驗。他現在在從事華爾街、制造和出版工業方面的IT解決方案的工作。
    關鍵詞:Java

    贊助商鏈接:

    主站蜘蛛池模板: 河北区| 商水县| 红河县| 平罗县| 靖州| 乾安县| 抚松县| 外汇| 健康| 临城县| 海伦市| 林西县| 定襄县| 攀枝花市| 怀安县| 高唐县| 鹤庆县| 万盛区| 沿河| 正阳县| 治多县| 许昌市| 宣化县| 南投县| 海宁市| 象州县| 天等县| 丁青县| 罗甸县| 精河县| 梁平县| 中牟县| 绥棱县| 西乌珠穆沁旗| 滁州市| 新绛县| 崇礼县| 从化市| 西和县| 绩溪县| 婺源县|