2011年7月18日
每当提到Exeption就会有人跳出来说“Exception not use for flow control”,那到底是什么意思呢?什么情况下Exception就算控制流程了,什么时候就该抛出Exception了呢?
首先什么是Exception?
Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
再看什么是“流程”?如果流程是指程序的每一步执行,那异常就是控制流程的,它就是用来区分程序的正常流程和非正常流程的,从上面异常的定义就可以看出。因此为了明确我们应该说”不要用异常控制程序的正常流程“。如何定义正常流程和非正常流程很难,这是一个主观的决定,没有一个统一的标准,只能根据实际情况。网上找个例子:
bool isDouble(string someString) {
try {
double d = Convert.ParseInt32(someString);
} catch(FormatException e) {
return false;
}
return true;
}
这个程序其实不是想convert数字,而是想知道一个字符串是否包含一个数字,通过判断是不是有异常的方式来决定返回true还是false,这是个Smell,这种应该算”异常控制了正常流程“。我们可以通过正则表达式或其他方式来判断。
另外Clean Code上一个例子:
try {
MealExpenses expenses = expenseReportDAO.getMeals(employee.getID());
m_total += expenses.getTotal();
} catch(MealExpensesNotFound e) {
m_total += getMealPerDiem();
}
MealExpensesNotFound异常影响了正常的计算m_total的业务逻辑。对于这种情况可以通过一下方式改进:
public class PerDiemMealExpenses implements MealExpenses {
public int getTotal() {
// return the per diem default
}
}
以上两个例子是比较明显的异常控制正常流程,Smell很明显,不会有很大争议,但是实际情况中可能有很多例子没有这么明显,因为都是主观判定的。比如一下代码,算不算异常控制正常流程?
public int doSomething()
{
doA();
try {
doB();
} catch (MyException e) {
return ERROR;
}
doC();
return SUCCESS;
}
看到这样一段程序,如果没有上下文,我们无法判断。但是如果doSomething是想让我们回答yes or no,success or error,我们不应该通过有无异常来判断yes or no,success or error,应该有个单独的方法来判断,这个方法就只做这一件事情。如果doSometing是执行一个操作,那么在这个过程中我们假定是不会出现问题的,否则抛出异常是比较合理的。
1. Java Class Loading Mechanism
首先当编译一个Java文件时,编译器就会在生成的字节码中内置一个public,static,final的class字段,该字段属于java.lang.Class类型,该class字段使用点来访问,所以可以有:
java.lang.Class clazz = MyClass.class
当class被JVM加载,就不再加载相同的class。class在JVM中通过(ClassLoader,Package,ClassName)来唯一决定。ClassLoader指定了一个class的scope,这意味着如果两个相同的包下面的class被不同的ClassLoader加载,它们是不一样的,并且不是type-compatible的。
JVM中所有的ClassLoader(bootstrap ClassLoader除外)都是直接或间接继承于java.lang.ClassLoader抽象类,并且人为逻辑上指定了parent-child关系,实现上child不一定继承于parent,我们也可以通过继承它来实现自己的ClassLoader。
JVM ClassLoder架构,从上到下依次为parent-child关系:
- Bootstrap ClassLoader - 启动类加载器,主要负责加载核心Java类如java.lang.Object和其他运行时所需class,位于JRE/lib目录下或-Xbootclasspath指定的目录。我们不知道过多的关于Bootstrap ClassLoader的细节,因为它是一个native的实现,不是Java实现,所以不同JVMs的Bootstrap ClassLoader的行为也不尽相同。调用java.lang.String.getClassLoder() 返回null。
- sun.misc.ExtClassLoader - 扩展类加载器,负责加载JRE/lib/ext目录及-Djava.ext.dirs指定目录。
- sun.misc.AppClassLoader - 应用类加载器,负责加载java.class.path目录
另外,还有一些其他的ClassLoader如:
java.net.URLClassLoader,java.security.SecureClassLoader,java.rmi.server.RMIClassLoader,sun.applet.AppletClassLoader
- 用户还可以自己继承java.lang.ClassLoader来实现自己的ClassLoader,用来动态加载class文件。
ClassLoader特性:
- 每个ClassLoader维护一份自己的命名空间,同一个ClassLoader命名空间不能加载两个同名的类。
- 为实现Java安全沙箱模型,默认采用parent-child加载链结构,除Bootstrap ClassLoader没有parent外,每个ClassLoader都有一个逻辑上的parent,就是加载这个ClassLoader的ClassLoader,因为ClassLoader本身也是一个类,直接或间接的继承java.lang.ClassLoader抽象类。
java.lang.Thread中包含一个public的方法public ClassLoader getContextClassLoader(),它返回某一线程相关的ClassLoader,该ClassLoader是线程的创建者提供的用来加载线程中运行的classes和资源的。如果没有显式的设置其ClassLoader,默认是parent线程的Context ClassLoader。Java默认的线程上下文加载器是AppClassLoader。
ClassLoader工作原理:
了解ClassLoader工作原理,先来看一个ClassLoader类简化版的loadClass()方法源码
1 protected Class<?> loadClass(String name, boolean resolve)
2 throws ClassNotFoundException
3 {
4 synchronized (getClassLoadingLock(name)) {
5 // First, check if the class has already been loaded
6 Class c = findLoadedClass(name);
7 if (c == null) {
8 long t0 = System.nanoTime();
9 try {
10 if (parent != null) {
11 c = parent.loadClass(name, false);
12 } else {
13 c = findBootstrapClassOrNull(name);
14 }
15 } catch (ClassNotFoundException e) {
16 // ClassNotFoundException thrown if class not found
17 // from the non-null parent class loader
18 }
19
20 if (c == null) {
21 // If still not found, then invoke findClass in order
22 // to find the class.
24 c = findClass(name);
25 }
26 }
27 if (resolve) {
28 resolveClass(c);
29 }
30 return c;
31 }
32 }
首先查看该class是否已被加载,如果已被加载则直接返回,否则调用parent的loadClass来加载,如果parent是null代表是Bootstrap ClassLoader,则有Bootstrap ClassLoader来加载,如果都未加载成功,最后由该ClassLoader自己加载。这种parent-child委派模型,保证了恶意的替换Java核心类不会发生,因为如果定义了一个恶意java.lang.String,它首先会被JVM的Bootstrap ClassLoader加载自己JRE/lib下的,而不会加载恶意的。另外,Java允许同一package下的类可以访问受保护成员的访问权限,如定义一个java.lang.Bad,但是因为java.lang.String由Bootstrap ClassLoader加载而java.lang.Bad由AppClassLoader加载,不是同一ClassLoader加载,仍不能访问。
2. Hotswap - 热部署
即不重启JVM,直接替换class。因为ClassLoader特性,同一个ClassLoader命名空间不能加载两个同名的类,所以在不重启JVM的情况下,只能通过新的ClassLoader来重新load新的class。
1 public static void main(String[] args) throws InterruptedException, MalformedURLException {
2 IExample oldExample = new Example();
3 oldExample.plus();
4 System.out.println(oldExample.getCount());
5
6 Hotswap hotswap = new Hotswap();
7 while (true) {
8 IExample newExample = hotswap.swap(oldExample);
9 String message = newExample.message();
10 int count = newExample.plus();
11 System.out.println(message.concat(" : " + count));
12 oldExample = newExample;
13 Thread.sleep(5000);
14 }
15 }
16
利用hotswap替换就的Example,每5秒钟轮询一次,swap方法实现如下:
1 private IExample swap(IExample old) {
2 try {
3 String sourceFile = srcPath().concat("Example.java");
4 if (isChanged(sourceFile)) {
5 comiple(sourceFile, classPath());
6 MyClassLoader classLoader = new MyClassLoader(new URL[]{new URL("file:"+classPath())});
7 Class<?> clazz = classLoader.loadClass("Example");
8 System.out.println(IExample.class.getClassLoader());
9 IExample exampleInstance = ((IExample) clazz.newInstance()).copy(old);
10 System.out.println(exampleInstance.getClass().getClassLoader());
11 return exampleInstance;
12 }
13 } catch ...
24 return old;
25 }
这里必须将exampleInstance转型为IExample接口而不是Exmaple,否则会抛出ClassCastExecption,这是因为swap方法所在类Hotswap是有AppClassLoader加载的,而且加载Hotswap的同时会加载该类引用的Exmaple的symbol link,而Example是MyClassLoader加载的,不同的ClassLoader加载的类之间直接用会抛出ClassCastException, 在本例中ClassLoader实现如下:
1 public class MyClassLoader extends URLClassLoader {
2
3 public MyClassLoader(URL[] urls) {
4 super(urls);
5 }
6
7 @Override
8 public Class<?> loadClass(String name) throws ClassNotFoundException {
9 if ("Example".equals(name)) {
10 return findClass(name);
11 }
12 return super.loadClass(name);
13 }
14 }
而对IExample我们还是调用super的loadClass方法,该方法实现仍是JVM的parent-child委派方式,因此最终由AppClassLoader加载,加载Hotswap时加载的symbol link也是由AppClassLoader加载的,因此能够成功。
此外再热部署时,被替换的类的所有引用及状态都要迁移到新的类上,本例中只是很简单的调用copy函数迁移了count的状态。
Tomcat的jsp热部署机制就是基于ClassLoader实现的,对于其类的热部署机制是通过修改内存中的class字节码实现的。
Resource:
1. java.lang.IllegalThreadStateException: process hasn't exited1 public static void main(String[] args) {
2 try {
3 Process process = Runtime.getRuntime().exec("javac");
4 System.out.println(process.exitValue());
5 } catch (IOException e) {
6 e.printStackTrace();
7 }
8 }
exec方法创建了一个native的进程,并返回该process的对象,如果进程还没有返回,调用exitValue方法就会出现此异常,因为该方法没有阻塞,其实现如下:
1 public synchronized int exitValue() {
2 if (!hasExited) {
3 throw new IllegalThreadStateException("process hasn't exited");
4 }
5 return exitcode;
6 }
2. waitFor方法
1 public static void main(String[] args) {
2 try {
3 Process process = Runtime.getRuntime().exec("javac");
4 int result = process.waitFor();
5 System.out.println(result);
6 } catch (IOException e) {
7 e.printStackTrace();
8 } catch (InterruptedException e) {
9 e.printStackTrace();
10 }
11 }
waitFor方法会一直阻塞直到native进程完成,并返回native进程的执行结果。如果native进程无法执行完成,waitFor方法将一直阻塞下去,其实现如下:
1 public synchronized int waitFor() throws InterruptedException {
2 while (!hasExited) {
3 wait();
4 }
5 return exitcode;
6 }
该程序在jdk1.7 windows下测试工作正常,返回2; 但是jdk1.4 windows下测试出现hang。JDK documention的解释是
The methods that create processes may not work well for special processes on certain native platforms,
such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows,or shell scripts.
The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr)
operations will be redirected to the parent process through three streams (getOutputStream(), getInputStream(),
getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams,
failure to promptly write the input stream or read the output stream of the subprocess may cause
the subprocess to block, and even deadlock.
所以,出现hang时,及时的flush标准输入输出或者错误流能够消除hang,如上面的javac,我们知道redirect到stderr中,所以解决hang后的代码
1 public static void main(String[] args) {
2 try {
3 Process process = Runtime.getRuntime().exec("echo 'abc'>b.txt");
4 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
5 String line;
6 while((line=reader.readLine())!=null){
7 System.out.println(line);
8 }
9 int result = process.waitFor();
10 System.out.println(result);
11 } catch (IOException e) {
12 e.printStackTrace();
13 } catch (InterruptedException e) {
14 e.printStackTrace();
15 }
16 }
3. exec() is not a command line 并不是所有的command line命令都可以用exec 1 public static void main(String[] args) {
2 try {
3 Process process = Runtime.getRuntime().exec("echo 'abc'>a.txt");
4 BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
5 String line;
6 while((line=reader.readLine())!=null){
7 System.out.println(line);
8 }
9 int result = process.waitFor();
10 System.out.println(result);
11 } catch (IOException e) {
12 e.printStackTrace();
13 } catch (InterruptedException e) {
14 e.printStackTrace();
15 }
16 }
结果为:
1 'abc'>a.txt
2 0
并没有将创建a.txt,而从命令行执行
"echo 'abc'>a.txt"却正确创建了a.txt
Extreme programming is a set of simple and concrete practices than combine into an agile development process.
- Whole Team - Cutomers, managers and developers work closely with one another. So they are all aware of one another's problem and are collaborating to solve the problem. The customers can be a group of BAs, QAs or marketing persons in the same company as developers. The customers can be the paying customer. But in an XP project, the customer, however defined, is the member of and available to the team.
- User Stories - In order to plan a project, we must know something about the requirement, but we don't need to know very much. We need to know only enough about a requirement to estimate it. You may think that in order to estimate the requirement, you need to know all the details. That's not quite true. You have to know that there are details and you have to know roughly the kinds of details, but you don't have to know the sepecifics. Since the sepecific details of the requirements are likely to change with time, especially once the customers begin to see the system together. So when talking about requirements with the customer, we write some key words on a card to remind us of the conversation. A user story is memonic token of an ongoing conversation about a requirement. Every user story should have an estimation.
- Short Cycles - An XP project delivers working software every iteration - one or two weeks. At the end of each iteration, the sytem is demonstrated to the customer or the stakeholder in order to get their feedbacks. Every release there is a major delivery that can be put into production.
The Planning Game - The customers decide how important a feature is and the developers decide how much effort the feature will cost to implement. So the customers will select a collection of stories based on the priority and the previous iterations' velocity.
The Iteration Plan - Once an iteration has been started, the business agrees not to change the definition or priority of the stories in that iteration. The order of the stories within the iteration is a technical decision. The developers may work on the stories serially or concurrently. It depends but it's a technical decision.
The Release Plan - A release is usually three months. Similarly, the business or customer selecte collections of user stories and determines the priority based on their buget. But release are not cast in stone. The business can change or reorder at any time. They can write new stories, cancel stroies or change the priority. However, the business should not to change an interation that has been started.
Acceptance Tests - The detail about the user stories are captured in the form of acceptance tests specified by the customer. The acceptance tests are written by BAs and QAs immediately before or concurrently with the implementation of that story. They are written in a scripting form that allow them to be run automatically and repeatlly. These tests should be easy to read and understand for customers and business people. These tests become the true requirement document of the project. Once the acceptance test passes, it will be added the body of passing acceptance tests and is never allowed to fail. So the system is migrated from one working state to another.
Pair Programming - One memeber of each pair drives the keyboard and types the code. The other member of the pair watches the code being typed, finding errors and improvements.
The roles change frequently. If the driver gets tired or stuck, the pair grabs the keyboard and starts to drive. The keybord will move back and forth between them serval times in one hour. The resulting code is designed and authored by both memebers.
Pair memebership changes frequently. A reasonable goal is to change pair partner at least once per day. They should have worked on about everything that was going on in this iteration. Also it is very good for knowledge transfer.
Collective Ownership - A pair has right to check out any module and imporve it. No particular pair or developer are individually responsible for one particular module. Every developer of the project has fully responsible for each line of the code. So don't complain about the code may be written by the other pair. Let's try to improve it. Since it is our code.
Open Workspace - The team works together at one table or in one room. Each pair is within earshot of every other pair. Each has the opportunity to hear when another pair is in trouble. Each konws the state of the other. The sound in this room is a buzz of conversation. One might think that this would be a noise and distracting envrionment. But study suggested, working in a "war room" envrionment may increase productivity.
Simple Design - An XP team makes its designs as simple and expressive as they can be. Furthermore, the team narrows its focus to consider only the stories that are planned for the current iteration, not worrying about stories to come. The team migrates the design of the system from iteration to iteration to be the best design for the stories that the system currently implements.
- consider the simplest thing that could possibly work. - XP teams always try to find the simplest possible design option fot the current batch of stories.
- You aren't going to need it. - That means an XP team introduces one technology or one infrastructure before it is strictly needed. Yeah, but we know we are going to need that database one day. We are going to have to support multiple threads one day. So don't we need to put the hooks in for those things? The team puts the technology or infrastucture in only if it has proof or at least very compelling evidence. that putting it in now will be more cost-effective than waiting.
- Once and only once. XPers don't tolerate duplication of code. Wherever they find it. they remove it. The best way to remove redundancy is to create abstractions. After all, if two things are similar, some abstraction can be from them.
Continuous Integration
Sustainable Pace
Test-Driven Development
Refactoring
Metaphor
- 第一范式 - 列的原子性,数据库表中的每一列都是不可再分的基本数据项
- 单一字段有多个有意义的值:比如 (people,address)其中address包括street,city,country,以逗号分割。想要查询住在某一city的people很不容易
- 用很多字段来表示同一事实:比如(people,address1,address2,address3),就算我们假设每个people最多有三个地址,当想要查询住在同一地址的people时也很不容易,因为有可能people1的address1与people2的address2相同,每一次都要比较3*3次组合
- 第二范式 - 符合第一范式;且表中的属性必须完全依赖于全部主键,消除非主属性对主键的部分依赖
- 比如(组件ID,供应商ID,供应商姓名,价格),组件ID+供应商ID为主键,价格完全依赖于全部主键,因为不同组件不同供应商具有不同价格,但是对于供应商姓名,则只依赖于供应商ID,会造成对同一供应商ID,名字数据重复,而且如果供应商改名,需要修改全部数据。因此需要单独一个表(供应商ID,供应商姓名),(组件ID,供应商ID,价格)
- 第三范式 - 非主属性之间不能有依赖关系,必须都直接依赖于主属性,消除传递依赖
- 比如(组件ID,制造商姓名,制造商地址),其中组件ID为主键,而制造商地址依赖于制造商姓名,需要(组件ID,制造商姓名)和新表(制造商姓名,制造商地址)其中姓名是主键
- 比如(订单ID,组件ID,单价,数量,总价),其中总价=单价*数量,总价依赖于单价和数量,需要去掉总价栏
- BC范式 - 任何属性(包括非主属性和主属性)不能被非主属性所决定。第三范式强调非主属性不能依赖于其他非主属性,BC范式是第三范式的加强,强调“任何属性”。因此如果满足第三范式,并且只有一个主键,则一定满足BC范式
一般,范式越高,表越多,数据库操作时需要表关联,增加了查询的复杂性,降低了查询性能。因此并不是范式越高越好,要根据需要进行权衡,第三范式已经消除了大部分的数据冗余,插入异常,更新异常和删除异常。
Why?Functional test characteristic
- The number of tests is mostly large.
- Page structure and elements may be changed frequently.
If our tests interact directly with the test driver (selenium,etc).
- UI element locators(Xpath, CSS, element Ids, names, etc) are copuled and repeat throughout the tests logic. It is hard to maintain, refactor and change especially when we change the page structure.
- The fine-grained UI operations hide our actual test intention. After some time we can not easily to identify what we want to do before.
What?A Page Object models the UI elements that your tests interact with as objects within the test code. It decouples the test logic from the fine-grained details of the UI page.
Test -> Page Object -> Test Driver
The driver is the actual executor of browser action, like click, select, type etc. The page object has knowledage of the HTML structure.
Advantages- When UI changes, only responding page object need to be changed. The tests logic will not be affected.
- It makes our tests logic simpler and more readable. Since the tests logic can only focus on its test secinaro rather than the structure of HTML page. As an example, think of login function, it only needs username and password, then do login action. How these are implemented shouldn't matter to the test. We don't care about that it uses a button or link to login.
- Complex interactions can be modeled as methods on the page object, which can be used in multiple times.
Best Practices- Public methods represent the services that the page offers
- Try not to expose the internals of the page. Like OO programming, object just expose the behaviour and hide its internal details.
- Generally don't make assertions, but it is better to do some kind of check to ensure the browser is actually on the page it should be. Since our following tests are all base on the assumption. It can be done by checking something simple like title.
- Methods return other page object. This means that we can effectively model the user's journey through our application.
- Don't need to represent the entire page. It can be just a tab or a navigation bar that your test interacts with.
- Only one place knows the HTML structure of a particular page. UI changes, the fix need only be applied in one place.
- Different results for the same action are modeled as different methods. Since the test knows the expected state.
1.
Small and the indent level should not be greater than one or two.
2.
Do One Thing - Functions should do one thing. They should do it well. They should do it only.
Steps of function are one level of abstraction below the name of the function. Then the function is doing one thing.
Another way to know function is doing more than one thing is if you can extract another function from it.
3.
One level of abstraction per function The stepdown rule - reading code from top to bottom.
switch
4.
Use Descriptive Names Don't be afraid to make a name long.
A long descriptive name is better than a short magic name.
A long descriptive name is better than a long descriptive comment.
Dont't be afraid to spend time choosing a name.
Be consistent in your names.
5.
Function Arguments The ideal number of arguments for a function is zero.
Three arguments should be avoided.
Flag Arguments - can be split into two function.
Aruments Objects - group the variables and abstract concept if possible.
Verbs and keywords - function and argument should form a very nice verb/noun pair.
6.
Have no side effects7.
Command Query Separation - Functions should either do something or answer something, but not both.
8.
Prefer Exceptions to returning error codes. Extract try/catch blocks, error handling is one thing.
9.
DRY - don't repeat yourself - especially the duplicated logic.
一,全局变量
1.全局变量可以被任何部分在任意时间改变,复杂化,降低可靠性
2.可能与子程序变量名相同,冲突可能导致程序无法运行,难以调试
三种声明全局变量模式
1.脱离任何函数的var foo = value
2.直接添加属性至全局对象,全局对象是所有全局变量的容器,在web浏览器中全局对象名为window,window.foo = value
3.直接未经声明的变量 - 隐式的全局变量 foo = value
二,没有块作用域,有函数作用域
函数中定义的参数和变量在函数外部不可见,而在一个函数中任何位置的定义的变量在该函数的任何地方可见。
function f1(){
var a=1;
function f2(){
if(false){
var a=2; //变量基于函数,而非基于语句块,没有块作用域
}
console.log(a); //undefined 未定义
}
f2();
console.log(a);//1
}
f1();
大多数语言中,一般声明变量都是在第一次用到它的地方,在javascript中是一个坏习惯,因为没有块作用域,更好的是在每个函数开头声明所有变量。
三,return语句返回一个值,值表达式必须和return在同一行上
return {
status:true
};
返回包含status成员元素的对象。
如果用
return
{
status:true
};
会返回undefined。
四,保留字不能用来命名变量或函数,当保留字被用作对象字面量的键值时,必须用引号,而且不能用点表示法,必须使用括号表示法。
var object = {case:value}; //非法
var object = {'case':value}; //ok
object.case = value; //非法
object['case'] = value; //ok
各浏览器对保留字使用限制上实现不同,以上语法在FF中合法,但其他浏览器不合法;再有不同的保留字行为也不相同。类似int/long/float等保留字在各浏览器中都可以做变量名及对象字面量的键值。但不建议使用任何保留字。
五,typeof - 识别运算数类型的字符串
但typeof null返回'object',更好的检测null的方法: my_value === null
对于正则表达式 typeof /a/,一些浏览器返回'object',另一些返回'function'
六,parseInt - 将字符串转换为整数
1.此函数遇到非数字时就停止解析,即parseInt('16')和parseInt('16 abc')产生结果相同,都是16.
2.如果字符串第一个字符是0,则基于八进制解析,而不是十进制。八进制中没有8,9数字,所以parseInt('08')和parseInt('09')结果为0。此函数可以接收一个基数作为参数,parseInt('08',10)结果为8。
七,浮点数
0.1+0.2不等于0.3
八,NaN
function isNumber(value){
return typeof value === 'number' && isFinite(value);
}
isFinite筛调NaN和Infinity,但是isFinite会试图把它的运算数转换为一个数字,如果运算数事实上不是一个数字,就会报错,所以加上typeof value === 'number'。
九,假值
0,NaN,'',false,null,undefined全部等于假,但它们是不可互换的。