<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    2006年12月15日

    執(zhí)行./startup.sh,或者./shutdown.sh的時候,爆出了Permission denied

    關(guān)于LINUX權(quán)限-bash: ./startup.sh: Permission denied

    <script type="text/javascript"></script><script type="text/javascript"></script>

    在執(zhí)行./startup.sh,或者./shutdown.sh的時候,爆出了Permission denied,

    其實很簡單,就是今天在執(zhí)行tomcat的時候,用戶沒有權(quán)限,而導致無法執(zhí)行,

    用命令chmod 修改一下bin目錄下的.sh權(quán)限就可以了

    如chmod u+x *.sh

    在此執(zhí)行,OK了。

    posted @ 2014-12-30 10:26 liujg 閱讀(289) | 評論 (0)編輯 收藏

    submit()和onsubmit()的區(qū)別(轉(zhuǎn))

    2011-03-16 10:34

    最近在開發(fā)中遇到了表單提交前驗證的問題,用一個普通的button按鈕代替submit按鈕,
    在提交前觸發(fā)這個button的onclick事件,在其事件中觸發(fā)form的submit事件。問題出現(xiàn)了:
    以下是出現(xiàn)相關(guān)代碼:
    <form action="http://www.baidu.com/s?wd=this.form.submit%28%29%3B&cl=3" method="post" name="form1" onsubmit="return alert('已提交!'); return false;"> 
        <table align="center" width="420px" cellPadding="2" cellSpacing="1" bgcolor="#A4B6D7"    style="word-wrap:Break-word;">                
            <tr style="cursor: hand;background:#d7e3f6" > 
                <td width="20%" align="right">條型碼</td> 
                <td><input style="width:90%" type="text" name="GOODSNUM"   size="30"  maxlength="8" ></td> 
            </tr> 
            <tr> 
                <td align="center" colspan="2"> 
                    <input type="button" name="save" value="保存" onclick="if((confirm('確定要提交嗎?'))) this.form.submit();"/> 
                </td> 
            </tr>  
        </table> 
    </form> 


    卻發(fā)現(xiàn)并沒有觸發(fā)form的onsubmit方法,而是直接提交了。奇怪了,難道沒有這種方式無法結(jié)合form的onsubmit方法嗎?
    仔細想了想,既然this.form表示form這個對象,那么肯定能獲取到form的屬性和方法的
    ,就改成this.form.onsubmit();  成功!
    我又查了查手冊,原來submit的方法是這樣解釋的:
      The submit method does not invoke the onsubmit event handler. Call the onsubmit event handler directly. When using Microsoft® Internet Explorer 5.5 and later, you can call the fireEvent method with a value of onsubmit in the sEvent parameter.

    意思是說submit這個方法是不觸發(fā)onsubmit時間的,如果想要觸發(fā)它,需要調(diào)用
    fireEvent方法。嘗試一下:this.form.fireEvent('onsubmit');哈哈,果然也成功!不過這樣不是多此一舉嗎?呵呵!

    就這個小問題也搞了我將近一個小時,不過為了以后不為這個問題煩惱,這也是值得的。
    this.form.submit(); //直接提交表單
    this.form.onsubmit(); //調(diào)用form的onsubmit方法
    this.form.fireEvent('onsubmit'); //同上,
         PS:又學到了fireEvent這個方法,

    2.onsubmit()與submit() :

    <sCript>
    funCtion fun()
    {
       alert("form_submit");
    }
    </sCript>

    <form onsubmit="fun()">
    <input type="submit" id="aaa" value="submit">   <!--能彈出form_submit-->
    <input type="button" id="bbb" value="onCliCk_submit" onCliCk="doCument.forms[0].submit()">
    <!--
    表單會提交,但是不會運行fun() 原因是 onsubmit事件不能通過此種方式觸發(fā)(在IE環(huán)境)
    直接用腳本doCumetn.formName.submit()提交表單是不會觸發(fā)表單的onsubmit()事件的
    -->
        <input type="button" id="bb1" value="onCliCk_onsubmit" onCliCk="doCument.forms[0].onsubmit()">

    <!--會觸發(fā)fun()參數(shù)-->
    </form>

    posted @ 2011-09-28 15:11 liujg 閱讀(346) | 評論 (0)編輯 收藏

    doGet()和doPost()的區(qū)別(轉(zhuǎn))

    service()是在javax.servlet.Servlet接口中定義的, 在 javax.servlet.GenericServlet 中實現(xiàn)了這個接口, 而 doGet/doPost 則是在 javax.servlet.http.HttpServlet 中實現(xiàn)的, javax.servlet.http.HttpServlet 是 javax.servlet.GenericServlet 的子類. 所有可以這樣理解, 其實所有的請求均首先由 service() 進行處理, 而在 javax.servlet.http.HttpServlet 的 service() 方法中, 主要做的事情就是判斷請求類型是 Get 還是 Post, 然后調(diào)用對應的 doGet/doPost 執(zhí)行.

    doGet:處理GET請求 doPost:處理POST請求 doPut:處理PUT請求 doDelete:處理DELETE請求 doHead:處理HEAD請求 doOptions:處理OPTIONS請求 doTrace:處理TRACE請求 通常情況下,在開發(fā)基于HTTP的servlet時,開發(fā)者只需要關(guān)心doGet和doPost方法,其它的方法需要開發(fā)者非常的熟悉HTTP編程,因此這些方法被認為是高級方法。 而通常情況下,我們實現(xiàn)的servlet都是從HttpServlet擴展而來。 doPut和doDelete方法允許開發(fā)者支持HTTP/1.1的對應特性; doHead是一個已經(jīng)實現(xiàn)的方法,它將執(zhí)行doGet但是僅僅向客戶端返回doGet應該向客戶端返回的頭部的內(nèi)容; doOptions方法自動的返回servlet所直接支持的HTTP方法信息; doTrace方法返回TRACE請求中的所有頭部信息。 對于那些僅僅支持HTTP/1.0的容器而言,只有doGet, doHead 和 doPost方法被使用,因為HTTP/1.

    下邊是CSDN里邊的一些討論:
    1.doGet和doPost的區(qū)別,在什么時候調(diào)用,為什么有時doPost中套用doGet
    2.提交的form     method=Post就執(zhí)行DOPOST,否則執(zhí)行GOGET 套用是不管method是post還是get都執(zhí)行dopost方法
    3.get:你可以通過URL傳參數(shù)。
    http://www.csdn.net/index.asp?user=1234    , Post不行  
    4.你的表單提交都有方法的,如果提交為get就調(diào)用get方法,用post就調(diào)用post方法.  
        get顯示你傳過去的參數(shù),post則不顯示.
    5.通常的寫法:先用doGet(),然后在doPost()中調(diào)用doGet(),這樣就萬無一失了
    6. 簡單的說,get是通過http     header來傳輸數(shù)據(jù),有數(shù)量限制,而post則是通過http     body來傳輸數(shù)據(jù),沒有數(shù)量限制。
    7.還有一點:get和post提交的數(shù)據(jù)量是不一樣的.  
        get好像最多只能在url后跟64K(?具體多少忘記了),  
        post好像沒這個限制,至少我post過5M以上的文本    
        還有url刷新時get好像可以不用重復提交原來提交的數(shù)據(jù),  
        而post則會說內(nèi)容已提交,想刷新請再提交.

    posted @ 2011-05-24 23:58 liujg 閱讀(479) | 評論 (0)編輯 收藏

    轉(zhuǎn)載 Vim 基本用法

    這是我總結(jié)的一些基本用法,可能對初用者會有幫助,獨樂樂不如眾樂樂,是吧!

    說明:以下黑色為vi和vim均有的一般功能,而紅色為Vim(Vi Improved)所特有功能。Vim一般的Unix和Linux下均有安裝。
    ? 三種狀態(tài)
    Command: 任何輸入都會作為編輯命令,而不會出現(xiàn)在屏幕上,任何輸入都引起立即反映
    Insert: 任何輸入的數(shù)據(jù)都置于編輯寄存器,按ESC,可跳回command方式
    Escape: 以“:”或者“/”為前導的指令,出現(xiàn)在屏幕的最下一行,任何輸入都被當成特別指令。
    ? 離開vi
    :q! 離開vi,并放棄剛在緩沖區(qū)內(nèi)編輯的內(nèi)容。
    :wq 將緩沖區(qū)內(nèi)的資料寫入磁盤中,并離開vi。
    :x 同wq。
    (注意—— :X 是文件加密,一定要與:x存盤退出相區(qū)別)
    ? 進入輸入模式
    a (append) 由游標之后加入資料。
    A 由該行之末加入資料。
    i (insert) 由游標之前加入資料。
    I 由該行之首加入資料。
    o (open) 新增一行於該行之下供輸入資料之用。
    O 新增一行於該行之上供輸入資料之用。
    ? 刪除與修改
    x 刪除游標所在該字元。
    X 刪除游標所在之前一字元。
    r 用接於此指令之后的字元取代(replace)游標所在字元。如:ra將游標所在字元以 a 取代之。
    R 進入取代狀態(tài),直到《ESC》為止。
    s 刪除游標所在之字元,并進入輸入模式直到《ESC》。
    S 刪除游標所在之該行資料,并進入輸入模式直到《ESC》。
    ? 光標的移動
    m<a-z> 設置書簽<a-z>
    ‘<a-z> 移至書簽<a-z>處
    0 移至該行之首
    $ 移至該行之末。
    e 移動到下個字的最後一個字母
    w 移動到下個字的第一個字母。
    b 移動到上個字的第一個字母。
    ^ 移至該行的第一個字元處。
    H 移至視窗的第一行。
    M 移至視窗的中間那行。
    L 移至視窗的最后一行。
    G 移至該文件的最后一行。
    + 移至下一列的第一個字元處。
    - 移至上一列的第一個字元處。
    :n 移至該文件的第 n 列。
    n+ 移至游標所在位置之后的第 n 列。
    n- 移至游標所在位置之前的第 n 列。
    <Ctrl><g> 顯示該行之行號、文件名稱、文件中最末行之行號、游標所在行號占總行號之百分比。

    (Vim) 光標移動基本用法小解:
    (這只要組合上邊的功能就可以明白了,不用再一一講解了吧!)
    ge b w e
    ← ← ---→ --→
    This is-a line, with special/separated/words (and some more).
    ←- ←-- -----------------→ ---→
    GE B W E

    ? 視窗的移動
    <Ctrl><f> 視窗往下卷一頁。
    <Ctrl><b> 視窗往上卷一頁。
    <Ctrl><d> 視窗往下卷半頁。
    <Ctrl><u> 視窗往上卷半頁。
    <Ctrl><e> 視窗往下卷一行。
    <Ctrl><y> 視窗往上卷一行。
    ? 剪切、復制、刪除
    Operator + Scope = command
    ? Operator
    d 剪切
    y 復制。
    p 粘帖,與 d 和 y 配和使用。可將最后d或y的資料放置於游標所在位置之行列下。
    c 修改,類似delete與insert的組和。刪除一個字組、句子等之資料,并插入新建資料。
    ? Scope
    e 由游標所在位置至該字串的最后一個字元。
    w 由游標所在位置至下一個字串的第一個字元。
    b 由游標所在位置至前一個字串的第一個字元。
    $ 由游標所在位置至該行的最后一個字元。
    0 由游標所在位置至該行的第一個字元。
    ? 整行動作
    dd 刪除整行。
    D 以行為單位,刪除游標后之所有字元。
    cc 修改整行的內(nèi)容。
    yy 使游標所在該行復制到記憶體緩沖區(qū)。
    ? 取消前一動作(Undo)
    u 恢復最后一個指令之前的結(jié)果。
    U 恢復游標該行之所有改變。
    (vim) u 可以多次撤消指令,一次撤消一個操作,直至本次操作開始為止。
    (vim) Ctrl+r 可以恢復撤消前內(nèi)容,按多次可恢復多次。
    ? 查找與替換
    /字串 往游標之后尋找該字串。
    ?字串 往游標之前尋找該字串。
    n 往下繼續(xù)尋找下一個相同的字串。
    N 往上繼續(xù)尋找下一個相同的字串。
    % 查找“(”,“)”,“{”,“}”的配對符。
    s 搜尋某行列范圍。
    g 搜尋整個編輯緩沖區(qū)的資料。
    :1,$s/old/new/g 將文件中所有的『old』改成『new』。
    :10,20s/^/ / 將第10行至第20行資料的最前面插入5個空白。
    (vim)
    /字符串 后邊輸入查詢內(nèi)容可保存至緩沖區(qū)中,可用↑↓進行以往內(nèi)容選擇。
    另外:將光標移動在選定單詞下方按*,則可以選中此單詞作為查詢字符,可以避免輸入一長串字符的麻煩。
    ? (vim) 大小寫替換
    首先用按v開啟選擇功能,然后用↑↓←→鍵來選定所要替換的字符,若是小寫變大寫,則按U;反之按u;
    如果是選擇單詞,則可以在按v后,按w,最后按U/u,這樣就可以將字符隨意的改變大小寫了,而不用刪除后重新敲入。

    ? 資料的連接
    J 句子的連接。將游標所在之下一行連接至游標該行的后面。
    ? 環(huán)境的設定
    :set all 可設置的環(huán)境變量列表
    :set 環(huán)境變量的當前值
    :set nu 設定資料的行號。
    :set nonu 取消行號設定。
    :set ai 自動內(nèi)縮。
    :set noai 取消自動內(nèi)縮。
    (vim)
    :set ruler 會在屏幕右下角顯示當前光標所處位置,并隨光移動而改變,占用屏幕空間較小,使用也比較方便,推薦使用。
    :set hlsearch 在使用查找功能時,會高亮顯示所有匹配的內(nèi)容。
    :set nohlsearch 關(guān)閉此功能。
    :set incsearch 使Vim在輸入字符串的過程中,光標就可定位顯示匹配點。
    :set nowrapscan 關(guān)閉查找自動回環(huán)功能,即查找到文件結(jié)尾處,結(jié)束查找;默認狀態(tài)是自動回環(huán)

    ? ex指令
    ? 讀寫資料
    :10,20w test 將第10行至第20行的資料寫入test文件。
    :10,20w>>test 將第10行至第20行的資料加在test文件之后。
    :r test 將test文件的資料讀入編輯緩沖區(qū)的最后。
    :e [filename] 編輯新的文件。
    :e! [filename] 放棄當前修改的文件,編輯新的文件。
    :sh 進入shell環(huán)境,使用exit退出,回到編輯器中。

    :!cmd 運行命令cmd后,返回到編輯器中。
    ? 刪除、復制及搬移
    :10,20d 刪除第10行至第20行的資料。
    :10d 刪除第10行的資料。
    :%d 刪除整個編輯緩沖區(qū)。
    :10,20co30 將第10行至第20行的資料復制至第30行之后。
    :10,20mo30 將第10行至第20行的資料搬移至第30行之后。

    本文來自CSDN博客,轉(zhuǎn)載請標明出處:http://blog.csdn.net/jsufcz/archive/2009/02/11/3875956.aspx

    posted @ 2011-05-03 14:25 liujg 閱讀(254) | 評論 (0)編輯 收藏

    OERR: ORA-12519


    OERR: ORA-12519報錯  
    1、查詢數(shù)據(jù)庫當前的連接數(shù):
    select count(*) from v$process;
    2、查詢數(shù)據(jù)庫允許的最大連接數(shù):
    select value from v$parameter where name = 'processes';
    3、修改數(shù)據(jù)庫允許的最大連接數(shù):
    alter system set processes = 300 scope = spfile;
    4、重啟數(shù)據(jù)庫:
    shutdown immediate;
    startup; 

     


    文章出處:飛諾網(wǎng)(www.firnow.com):http://dev.firnow.com/course/7_databases/oracle/oraclejs/20091103/181042.html

    posted @ 2011-01-30 13:36 liujg 閱讀(562) | 評論 (0)編輯 收藏

    原形設計模式,搞不懂

    今天下載了個設計模式看,prototype模式就兩頁紙,看過了也沒看出來它到底做什么,比較郁悶。我就不清楚那個copy方法到底做了什么?沒有copy方法不行嗎?


    定義:

    用原型實例指定創(chuàng)建對象的種類,并且通過拷貝這些原型創(chuàng)建新的對象. //通過拷貝創(chuàng)建新的對象跟通過繼承創(chuàng)建有什么區(qū)別呢?
    Prototype 模式允許一個對象再創(chuàng)建另外一個可定制的對象,根本無需知道任何如何創(chuàng)建的

    細節(jié),工作原理是:通過將一個原型對象傳給那個要發(fā)動創(chuàng)建的對象,這個要發(fā)動創(chuàng)建的對象

    通過請求原型對象拷貝它們自己來實施創(chuàng)建。

    如何使用?

    因為Java 中的提供clone()方法來實現(xiàn)對象的克隆(具體了解 clone()按這里),所以

    Prototype 模式實現(xiàn)一下子變得很簡單.

    以勺子為例:

    public abstract class AbstractSpoon implements Cloneable
    {

        String spoonName;

        public void setSpoonName(String spoonName) {this.spoonName = spoonName;}

        public String getSpoonName() {return this.spoonName;}

        public Object clone()

         {

            Object object = null;

            try {
                object = super.clone();

            } catch (CloneNotSupportedException exception) {

                System.err.println("AbstractSpoon is not Cloneable");

            }

            return object;
        }

    }

    有兩個具體實現(xiàn)(ConcretePrototype):

    public class SoupSpoon extends AbstractSpoon

    {

        public SoupSpoon()
         {

            setSpoonName("Soup Spoon");

        }

    }

    public class SaladSpoon extends AbstractSpoon

    {

         public SaladSpoon()

         {
             setSpoonName("Salad Spoon");

         }

    }

    調(diào)用 Prototype 模式很簡單:

    AbstractSpoon spoon = new SoupSpoon();

    AbstractSpoon spoon = new SaladSpoon();

    posted @ 2007-11-29 16:23 liujg 閱讀(317) | 評論 (0)編輯 收藏

    java 關(guān)閉IE

    本文代碼來自以下連接。
    http://www.developer.com/java/other/article.php/10936_2212401_3Introduction to the Java Robot Class in Java
    代碼簡單說明:可以在1024*768的屏幕分辨率下關(guān)掉一個最大化的IE窗口。


    import java.awt.*;
    import java.awt.event.*;

    /**this class will close an maxmimum IE window in the 1024*768's screen resolution's machine.*/
    public class Robot04{
       public static void main(String[] args)
                                 throws AWTException{
      Robot robot = new Robot();
      robot.mouseMove(1005,10);
      robot.delay(2000);
      robot.mousePress(InputEvent.BUTTON1_MASK);
      robot.delay(2000);
      robot.mouseRelease(InputEvent.BUTTON1_MASK);
       }//end main

    }//end class Robot04

    這個程序的GUI版本。
    Robot04GUI.java
    /**
     * Robot04GUI.java
     * create by kin. 2004/11/07.
     * Please enjoy this.
     */

    import javax.swing.*;
    import javax.swing.event.*;

    import java.awt.event.*;
    import java.awt.*;

    /**Robot04's GUI version.*/
    public class Robot04GUI extends JFrame {
     
     private JButton b = new JButton("Close IE");
     
     public Robot04GUI() {
      super("Close IE");
      getContentPane().add(b,BorderLayout.CENTER);
      b.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
        try {
         new Robot04().main(new String[]{}); 
        } catch (Exception ex) {
         ex.printStackTrace();
        }
       } 
      });
     } 
     
     public static void main(String[] args) {
      Robot04GUI r = new Robot04GUI();
      r.setSize(200,200);
      r.setVisible(true);
     } 

    posted @ 2007-10-12 10:06 liujg 閱讀(584) | 評論 (0)編輯 收藏

    看了下java核心技術(shù)中的代理,還是很暈

    需要記住的東東:
       1.代理類是在程序運行過程中創(chuàng)建的,一旦創(chuàng)建就變成了常規(guī)類,與虛擬機種的任何其他類沒有什么區(qū)別.
      2.所有的代理類都擴展于Proxy類,一個代理類只有一個實例變量--調(diào)用處理器,它定義在Proxy的超類中,為了履行代理對象的職責,所需要的任何附加數(shù)據(jù)都必須存儲在調(diào)用處理器中.
       3.所有的代理類都覆蓋了Object中的toString,equals和hashCode,如何所有的代理方法一樣,這些方法僅僅調(diào)用了調(diào)用處理器的invoke.Object中的其他方法clone,getClass沒有被重新定義.

    感覺就是把原來的方法,拿到代理類里面執(zhí)行,在執(zhí)行前后可以加入自己的代碼而已,spring的IOC就是這樣的.
    例子:

    import java.lang.reflect.*;
    import java.util.*;

    public class PorxyTest {

     /**
      * @param args
      */
     public static void main(String[] args) {
      // TODO Auto-generated method stub
      Object[] elements = new Object[1000];
      
      for (int i = 0; i < elements.length; i ++) {
       Integer value = i + 1;
       Class[] interfaces = value.getClass().getInterfaces();
       InvocationHandler handler = new TraceHandler(value);
       Object proxy = Proxy.newProxyInstance(null, interfaces, handler);
       elements[i] = proxy;
      }
      Integer key = new Random().nextInt(elements.length) + 1;
      int result = Arrays.binarySearch(elements, key);
      
      if (result >= 0)
       System.out.println(elements[result]);
     }

    }

    class TraceHandler implements InvocationHandler {
     private Object target;
     public TraceHandler(Object t) {
      target = t;
     }
     
     public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
      System.out.print(target);
      System.out.print("." + m.getName() + "(");
      if (args != null) {
       for (int i = 0; i < args.length; i ++) {
        System.out.print(args[i]);
        if (i < args.length - 1) {
         System.out.print(",");
        }
       }
      }
      System.out.println(")");
      return m.invoke(target, args);
     }
    }

    posted @ 2007-05-24 14:57 liujg 閱讀(396) | 評論 (0)編輯 收藏

    java程序員的5個好習慣()

    http://today.java.net/pub/a/today/2006/08/24/five-habits-of-highly-profitable-developers.html


    Five Habits of Highly Profitable Software Developers Five Habits of Highly Profitable Software Developers

    by Robert J. Miller
    08/24/2006

    Software developers who have the ability to create and maintain quality software in a team environment are in high demand in today's technology-driven economy. The number one challenge facing developers working in a team environment is reading and understanding software written by another developer. This article strives to help software development teams overcome this challenge.

    This article illustrates five habits of software development teams that make them more effective and therefore more profitable. It first will describe the demands the business team puts on its software development team and the software they create. Next it will explain the important differences between state-changing logic and behavior logic. Finally, it will illustrate the five habits using a customer account scenario as a case study.

    Demands Placed on Developers by the Business

    The business team's job is to determine what new value can be added to the software, while ensuring that the new value is most advantageous to the business. Here, "new value" refers to a fresh product or additional enhancement to an existing product. In other words, the team determines what new features will make the business the most money. A key factor in determining what the next new value will be is how much it will cost to implement. If the cost of implementation exceeds the potential revenue, then the new value will not be added.

    The business team demands that the software development team be able to create new value at the lowest possible cost. It also demands that the software development team have the ability to add new value to a product without having the product's implementation costs increase over time. Furthermore, every time the business team requests new value, it demands that value be added without losing any existing value. Over time, the software will accrue enough value that the business team will demand documentation to describe the current value the software provides. Then the business team will use this documentation to help determine what the next new value will be.

    Software development teams can best meet these demands by creating easy-to-understand software. Difficult-to-understand software results in inefficiencies throughout the development process. These inefficiencies increase the cost of software development and can include the unexpected loss of existing value, an increase in developer ramp-up time, and the delivery of incorrect software documentation. These inefficiencies can be reduced by converting the business team's demands, even if complex, into simple, easy-to-understand software.

    Introducing Key Concepts: State and Behavior

    Creating software that is easy to understand starts by creating objects that have state and behavior. "State" is an object's data that persists between method calls. A Java object can hold its state temporarily in its instance variables and can persist it indefinitely by saving it into a permanent data store. Here, a permanent data store can be a database or Web service. "State-changing methods" typically manage an object's data by retrieving it and persisting it to and from a remote data store. "Behavior" is an object's ability to answer questions based on state. "Behavior methods" answer questions consistently without modifying state and are often referred to as the business logic in an application.

    Case Study: CustomerAccount object

    The following ICustomerAccount interface defines methods an object must implement to manage a customer's account. It defines the ability to create a new active account, to load an existing customer's account status, to validate a prospective customer's username and password, and to validate that an existing account is active for purchasing products.

    public interface ICustomerAccount {
    //State-changing methods
    public void createNewActiveAccount()
    throws CustomerAccountsSystemOutageException;
    public void loadAccountStatus()
    throws CustomerAccountsSystemOutageException;
    //Behavior methods
    public boolean isRequestedUsernameValid();
    public boolean isRequestedPasswordValid();
    public boolean isActiveForPurchasing();
    public String getPostLogonMessage();
    }

    Habit 1: Constructor Performs Minimal Work

    The first habit is for an object's constructor to do as little work as possible. Ideally, its constructor will only load data into its instance variables using the constructor's parameters. In the following example, creating a constructor that performs minimal work makes the object easier to use and understand because the constructor performs only the simple task of loading data into the object's instance variables:

    public class CustomerAccount implements ICustomerAccount{
    //Instance variables.
    private String username;
    private String password;
    protected String accountStatus;
    //Constructor that performs minimal work.
    public CustomerAccount(String username, String password) {
    this.password = password;
    this.username = username;
    }
    }

    A constructor is used to create an instance of an object. A constructor's name is always the same as the object's name. Since a constructor's name is unchangeable, its name is unable to communicate the work it is performing. Therefore, it is best if it performs as little work as possible. On the other hand, state-changing and behavior method names use descriptive names to convey their more complex intent, as described in "Habit 2: Methods Clearly Convey Their Intent." As this next example illustrates, the readability of the software is high because the constructor simply creates an instance of the object, letting the behavior and state-changing methods do the rest.

    Note: The use of "..." in the examples represents code that is necessary to run in a live scenario but is not relevant to the example's purpose.

    String username = "robertmiller";
    String password = "java.net";
    ICustomerAccount ca = new CustomerAccount(username, password);
    if(ca.isRequestedUsernameValid() && ca.isRequestedPasswordValid()) {
    ...
    ca.createNewActiveAccount();
    ...
    }

    On the other hand, objects with constructors that do more than just load instance variables are harder to understand and more likely to be misused because their names do not convey their intent. For example, this constructor also calls a method that makes a remote call to a database or Web service in order to pre-load an account's status:

    //Constructor that performs too much work!
    public CustomerAccount(String username, String password)
    throws CustomerAccountsSystemOutageException {
    this.password = password;
    this.username = username;
    this.loadAccountStatus();//unnecessary work.
    }
    //Remote call to the database or web service.
    public void loadAccountStatus()
    throws CustomerAccountsSystemOutageException {
    ...
    }

    A developer can use this constructor and, not realizing it is making a remote call, end up making two remote calls:

    String username = "robertmiller";
    String password = "java.net";
    try {
    //makes a remote call
    ICustomerAccount ca = new CustomerAccount(username, password);
    //makes a second remote call
    ca.loadAccountStatus();
    } catch (CustomerAccountsSystemOutageException e) {
    ...
    }

    Or a developer can reuse this constructor to validate a prospective customer's desired username and password and be forced to make an unnecessary remote call since these behavior methods (isRequestedUsernameValid(), isRequestedPasswordValid()) don't need the account status:

    String username = "robertmiller";
    String password = "java.net";
    try {
    //makes unnecessary remote call
    ICustomerAccount ca = new CustomerAccount(username, password);
    if(ca.isRequestedUsernameValid() && ca.isRequestedPasswordValid()) {
    ...
    ca.createNewActiveAccount();
    ...
    }
    } catch (CustomerAccountsSystemOutageException e){
    ...
    }

    Habit 2: Methods Clearly Convey Their Intent

    The second habit is for all methods to clearly convey their intent through the names they are given. For example, isRequestedUsernameValid() lets the developer know that this method determines whether or not the requested username is valid. In contrast, isGoodUser() can have any number of uses: it can determine if the user's account is active, determine if the requested username and/or password are valid, or determine if the user is a nice person. Since this method is less descriptive, it is more difficult for a developer to figure out what its purpose is. In short, it is better for the method names to be long and descriptive than to be short and meaningless.

    Long and descriptive method names help developer teams quickly understand the purpose and function of their software. Moreover, applying this technique to test method names allows the tests to convey the existing requirements of the software. For example, this software is required to validate that requested usernames and passwords are different. Using the method name testRequestedPasswordIsNotValidBecauseItMustBeDifferentThanTheUsername() clearly conveys the intent of the test and, therefore, the requirement of the software.

    import junit.framework.TestCase;
    public class CustomerAccountTest extends TestCase{
    public void testRequestedPasswordIsNotValid
    BecauseItMustBeDifferentThanTheUsername(){
    String username = "robertmiller";
    String password = "robertmiller";
    ICustomerAccount ca = new CustomerAccount(username, password);
    assertFalse(ca.isRequestedPasswordValid());
    }
    }

    This test method could have easily been named testRequestedPasswordIsNotValid() or even worse testBadPassword(), both of which would make it hard to determine the precise intention of the test. Unclear or ambiguously named test methods result in a loss of productivity. The loss in productivity can be caused by an increase in ramp-up time used to understand the tests, the unnecessary creation of duplicated or conflicting tests, or the destruction of existing value in the object being tested.

    Finally, descriptive method names reduce the need for both formal documentation and Javadoc comments.

    Habit 3: An Object Performs a Focused Set of Services

    The third habit is for each object in the software to be focused on performing a small and unique set of services. Objects that perform a small amount of work are easier to read and more likely to be used correctly because there is less code to digest. Moreover, each object in the software should perform a unique set of services because duplicating logic wastes development time and increases maintenance costs. Suppose in the future, the business team requests an update to the isRequestedPasswordValid() logic and two different objects have similar methods that perform the same work. In this case, the software development team would spend more time updating both objects than they would have had to spend updating just one.

    As the case study illustrates, the purpose of the CustomerAccount object is to manage an individual customer's account. It first creates the account and later can validate that the account is still active for purchasing products. Suppose in the future, this software will need to give discounts to customers who have purchased more than ten items. Creating a new interface, ICustomerTransactions, and object, CustomerTransactions, to implement these new features will facilitate the ongoing goal of working with easy-to-understand software:

    public interface ICustomerTransactions {
    //State-changing methods
    public void createPurchaseRecordForProduct(Long productId)
    throws CustomerTransactionsSystemException;
    public void loadAllPurchaseRecords()
    throws CustomerTransactionsSystemException;
    //Behavior method
    public void isCustomerEligibleForDiscount();
    }

    This new object holds state-changing and behavior methods that store customer transactions and determine when a customer gets its ten-product discount. It should be easy to create, test, and maintain since it has a simple and focused purpose. The less effective approach is to add these new methods to the existing ICustomerAccount interface and CustomerAccount object, as seen below:

    public interface ICustomerAccount {
    //State-changing methods
    public void createNewActiveAccount()
    throws CustomerAccountsSystemOutageException;
    public void loadAccountStatus()
    throws CustomerAccountsSystemOutageException;
    public void createPurchaseRecordForProduct(Long productId)
    throws CustomerAccountsSystemOutageException;
    public void loadAllPurchaseRecords()
    throws CustomerAccountsSystemOutageException;
    //Behavior methods
    public boolean isRequestedUsernameValid();
    public boolean isRequestedPasswordValid();
    public boolean isActiveForPurchasing();
    public String getPostLogonMessage();
    public void isCustomerEligibleForDiscount();
    }

    As seen above, allowing objects to become large repositories of responsibility and purpose makes them harder to read and more likely to be misunderstood. Misunderstandings result in a loss in productivity, costing the business team time and money. In short, it is better for objects and their methods to be focused on performing a small unit of work.

    Habit 4: State-Changing Methods Contain Minimal Behavior Logic

    The fourth habit is for state-changing methods to contain a minimal amount of behavior logic. Intermixing state-changing logic with behavior logic makes the software more difficult to understand because it increases the amount of work happening in one place. State-changing methods typically retrieve or send data to a remote data store and, therefore, are prone to have problems in the production system. Diagnosing a system problem within a state-changing method is easier when the remote call is isolated and it has zero behavior logic. Intermixing also inhibits the development process because it makes it harder to unit test the behavior logic. For example, getPostLogonMessage() is a behavior method with logic based on the accountStatus's value:

    public String getPostLogonMessage() {
    if("A".equals(this.accountStatus)){
    return "Your purchasing account is active.";
    } else if("E".equals(this.accountStatus)) {
    return "Your purchasing account has " +
    "expired due to a lack of activity.";
    } else {
    return "Your purchasing account cannot be " +
    "found, please call customer service "+
    "for assistance.";
    }
    }

    loadAccountStatus() is a state-changing method that loads the accountStatus's value from a remote data store:

    public void loadAccountStatus()
    throws CustomerAccountsSystemOutageException {
    Connection c = null;
    try {
    c = DriverManager.getConnection("databaseUrl", "databaseUser",
    "databasePassword");
    PreparedStatement ps = c.prepareStatement(
    "SELECT status FROM customer_account "
    + "WHERE username = ? AND password = ? ");
    ps.setString(1, this.username);
    ps.setString(2, this.password);
    ResultSet rs = ps.executeQuery();
    if (rs.next()) {
    this.accountStatus=rs.getString("status");
    }
    rs.close();
    ps.close();
    c.close();
    } catch (SQLException e) {
    throw new CustomerAccountsSystemOutageException(e);
    } finally {
    if (c != null) {
    try {
    c.close();
    } catch (SQLException e) {}
    }
    }
    }

    Unit testing the getPostLogonMessage() method can easily be done by mocking the loadAccountStatus() method. Each scenario can then be tested without making a remote call to a database. For example, if the accountStatus is "E" for expired, then getPostLogonMessage() should return "Your purchasing account has expired due to a lack of activity," as follows:

    public void testPostLogonMessageWhenStatusIsExpired(){
    String username = "robertmiller";
    String password = "java.net";
    class CustomerAccountMock extends CustomerAccount{
    ...
    public void loadAccountStatus() {
    this.accountStatus = "E";
    }
    }
    ICustomerAccount ca = new CustomerAccountMock(username, password);
    try {
    ca.loadAccountStatus();
    }
    catch (CustomerAccountsSystemOutageException e){
    fail(""+e);
    }
    assertEquals("Your purchasing account has " +
    "expired due to a lack of activity.",
    ca.getPostLogonMessage());
    }

    The inverse approach is to put both the getPostLogonMessage() behavior logic and the loadAccountStatus() state-changing work into one method. The following example illustrates what not to do:

    public String getPostLogonMessage() {
    return this.postLogonMessage;
    }
    public void loadAccountStatus()
    throws CustomerAccountsSystemOutageException {
    Connection c = null;
    try {
    c = DriverManager.getConnection("databaseUrl", "databaseUser",
    "databasePassword");
    PreparedStatement ps = c.prepareStatement(
    "SELECT status FROM customer_account "
    + "WHERE username = ? AND password = ? ");
    ps.setString(1, this.username);
    ps.setString(2, this.password);
    ResultSet rs = ps.executeQuery();
    if (rs.next()) {
    this.accountStatus=rs.getString("status");
    }
    rs.close();
    ps.close();
    c.close();
    } catch (SQLException e) {
    throw new CustomerAccountsSystemOutageException(e);
    } finally {
    if (c != null) {
    try {
    c.close();
    } catch (SQLException e) {}
    }
    }
    if("A".equals(this.accountStatus)){
    this.postLogonMessage = "Your purchasing account is active.";
    } else if("E".equals(this.accountStatus)) {
    this.postLogonMessage = "Your purchasing account has " +
    "expired due to a lack of activity.";
    } else {
    this.postLogonMessage = "Your purchasing account cannot be " +
    "found, please call customer service "+
    "for assistance.";
    }
    }

    In this implementation the behavior method getPostLogonMessage() contains zero behavior logic and simply returns the instance variable this.postLogonMessage. This implementation creates three problems. First, it makes it more difficult to understand how the "post logon message" logic works since it is embedded in a method performing two tasks. Second, the getPostLogonMessage() method's reuse is limited because it must always be used in conjunction with the loadAccountStatus() method. Finally, in the event of a system problem the CustomerAccountsSystemOutageException will be thrown, causing the method to exit before it sets this.postLogonMessage's value.

    This implementation also creates negative side effects in the test because the only way to unit test this getPostLogonMessage() logic is to create a CustomerAccount object with a username and password for an account in the database with an accountStatus set to "E" for expired. The result is a test that makes a remote call to a database. This causes the test to run slower and to be prone to unexpected failures due to changes in the database. This test has to make a remote call to a database because the loadAccountStatus() method also contains the behavior logic. If the behavior logic is mocked, then the test is testing the mocked object's behavior instead of the real object's behavior.

    Habit 5: Behavior Methods Can Be Called in Any Order

    The fifth habit is to ensure that each behavior method provides value independent of any other behavior method. In other words, an object's behavior methods can be called repeatedly and in any order. This habit allows the object to deliver consistent behavior. For example, CustomerAccount's isActiveForPurchasing() and getPostLogonMessage() behavior methods both use the accountStatus's value in their logic. Each of these methods should be able to function independently of the other. For instance, one scenario can require that isActiveForPurchasing() be called, followed by a call to getPostLogonMessage():

    ICustomerAccount ca = new CustomerAccount(username, password);
    ca.loadAccountStatus();
    if(ca.isActiveForPurchasing()){
    //go to "begin purchasing" display
    ...
    //show post logon message.
    ca.getPostLogonMessage();
    } else {
    //go to "activate account" display
    ...
    //show post logon message.
    ca.getPostLogonMessage();
    }

    A second scenario can require that getPostLogonMessage() is called without isActiveForPurchasing() ever being called:

    ICustomerAccount ca = new CustomerAccount(username, password);
    ca.loadAccountStatus();
    //go to "welcome back" display
    ...
    //show post logon message.
    ca.getPostLogonMessage();

    The CustomerAccount object will not support the second scenario if getPostLogonMessage() requires isActiveForPurchasing() to be called first. For example, creating the two methods to use a postLogonMessage instance variable so that its value can persist between method calls supports the first scenario but not the second:

    public boolean isActiveForPurchasing() {
    boolean returnValue = false;
    if("A".equals(this.accountStatus)){
    this.postLogonMessage = "Your purchasing account is active.";
    returnValue = true;
    } else if("E".equals(this.accountStatus)) {
    this.postLogonMessage = "Your purchasing account has " +
    "expired due to a lack of activity.";
    returnValue = false;
    } else {
    this.postLogonMessage = "Your purchasing account cannot be " +
    "found, please call customer service "+
    "for assistance.";
    returnValue = false;
    }
    return returnValue;
    }
    public String getPostLogonMessage() {
    return this.postLogonMessage;
    }

    On the other hand, if both methods derive their logic independently of each other, then they will support both scenarios. In this preferred example, postLogonMessage is a local variable created exclusively by the getPostLogonMessage() method:

    public boolean isActiveForPurchasing() {
    return this.accountStatus != null && this.accountStatus.equals("A");
    }
    public String getPostLogonMessage() {
    if("A".equals(this.accountStatus)){
    return "Your purchasing account is active.";
    } else if("E".equals(this.accountStatus)) {
    return "Your purchasing account has " +
    "expired due to a lack of activity.";
    } else {
    return "Your purchasing account cannot be " +
    "found, please call customer service "+
    "for assistance.";
    }
    }

    An added benefit of making these two methods independent of each other is that the methods are easier to comprehend. For example, isActiveForPurchasing() is more readable when it is only trying to answer the "is active for purchasing" question as opposed to when it is also trying to set the "post logon message". Another added benefit is that each method can be tested in isolation, which also makes the tests easier to comprehend:

    public class CustomerAccountTest extends TestCase{
    public void testAccountIsActiveForPurchasing(){
    String username = "robertmiller";
    String password = "java.net";
    class CustomerAccountMock extends CustomerAccount{
    ...
    public void loadAccountStatus() {
    this.accountStatus = "A";
    }
    }
    ICustomerAccount ca = new CustomerAccountMock(username, password);
    try {
    ca.loadAccountStatus();
    } catch (CustomerAccountsSystemOutageException e) {
    fail(""+e);
    }
    assertTrue(ca.isActiveForPurchasing());
    }
    public void testGetPostLogonMessageWhenAccountIsActiveForPurchasing(){
    String username = "robertmiller";
    String password = "java.net";
    class CustomerAccountMock extends CustomerAccount{
    ...
    public void loadAccountStatus() {
    this.accountStatus = "A";
    }
    }
    ICustomerAccount ca = new CustomerAccountMock(username, password);
    try {
    ca.loadAccountStatus();
    } catch (CustomerAccountsSystemOutageException e) {
    fail(""+e);
    }
    assertEquals("Your purchasing account is active.",
    ca.getPostLogonMessage());
    }
    }

    Conclusion

    Following these five habits will help development teams create software that everyone on the team can read, understand, and modify. When software development teams create new value too quickly and without consideration for the future, they tend to create software with increasingly high implementation costs. Inevitably, bad practices will catch up to these teams when they have to revisit the software for future comprehension and modification. Adding new value to existing software can be very expensive if the software is difficult to comprehend. However, when development teams apply these best practices, they will provide new value at the lowest possible cost to their business team.

     


    posted @ 2006-12-15 17:27 liujg 閱讀(804) | 評論 (0)編輯 收藏

    <2006年12月>
    262728293012
    3456789
    10111213141516
    17181920212223
    24252627282930
    31123456

    導航

    統(tǒng)計

    常用鏈接

    留言簿(1)

    隨筆分類

    隨筆檔案

    文章分類

    文章檔案

    相冊

    收藏夾

    boddiy

    搜索

    最新評論

    閱讀排行榜

    評論排行榜

    主站蜘蛛池模板: 免费人成网站在线观看10分钟| 亚洲国产综合久久天堂| 亚洲国产精品自在自线观看| 亚洲成a人无码av波多野按摩| 嫩草成人永久免费观看| 亚洲人成自拍网站在线观看| 久久影视综合亚洲| 免费国产成人高清在线观看网站| 麻豆va在线精品免费播放| 亚洲第一福利视频| 免费中文字幕不卡视频| 在线观看免费av网站| 又爽又高潮的BB视频免费看| 免费人成在线观看视频高潮| 亚洲欧美日韩久久精品| 亚洲AV永久无码精品一百度影院| 99视频在线精品免费观看6| 免费看黄的成人APP| 亚洲色偷偷色噜噜狠狠99网| 亚洲国产三级在线观看| 国产自产拍精品视频免费看| 亚洲一级免费毛片| 久久国产美女免费观看精品| 中文字幕在线日亚洲9| 在线免费观看国产视频| 日韩免费电影网站| 人成电影网在线观看免费| 国产精品亚洲аv无码播放| 国产精品久久香蕉免费播放| 1区2区3区产品乱码免费| 精品国产成人亚洲午夜福利| 久久精品视频亚洲| 超清首页国产亚洲丝袜| 日本牲交大片免费观看| 免费毛片a在线观看67194| 国产精品免费看久久久| 巨胸狂喷奶水视频www网站免费| 亚洲aⅴ天堂av天堂无码麻豆| 亚洲日本视频在线观看| 国产又黄又爽又猛的免费视频播放| 亚洲视频免费播放|