??xml version="1.0" encoding="utf-8" standalone="yes"?> 关于LINUX权限-bash: ./startup.sh: Permission denied 在执?/startup.sh,或?/shutdown.sh的时候,爆出了Permission deniedQ?/p> 其实很简单,是今天在执行tomcat的时候,用户没有权限Q而导致无法执行, 用命令chmod 修改一下bin目录下的.sh权限可以了 如chmod u+x *.sh 在此执行QOK了?/p> 最q在开发中遇到了表单提交前验证的问题,用一个普通的button按钮代替submit按钮Q?br />在提交前触发q个button的onclick事gQ在其事件中触发form的submit事g。问题出CQ?br />以下是出现相关代码: 意思是说submitq个Ҏ(gu)是不触发onsubmit旉的,如果惌触发它,需要调?br />fireEventҎ(gu)。尝试一下:this.form.fireEvent('onsubmit');哈哈Q果然也成功Q不q这样不是多此一丑Q呵呵! p个小问题也搞了我近一个小Ӟ不过Z以后不ؓq个问题烦恼Q这也是值得的?br />this.form.submit(); //直接提交表单 2.onsubmit()与submit() Q?/p>
<sCript> <form onsubmit="fun()"> <!--会触发fun()参数--> service()是在javax.servlet.Servlet接口中定义的, ?javax.servlet.GenericServlet 中实Cq个接口, ?doGet/doPost 则是?javax.servlet.http.HttpServlet 中实现的, javax.servlet.http.HttpServlet ?javax.servlet.GenericServlet 的子c? 所有可以这L? 其实所有的h均首先由 service() q行处理, 而在 javax.servlet.http.HttpServlet ?service() Ҏ(gu)? 主要做的事情是判断hcd?Get q是 Post, 然后调用对应?doGet/doPost 执行. doGetQ处理GETh doPostQ处理POSTh doPutQ处理PUTh doDeleteQ处理DELETEh doHeadQ处理HEADh doOptionsQ处理OPTIONSh doTraceQ处理TRACEh 通常情况下,在开发基于HTTP的servletӞ开发者只需要关心doGet和doPostҎ(gu)Q其它的Ҏ(gu)需要开发者非常的熟?zhn)HTTP~程Q因此这些方法被认ؓ是高U方法?而通常情况下,我们实现的servlet都是从HttpServlet扩展而来?doPut和doDeleteҎ(gu)允许开发者支持HTTP/1.1的对应特性; doHead是一个已l实现的Ҏ(gu)Q它?yu)执行doGet但是仅仅向客Lq回doGet应该向客Lq回的头部的内容Q?doOptionsҎ(gu)自动的返回servlet所直接支持的HTTPҎ(gu)信息Q?doTraceҎ(gu)q回TRACEh中的所有头部信息?对于那些仅仅支持HTTP/1.0的容器而言Q只有doGet, doHead ?doPostҎ(gu)被用,因ؓHTTP/1.
]]>
<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">条型?lt;/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('定要提交吗Q?))) this.form.submit();"/>
</td>
</tr>
</table>
</form>
却发现ƈ没有触发form的onsubmitҎ(gu)Q而是直接提交了。奇怪了Q难道没有这U方式无法结合form的onsubmitҎ(gu)吗?
仔细想了惻I既然this.form表示formq个对象Q那么肯定能获取到form的属性和Ҏ(gu)?br />Q就Ҏ(gu)this.form.onsubmit(); 成功Q?br />我又查了查手册,原来submit的方法是q样解释的:
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.
this.form.onsubmit(); //调用form的onsubmitҎ(gu)
this.form.fireEvent('onsubmit'); //同上,
PS:又学CfireEventq个Ҏ(gu)Q?/p>
funCtion fun()
{
alert("form_submit");
}
</sCript>
<input type="submit" id="aaa" value="submit"> <!--能弹出form_submit-->
<input type="button" id="bbb" value="onCliCk_submit" onCliCk="doCument.forms[0].submit()">
<!--
表单会提交,但是不会q行fun() 原因?onsubmit事g不能通过此种方式触发Q在IE环境Q?br />直接用脚本doCumetn.formName.submit()提交表单是不会触发表单的onsubmit()事g?br />-->
<input type="button" id="bb1" value="onCliCk_onsubmit" onCliCk="doCument.forms[0].onsubmit()">
</form>
]]>
1.doGet和doPost的区别,在什么时候调用,Z么有时doPost中套用doGet
2.提交的form method=Post执行DOPOSTQ否则执行GOGET 套用是不method是postq是get都执行dopostҎ(gu)
3.get:你可以通过URL传参数?/font>http://www.csdn.net/index.asp?user=1234 , Post不行
4.你的表单提交都有Ҏ(gu)?如果提交为getp用getҎ(gu),用postp用postҎ(gu).
get昄你传q去的参?post则不昄.
5.通常的写法:先用doGet(),然后在doPost()中调用doGet(),q样׃无一׃
6. 单的_get是通过http header来传输数据,有数量限Ӟ而post则是通过http body来传输数据,没有数量限制?br />7.q有一?get和post提交的数据量是不一L.
get好像最多只能在url后跟64K(?具体多少忘记?,
post好像没这个限?臛_我postq?M以上的文?nbsp;
q有urlh时get好像可以不用重复提交原来提交的数?
而post则会说内容已提交,惛_新请再提?
]]>
说明Q以下黑色ؓvi和vim均有的一般功能,而红色ؓVimQVi ImprovedQ所Ҏ(gu)功能。Vim一般的Unix和Linux下均有安装?br />
?三种状?br />
CommandQ?M输入都会作ؓ~辑命oQ而不会出现在屏幕上,M输入都引L卛_?br />
InsertQ?M输入的数据都|于~辑寄存器,按ESCQ可跛_command方式
EscapeQ??#8220;Q?#8221;或?#8220;/”为前导的指oQ出现在屏幕的最下一行,M输入都被当成特别指o?br />
?dvi
:q! dviQƈ攑ּ刚在~冲区内~辑的内宏V?br />
:wq 缓冲区内的资料写入盘中,q离开vi?br />
:x 同wq?br />
Q注意—?:X 是文件加密,一定要?x存盘退出相区别Q?br />
?q入输入模式
a (append) 由游标之后加入资料?br />
A p行之末加入资料?br />
i (insert) 由游标之前加入资料?br />
I p行之首加入资料?br />
o (open) 新增一行於该行之下供输入资料之用?br />
O 新增一行於该行之上供输入资料之用?br />
?删除与修?br />
x 删除游标所在该字元?br />
X 删除游标所在之前一字元?br />
r 用接於此指o之后的字元取?replace)游标所在字元。如Qra游标所在字元以 a 取代之?br />
R q入取代状态,直到《ESC》ؓ止?br />
s 删除游标所在之字元Qƈq入输入模式直到《ESC》?br />
S 删除游标所在之该行资料Qƈq入输入模式直到《ESC》?br />
?光标的移?br />
m<a-z> 讄书签<a-z>
‘<a-z> U至书签<a-z>?br />
0 U至该行之首
$ U至该行之末?br />
e UdC个字的最後一个字?br />
w UdC个字的第一个字母?br />
b UdC个字的第一个字母?br />
^ U至该行的第一个字元处?br />
H U至视窗的第一行?br />
M U至视窗的中间那行?br />
L U至视窗的最后一行?br />
G U至该文件的最后一行?br />
+ U至下一列的W一个字元处?br />
- U至上一列的W一个字元处?br />
:n U至该文件的W?n 列?br />
n+ U至游标所在位|之后的W?n 列?br />
n- U至游标所在位|之前的W?n 列?br />
<Ctrl><g> 昄该行之行受文件名U、文件中最末行之行受游标所在行号占总行号之癑ֈ比?/p>
QVimQ?光标Ud基本用法解Q?br />
(q只要组合上边的功能可以明白了Q不用再一一讲解了吧Q?
ge b w e
← ← ---→ --→
This is-a line, with special/separated/words (and some more).
←- ←-- -----------------→ ---→
GE B W E
?视窗的移?br />
<Ctrl><f> 视窗往下卷一c?br />
<Ctrl><b> 视窗往上卷一c?br />
<Ctrl><d> 视窗往下卷半页?br />
<Ctrl><u> 视窗往上卷半页?br />
<Ctrl><e> 视窗往下卷一行?br />
<Ctrl><y> 视窗往上卷一行?br />
?剪切、复制、删?br />
Operator + Scope = command
?Operator
d 剪切
y 复制?br />
p _帖Q与 d ?y 配和使用。可最后d或y的资料放|於游标所在位|之行列下?br />
c 修改Q类似delete与insert的组和。删除一个字l、句子等之资料,q插入新料?br />
?Scope
e 由游标所在位|至该字串的最后一个字元?br />
w 由游标所在位|至下一个字串的W一个字元?br />
b 由游标所在位|至前一个字串的W一个字元?br />
$ 由游标所在位|至该行的最后一个字元?br />
0 由游标所在位|至该行的第一个字元?br />
?整行动作
dd 删除整行?br />
D 以行为单位,删除游标后之所有字元?br />
cc 修改整行的内宏V?br />
yy 使游标所在该行复制到记忆体缓冲区?br />
?取消前一动作(Undo)
u 恢复最后一个指令之前的l果?br />
U 恢复游标该行之所有改变?br />
(vim) u 可以多次撤消指oQ一ơ撤消一个操作,直至本次操作开始ؓ止?br />
(vim) Ctrl+r 可以恢复撤消前内容,按多ơ可恢复多次?br />
?查找与替?br />
/字串 往游标之后L该字丌Ӏ?br />
?字串 往游标之前L该字丌Ӏ?br />
n 往下l寻找下一个相同的字串?br />
N 往上l寻找下一个相同的字串?br />
% 查找“(”Q?#8220;)”Q?#8220;{”Q?#8220;}”的配对符?br />
s 搜寻某行列范围?br />
g 搜寻整个~辑~冲区的资料?br />
:1,$s/old/new/g 文件中所有的『old』改成『new』?br />
:10,20s/^/ / 第10行至W?0行资料的最前面插入5个空白?br />
(vim)
/字符?后边输入查询内容可保存至~冲ZQ可?#8593;↓q行以往内容选择?br />
另外Q将光标Ud在选定单词下方?Q则可以选中此单词作为查询字W,可以避免输入一长串字符的麻烦?br />
?(vim) 大小写替?br />
首先用按v开启选择功能Q然后用↑↓←→键来选定所要替换的字符Q若是小写变大写Q则按U;反之按u;
如果是选择单词Q则可以在按v后,按wQ最后按U/u,q样可以将字符随意的改变大写了,而不用删除后重新敲入?/p>
?资料的连?br />
J 句子的连接。将游标所在之下一行连接至游标该行的后面?br />
?环境的设?br />
:set all 可设|的环境变量列表
:set 环境变量的当前?br />
:set nu 讑֮资料的行受?br />
:set nonu 取消行号讑֮?br />
:set ai 自动内羃?br />
:set noai 取消自动内羃?br />
(vim)
:set ruler 会在屏幕右下角显C当前光标所处位|,q光移动而改变,占用屏幕I间较小Q用也比较方便Q推荐用?br />
:set hlsearch 在用查扑֊能时Q会高亮昄所有匹配的内容?br />
:set nohlsearch 关闭此功能?br />
:set incsearch 使Vim在输入字W串的过E中Q光标就可定位显C匹配点?br />
:set nowrapscan 关闭查找自动回环功能Q即查找到文件结֤Q结束查找;默认状态是自动回环
?ex指o
?d资料
:10,20w test 第10行至W?0行的资料写入test文g?br />
:10,20w>>test 第10行至W?0行的资料加在test文g之后?br />
:r test test文g的资料读入编辑缓冲区的最后?br />
:e [filename] ~辑新的文g?br />
:e! [filename] 攑ּ当前修改的文Ӟ~辑新的文g?br />
:sh q入shell环境Q用exit退出,回到~辑器中?/p>
:!cmd q行命ocmd后,q回到编辑器中?br />
?删除、复制及搬移
:10,20d 删除W?0行至W?0行的资料?br />
:10d 删除W?0行的资料?br />
:%d 删除整个~辑~冲区?br />
:10,20co30 第10行至W?0行的资料复制至第30行之后?br />
:10,20mo30 第10行至W?0行的资料搬移至第30行之后?/p>
本文来自CSDN博客Q{载请标明出处Qhttp://blog.csdn.net/jsufcz/archive/2009/02/11/3875956.aspx
文章出处Q飞诺网(www.firnow.com):http://dev.firnow.com/course/7_databases/oracle/oraclejs/20091103/181042.html
定义:
用原型实例指定创建对象的U类,q且通过拯q些原型创徏新的对象. //通过拯创徏新的对象跟通过l承创徏有什么区别呢Q?br /> Prototype 模式允许一个对象再创徏另外一个可定制的对象,Ҏ(gu)无需知道M如何创徏?
l节,工作原理?通过一个原型对象传l那个要发动创徏的对象,q个要发动创建的对象
通过h原型对象拯它们自己来实施创建?
如何使用?
因ؓJava 中的提供clone()Ҏ(gu)来实现对象的克隆(具体了解 clone()按这?,所?
Prototype 模式实现一下子变得很简?
以勺子ؓ例:
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;
}
}
有两个具体实?ConcretePrototype):
public class SoupSpoon extends AbstractSpoon
{
public SoupSpoon()
{
setSpoonName("Soup Spoon");
}
}
public class SaladSpoon extends AbstractSpoon
{
public SaladSpoon()
{
setSpoonName("Salad Spoon");
}
}
调用 Prototype 模式很简?
AbstractSpoon spoon = new SoupSpoon();
AbstractSpoon spoon = new SaladSpoon();
/**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
q个E序的GUI版本?br>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);
}
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);
}
}
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.
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.
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.
CustomerAccount
objectThe 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();
}
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){
...
}
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.
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.
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.
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());
}
}
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.