Verifying preconditions: the assert statement July 28, 2008
Posted by crystalchangdin in education and career in Sweden.add a comment
Java’s assert statement can be usd in verifying preconditions. The statement had two formats. The simpler form is
assert booleanExpression;
The boolean expression is evaluated, and if it is ture, the statement has no effect. If it is false, the statement raise an error condition – an exception. This will stop execution of the program and display some information about the caise of the exception. We can use assert statement to verify preconditions in the constructor as follows:
public Expoler (String name, Room location, int strength, int tolerence)
assert strength >= 0;
assert tolerence >= 0;
this.name = name;
this.location = location;
this.strength = strength;
this.tolerence = tolerence;
}
If a client invokes the constructor with a negative tolerence argument, the program will terminate and we’ll get a meddage that looks something like this:
Exception in thread “main” java.lang.AssertionError
at maseGame.Explorer.<init>(Explorer.java:16)
at maseGame.ExplorerTest.runTest(TestExplorer.java:16)
at maseGame.TestExplorer.main(TestExplorer.java:7)
The second form of the assert statement is
assert booleanExpression:expression;
As before, the boolean expression is evaluated, and if it is ture, the statement has no effect. If it is false, the second expression is evaluated and the result incorporated into the exception message. For instance, we might write
assert tolerence >= 0 : “precondition: tolorence ( ” + tolerence + “) >= 0″;
Here the expression produces a String that includes the argument value of tolerence. If a client invokes the constructor with a negative tolerence argument, the message will look something like this:
Exception in thread “main” java.lang.AssertionError
precondition: tolerence (-10) >= 0
at maseGame.Explorer.<init>(Explorer.java:16)
at maseGame.ExplorerTest.runTest(TestExplorer.java:16)
at maseGame.TestExplorer.main(TestExplorer.java:7)
Swedish today July 27, 2008
Posted by crystalchangdin in language exchange.add a comment
kulle:小土坡,滿佈青草
tyvärr är det ganska dålig kvalitet
kvalitet=quality
Allt väl med dig?
everything alright with you?
English today July 27, 2008
Posted by crystalchangdin in New Words Today.add a comment
eloquent:雄辯的,有說服力的
I really enjoyed Mark’s presentation. It’s rare to hear such an eloquent speaker.
rival:競爭者,對手
full-down:
onerous:繁重的,麻煩的,負有義務的,有償的
frolic:歡樂,嬉戲,嘻鬧,歡樂的聚會(或遊戲)
chaperoned:陪伴的,護送的
nose-dived
spawned:生育的
rampant:繁茂的,蔓生的,猖獗的
perennial:終年的,常年的
tenacious:緊握的
blithe:歡樂的,快活的
stiff:硬的,挺的(stiff brush)
The shoes are brand new and the leather is still very stiff.
relic:遺物,殘片,遺跡,廢墟
artifact:人工製品,手工藝品,加工品
revive
(v) to bring something back to full strength 使復甦;振興
I watered my plants to revive them.
dissolve
(v) to cause a solid to be absorbed by a liquid 溶解
The cubes of sugar slowly dissolved in the hot coffee.
no-brainer
(n) something that is very simple to do or to understand; a choice that is obvious or easy 非常簡單的事情;不用動腦就能了解的事
The homework assignment was a no-brainer so I was able to finish it easily in only 15 minutes.
allocate
(v) to give something to someone as their share, for them to use in a particular way 分配;撥配
The teachers allocated the students their hotel rooms on the school trip.
sound bite
(n phr) a short sentence or phrase said publicly and likely to be repeated in newspapers or on television and radio 流傳於傳媒的金句或名言
The president’s sound bite on his latest plans for city improvements was played on every news station today.
programming by contract July 26, 2008
Posted by crystalchangdin in education and career in Sweden.add a comment
A programming style in which the invocation of a method is viewed as a contract between client and server, with each having explicity stated responsibilities.
Preconditions and postconditions are part of a programming style called programming by contract.
invariant, class invariant, precondition, postcondition July 26, 2008
Posted by crystalchangdin in education and career in Sweden.add a comment
invariant: a condition that always holds true
class invariant: an invariant regarding properties of class instances; that is, a condition that will always be true for all instances of a class.
precondition: a condition the client guarentees have been satisfied at the time of the call. It is labeled “require.”
postcondition: a condition the implementor quarantees will hold when a method or constructor completes exection. It is labeled “ensure.”
For example,
/**Create a new Explorer with the specified name,
*initial location, strength, and tolerance.
*@ require strength >= 0
* tolorence >= 0
*@ ensure this.name().equals(name)
* this.location() == location
* this.strength() == strength
* this.tolerence() == tolerence
*/
public Explorer (String name, Room location, int strength, int tolerence)…
Java in details: static and final features July 26, 2008
Posted by crystalchangdin in education and career in Sweden.add a comment
Final features
public static final int GREEN = 0;
The specification static implies that the feature is associated with the class itself, rather than with an instance of the class. Hence the use of the class name when referring to the feature:
light = TrafficSignal.GREEN. // TrafficSignal is the class name
The keyword final means that the value to which the identifier is bound cannot be changed. We can declare instance variables and even parameters final. For example, we could declare instance variables of a Rectangle to be final:
public class Rectangle{
private final int length;
}
After these variable is assigned values in the constructor,
public Rectangle(int length){
this.length = length;
}
their values cannot subsequently be modified.
A parameter is initialized with the argument provided by the client. If a parameter is defined to be final, such as,
public void increamentCount(final int amount)…
it cannot be modified in the body of the method.
Note that the modifier final applied to a variable refers to the value stored in the variable, not to an object denoted by a reference value. Suppose the parameter pile in nim Player method takeTurn was definedto be final:
public void takeTurn(final Pile pile)…
When the method is invoked, a method variable is allocated and initialized with a reference-to-Pile value provided as argument.
The fact that the parameter is final means that the value stored in this variable cannot be changed. For instance, the method cannot contain the statement:
pile = new Pile(10); // No! pile is final!
However, the method is not prevented from giving the object a command that moght change the object’s state. The method can contain the statement
pile.remove(1); // OK! This doesn’t change the reference value stored in pile.
Importing static features
import static className.identifoer;
import static className.*;
For example,
import Math.sqrt;
import Trafficsignal.GREEN;
These statement allow the identifier to be used without being prefixed with the class name. We can write
return sqrt(a);
and
light = GREEN;
rather than
return Math.sqrt(a);
and
light = TrafficSignal.GREEN;
The second format allows all static features defined in a class to be used without being prefixed with the class name. For instance,
import static TrafficSignal.*;
allows the simple identifiers GREEN,RED, and YELLOW to be used in place of the qualified names TrafficSignal.GREEN, TrafficSignal.RED, and TrafficSignal.YELLOW.
Traffic Light July 26, 2008
Posted by crystalchangdin in coding.add a comment
main
public class TrafficLight {
public static void main(String[] args) {
LightTester tester = new LightTester();
tester.runTest();
}
}
Light
public class Light {
public static final int RED = 0;
public static final int GREEN = 1;
public static final int YELLOW = 2;
private int currentLight;
public Light()
{
currentLight = RED;
}
public void change()
{
currentLight = (currentLight + 1) %3;
}
public void show()
{
showColor();
}
private void showColor()
{
if(currentLight == RED)
System.out.println(“RED”);
else if (currentLight == GREEN)
System.out.println(“GREEN”);
else
System.out.println(“YELLOW”);
}
}
LightTester
public class LightTester {
Light light;
public LightTester()
{
light = new Light();
}
public void runTest()
{
System.out.print(“current light is = “);
light.show();
testChange();
}
private void testChange()
{
System.out.println(“Change first time”);
light.change();
System.out.print(“current light is = “);
light.show();
System.out.println(“Change second time”);
light.change();
System.out.print(“current light is = “);
light.show();
System.out.println(“Change third time”);
light.change();
System.out.print(“current light is = “);
light.show();
}
}
很棒的挑戰與鼓勵_from mom July 26, 2008
Posted by crystalchangdin in Uncategorized.add a comment
熱情 智慧 堅持 是求學做事的絕妙因素
new settings July 26, 2008
Posted by crystalchangdin in my computer.add a comment
MikTeX 2.7 Texmaker
Testing an implementation July 26, 2008
Posted by crystalchangdin in education and career in Sweden.add a comment
Testing is an fundamental part of building a software system. The testing we consider here is called unit testing. We test a class we are implementing to make sure that it behaves as expected. This is part of the job of implementing the class. Functional testing, on the other hand, involves testing the entire system to ensure that it meets the customer’s specifications. Functional testing is a different beast entirely, and is often the responsibility of a team different from the programming team that implements the system.
It is an unfortunate fact that programmers spend more time debugging than writing code. As a result, the best way to improve productively is to reduce debugging time, and the best way to reduce debugging time is to adopt an aggresive testing regmin. In our opinion, an increamental test-driven implementation procedure is the most effective means of reducing the time required to track down and correct bugs.
There are several aspects to this approach. First, the implementation proceeds in relatively small increaments. The process is to code a little, test a little. Each time you add a new bit of functionality, you test it immediately. Second, the implementation is “test-driven.” That is, you write the test for a feature before implementing the feature. Writing the test gives you a very concrete specification of how the feature is to behave. Once the test is written, you write code to satisfy the test. In fact, developing a test sometimes exposes inconsistencies or lack of completeness in the specification.