Thursday, April 19, 2007

4/19 Serialization and Runtime Assertions

Reading & Writing Objects
+ we can write objects to a file without having to connect them to things like strings
+ we can read objects from a file without having to convert strings to objects

Serialization means:
+ save a file the class & the data in the instances of that class
+ if any fields reference other objects those will be serialized, too
+ when reading from a file where the objects were serialized they will be stored to same state and content they had when serialized

package java.util;
public class Date implements java.io.serializable {...}
...
// create a file
FileOut.printStream fos = new FileOutputStream("serialDate.bin");
ObjectOutputStream oos = new ObjectOutputStream(fos);
//create data object and write to file
Date d = new Date();
oos.writeObject(d);


this allows us save an object of type Date to file

Ex: read object from file

FileInputStream fis = new FileInputStream("serialDate.bin");
ObjectInputStream ois = new ObjectInputStream(fis);
Object o = ois.readObject(ois); //reads Object from the object input stream (returns from stream)
// now we need to typecast the object to Date (the type you expect)
Date savedDate =(Date)o;

Type casting is type safe in Java, i.e. you can't force an object into a class it doesn't belong to
If you try to...it will raise a "class cast exception"

EX:

Object o = ois.readObject(ois);
Cup myCup = (Cup)o;
//this is wrong - raises a class cast exception

Note: if a class is serializable, then all of its classes are serializable as well.



Serialization and Security
The people designing java debated whether all objects shoul dbe serializable

+ the programmer must explicitly decide what objects are serializable because it has implications on security

EX: assume you serialize a file descriptor. Then somebody evil edits the file where the object is stored and modifies it. When the object is read from the file, the file descriptor will point to someplace other than intended

NOTE: you must consider the security implications of your decision to make a class serializable

What can you do?
+ validate the object after you read it back; cross-check for consistency
+ take care of serialization yourself; implement the Externalizable interface (provide the implementation for the read and write methods)
+ use the keyword "transient" to prevent certain data members from being written to the file

class Employer {
String name;
int employeeID;
private transient int SSN;
//the social security # will not be written to the file
//when an instance of Employee is serialized
...
}


Certain classes cannot be serialized at all, e.g. java.lang.Thread
+ thread include java code and native code (perhaps written in C/C++); threads maintain two stacks, one for Java code, the other for native code; the problem is that Java doesn't know what
's in the native stack, therefore serialization cannot possibly work



Assertions and Defensive Programming

+ defensive programming is a way to mitigate the effects of bugs w/o knoowing where the bugs are

NOTE: adopting a defensive programming attitude does not mean youre incompetent

How does it work?

_ figure out invariants, i.e. conditions you expect to hold true at certain points in the program. Test if the condition actually holds true; if it doesn't then something is really wrong -> abort

EX: assume you are working on a compiler, big sofwatre lots of possibiliteis for stuff to go wrong

class Symbols {
Vector symbols;
Vector types;
Vector partitions;
}

Assume a symbol called "sym", the sumbol vector. To find the Type of "sym" we need to access the Types of vecotr at the same index.


int i = symbols.indexOf(sym);
Type t = types.get(i);

This code only works if the vectors symbols and types have the same length

this is your invariate for this piece of code.

Runtime Assertions
+ don't use assertiona as a crutch for sloppy/bad code
+ ways to use assertions
-at the start of precedure to check that procedure is called as ecpected (e.g. proper value for assigments, etc.)
- at the end of the procedure to check that result is reasonable/plausible
- when an operation is performed that has an external effect


Assertions in Java
+ introduced in Java 1.4

EX:

assert booleanExpression ;


+ assert is not recognized by the java compiler unless you instruct it to;

java -source 1.4 MyClass.java

you'll get compilation error with this flag (-source) if your program contains assert statements

+ assertions are turned off by default: you must instruct the run-time environment to execture them

java -ea MyClass

NOTE: test your program both with assertions enabled and assertions disabled (they should do the exact same thing)
avoid assertions that have side effects

EX:
boolean noMoreData = true;
boolean checkingMethod() {
noMoreData = false;
return noMoreData;
}

PROBLEM: different values for noMOreData depending on whether assertions are enabled or disabled.

Q: what is the status of your code?
A: (typical): I'm X% done (x is typically 80 or 90%)
WRONG! you may be 90% done for another month or year even thought waht you've done took only a week or a day...it's easy to get stuck
The correct answer is I'm done or I'm not done.... DO NOT give any other answer (make promises you cannot keep)



No comments: