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

Java開(kāi)發(fā)人員的十大戒律

2010-08-28 10:51:27來(lái)源:西部e網(wǎng)作者:

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開(kāi)發(fā)人員的十大戒律

     
     
    對(duì)Java開(kāi)發(fā)者來(lái)說(shuō),有許多的標(biāo)準(zhǔn)和最佳實(shí)踐。本文列舉了每一個(gè)開(kāi)發(fā)人員必須遵從的十大基本法則;如果有了可以遵從的規(guī)則而不遵從,那么將導(dǎo)致的是十分悲慘的結(jié)局。
     
    1.    在你的代碼里加入注釋
    每個(gè)人都知道這點(diǎn),但不知何故忘記了遵守。算一算有多少次你“忘記”了添加注釋?這是事實(shí):注釋對(duì)程序在功能上沒(méi)有實(shí)質(zhì)的貢獻(xiàn)。但是,你需要一次又一次的回到你兩個(gè)禮拜之前寫的代碼上來(lái),可能一輩子都是這樣,你一定記不住這些代碼為什么會(huì)這樣。如果這些代碼是你的,你還比較的幸運(yùn)。因?yàn)樗锌赡茏屇慊貞浧稹5遣恍业氖牵芏鄷r(shí)間,這些代碼是別人的,而且很有可能他已經(jīng)離開(kāi)了公司。
     
    2.    不要讓事情復(fù)雜化
    我以前就這么干過(guò),而且我相信所有的人都這么干過(guò)。開(kāi)發(fā)人員常常為一個(gè)簡(jiǎn)單的問(wèn)題而提出一個(gè)解決方案。我們?yōu)閮H僅只有5個(gè)用戶的應(yīng)用而引入EJBs。我們?yōu)橐粋(gè)應(yīng)用使用框架而它根本不需要。我們加入屬性文件,面向?qū)ο蟮慕鉀Q方案,和線程到應(yīng)用中,但是它根本不需要這些。為什么我們這樣做?我們中的一些人是因?yàn)椴恢涝趺醋龈茫沁有一些人這樣做的目的是為了學(xué)習(xí)新的知識(shí),從而使得這個(gè)應(yīng)用對(duì)于我們自己來(lái)說(shuō)做得比較有趣。
     
    3.    牢牢記住——“少即是多(less is more)”并不永遠(yuǎn)是好的
    代碼的效率是一偉大的事情,但是在很多情況下,寫更少的代碼行并不能提高該代碼的效率。請(qǐng)讓我向你展示一個(gè)簡(jiǎn)單的例子。
    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";
    }
    我想問(wèn)一句:說(shuō)出上面的那段代碼的if條件想干什么容易嗎?現(xiàn)在,我們?cè)賮?lái)假設(shè)無(wú)論是誰(shuí)寫出這段代碼,而沒(méi)有遵從第一條規(guī)則——在你的代碼里加入注釋。
    如果我們把這個(gè)條件分到兩個(gè)獨(dú)立的if陳述句中,難道不是更簡(jiǎn)單一些嗎?現(xiàn)在,考慮下面的修正代碼:
    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";
    }
    難道它不是有了更好的可讀性?是的,我們重復(fù)了陳述條件。是的,我們多出了一個(gè)多余的“IF”和兩對(duì)多余的括弧。但是代碼有了更好的可讀性和可理解性。
     
    4.    請(qǐng)不要有硬代碼
    開(kāi)發(fā)人員常常有意識(shí)的忘記或者忽視這條規(guī)則,原因是我們,和一般時(shí)候一樣,在趕時(shí)間。如果我們遵從這條規(guī)則,我們可能會(huì)趕不上進(jìn)度。我們可能不能結(jié)束我們的當(dāng)前狀態(tài)。但是寫一條額外的定義靜態(tài)常量的代碼行又能花費(fèi)我們多少時(shí)間呢?
    這里有一個(gè)例子。
                   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;
                                   }
                   }
    現(xiàn)在,每一次我們需要和某一些變量比較字符串“ABC”的時(shí)候,我們只需要引用S_CONSTANT_ABC而不是記住實(shí)際的代碼是什么。它還有一個(gè)好處是:更加容易在一個(gè)地方修改常量,而不是在所有的代碼中尋找這個(gè)代碼。
     
    5.    不要發(fā)明你自己的frameworks
    已經(jīng)推出了幾千種frameworks,而且它們中的大多數(shù)是開(kāi)源的。這些frameworks中間有很多是極好的解決方案,被應(yīng)用到成千上萬(wàn)的應(yīng)用中。你們需要跟上這些新frameworks的步伐,最起碼是膚淺的。在這些極好的、應(yīng)用廣泛的frameworks中間,一個(gè)最好的、最直接的例子是Struts。在你所能想象到的frameworks中,這個(gè)開(kāi)源的web frameworks對(duì)于基于web的應(yīng)用是一個(gè)完美的候選者。但是你必須記住第二條規(guī)則——不要讓事情復(fù)雜化。如果你開(kāi)發(fā)的應(yīng)用只有三個(gè)頁(yè)面—請(qǐng),不要使用Struts,對(duì)于這樣一個(gè)應(yīng)用,沒(méi)有什么“控制”請(qǐng)求的。
     
    6.    不要打印行和字符串相加
    我知道,為了調(diào)試的目的,開(kāi)發(fā)人員喜歡在每一個(gè)我們認(rèn)為適合的地方添加System.out.println,而且我們會(huì)對(duì)我們自己說(shuō),會(huì)在以后刪掉這些代碼的。但是我們常常忘掉刪去這些代碼行,或者我們根本就不想刪掉它們。我們使用System.out.println來(lái)測(cè)試,當(dāng)我們測(cè)試完成以后,為什么我們還能接觸到它們呢?我們可能刪掉一行我們實(shí)際需要的代碼,僅僅是因?yàn)槟愕凸懒?/SPAN>System.out.println所帶來(lái)的傷害,考慮下面的代碼:
    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()方法的運(yùn)行花了0.001204秒。相比較而言,運(yùn)行calculationWithPrint()方法花了令人驚訝的10.52秒。
    \
    (如果你不知道怎么得到一個(gè)像這樣的表格,請(qǐng)參閱我的文章“Java Profiling with WSAD Java Profiling with WSAD
    避免這樣一個(gè)CPU浪費(fèi)的最好方法是引入一個(gè)包裝器方法,就象下面這樣
    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的那個(gè)方法只花了0.01秒來(lái)執(zhí)行,而那個(gè)使用了字符串相加的方法卻花了0.08秒來(lái)運(yùn)行。選擇是顯而易見(jiàn)的。
    \
     
    7.   關(guān)注GUI
    不管這聽(tīng)起來(lái)有多么可笑,我都要再三地說(shuō)明:GUI對(duì)于商業(yè)客戶來(lái)說(shuō)和功能和性能一樣重要。GUI是一個(gè)成功的系統(tǒng)的必要的一部分。(但是),IT雜志常常傾向于忽視GUI的重要性。很多機(jī)構(gòu)為了省錢而不雇用那些在設(shè)計(jì)“用戶友好”GUI方面有豐富經(jīng)驗(yàn)的設(shè)計(jì)人員。Java開(kāi)發(fā)人員不得不依賴他們自己的HTML知識(shí),但是他們?cè)谶@方面的知識(shí)十分有限。我看到過(guò)很多這樣的應(yīng)用:它們是“計(jì)算機(jī)友好”,而不是“用戶友好”我很少很少能看到有開(kāi)發(fā)人員既精通軟件開(kāi)發(fā),又精通GUI開(kāi)發(fā)。如果你是那個(gè)不幸的開(kāi)發(fā)人員,被分配去開(kāi)發(fā)用戶接口,你應(yīng)該遵從以下的三條原則:
    一、不要重復(fù)發(fā)明輪子。尋找有相似用戶接口需求的已經(jīng)存在的系統(tǒng)。
    二、首先創(chuàng)建一個(gè)原型。這是非常重要的步驟。客戶喜歡看看他們將要得到什么。這對(duì)你來(lái)說(shuō)也是很好的,因?yàn)樵谀闳σ愿岸龀鲆粋(gè)將要使用戶生氣的用戶接口之前,你就得到了它們的反饋。
    三、戴用戶的帽子。換一句話說(shuō),站在用戶的視角檢查應(yīng)用的需求。例如,一個(gè)總結(jié)頁(yè)面到底要不要分頁(yè)。作為一個(gè)軟件開(kāi)發(fā)者,你傾向于在一個(gè)系統(tǒng)中忽視分頁(yè),因?yàn)檫@樣使得你有比較少的開(kāi)發(fā)復(fù)雜性。但是,這對(duì)于從一個(gè)用戶的視角來(lái)說(shuō)卻不是最好的解決方案,因?yàn)樾〗Y(jié)的數(shù)據(jù)將會(huì)有成百上千個(gè)數(shù)據(jù)行。
     
    8.   永遠(yuǎn)準(zhǔn)備文檔化的需求
    每一個(gè)業(yè)務(wù)需求都必須文檔化。這可能在一些童話故事里才能成真,但是在現(xiàn)實(shí)世界卻不可能。不管時(shí)間對(duì)于你的開(kāi)發(fā)來(lái)說(shuō)是多么緊迫,也不管交付日期馬上就要到來(lái),你永遠(yuǎn)都必須清楚,每一個(gè)業(yè)務(wù)需求是文檔化的。
     
    9.   單元測(cè)試、單元測(cè)試、單元測(cè)試
    我將不會(huì)深入地討論哪些什么是把你的代碼進(jìn)行單元測(cè)試的最佳方法的細(xì)節(jié)問(wèn)題。我將要說(shuō)的是單元測(cè)試必須要做。這是編程的最基本的法則。這是上面所有法則中最不能被忽略的一個(gè)。如果你的同事能為你的代碼創(chuàng)建和測(cè)試單元測(cè)試,這是最好不過(guò)的事。但是如果沒(méi)有人為你做這些事,那么你就必須自己做。在創(chuàng)建你的單元測(cè)試計(jì)劃的時(shí)候,遵從下面的這些規(guī)則:
    一、在寫代碼之前就寫單元測(cè)試用例。
    二、在單元測(cè)試?yán)飳懽⑨尅?/SPAN>
    三、測(cè)試一切執(zhí)行“interesting”功能的公有方法(“interesting”的意思是非setters或getters方法,除非它們通過(guò)一種特殊的方式執(zhí)行set和get方法)。
     
    10.             記住—質(zhì)量,而不是數(shù)量。
    不要在辦公室里呆得太晚(當(dāng)你不必呆的太晚的時(shí)候)。我理解有時(shí),產(chǎn)品的問(wèn)題、緊迫的最終期限、意想不到的事件都會(huì)阻止我們按時(shí)下班。但是,在正常情況下,經(jīng)理是不會(huì)賞識(shí)和獎(jiǎng)賞那些下班太晚的員工的,他賞識(shí)他們是因?yàn)樗麄兯霎a(chǎn)品的質(zhì)量。如果你遵從了我上面給出的那些規(guī)則,你將會(huì)發(fā)現(xiàn)你的代碼更加少的bug,更加多的可維護(hù)性。而這才是你的工作的最重要的部分。
     
    總結(jié)
    在這篇文章里,我給出了針對(duì)Java開(kāi)發(fā)人員的十個(gè)重要的規(guī)則。重要的不僅僅是知道這些規(guī)則,在編碼的過(guò)程中遵從這些規(guī)則更為重要。希望這些規(guī)則能夠幫助我們成為更好的編程人員和專業(yè)人員。
     
    關(guān)于作者
    Aleksey Shevchenko在面向?qū)ο蠓矫娴木幊逃兄吣暌陨系慕?jīng)驗(yàn)。他現(xiàn)在在從事華爾街、制造和出版工業(yè)方面的IT解決方案的工作。
    關(guān)鍵詞:Java

    贊助商鏈接:

    主站蜘蛛池模板: 时尚| 新郑市| 安化县| 长乐市| 南城县| 九台市| 大同县| 澄迈县| 喀喇| 依兰县| 漳平市| 平武县| 兴宁市| 信宜市| 呼和浩特市| 余庆县| 高雄市| 鲁甸县| 许昌县| 双辽市| 琼结县| 宣威市| 鸡东县| 万宁市| 武强县| 壤塘县| 竹北市| 博乐市| 南汇区| 宿州市| 徐闻县| 平阴县| 武功县| 临澧县| 岑巩县| 黑龙江省| 永修县| 通州市| 德令哈市| 湄潭县| 姜堰市|