A Simple database

Sven-Olof Nyström
OOP med Java våren -25
Informationsteknologi
Uppsala Universitet

An assignment from 2003

(Detta avsnitt är på engelska eftersom uppgiftsspecifikationen jag länkar är på engelska.)

Please read the assignment specification first: program/database/assignment2.html. (This text was written by another teacher.)

The obvious and intended solution is to define a class hierarchy, with classes for laptops, printers, etc. Each attribute corresponds to an instance variable.

This is a reasonable way to illustrate OOP concepts, but is it the best solution to the problem at hand?

There are a few problems with the obvious solution:

I will show two solutions based on other ideas:

Solution 1:

An entry in the database:

class Entry {
    List <String> keys = new ArrayList<String>();
    Map <String, String> data = new TreeMap<String, String>();

    void add(String key, String attribute) {
	keys.add(key);
	data.put(key, attribute);
    }

    boolean compare(String key, String attribute) {
	return attribute.equals(data.get(key));
    }

    void print () {
	System.out.println("--------------------------------------------------");
	for (String key : keys) {
	    System.out.println(key+ " : "+ data.get(key));
	}
	System.out.println("--------------------------------------------------");
    }
}

The rest of the code is here:

program/database/db1/

Here, all entries are represented as Maps that take attribute names to their associated values.

The database is simply a Set of entries.

This solution is incomplete as it does not divide entries into categories.

Solution 2

program/database/db2/

Add an attribute category to each entry.

Divide the database into categories.

Modify the command-line language.

Still incomplete

The solutions are still incomplete, as there is no way to save the data to file or load it from file. Also, there is no way to specify categories and have the database check that the attributes of an entry conforms to its category.

How would you implement the following?

Conclusion

The point of my example is that sometimes "obvious" classes in a specification need not be implemented as classes in the program.

In particular, if there is a very large number of "classes" in the problem specification, and the class structure is likely to change, you should not assume that best implementation is to represent the classes of the problem specification as Java classes.

The categories of the assignment were intended to be represented statically as classes in the Java program, Instead, my solution represents the categories as dynamic information at runtime.

The example also shows a way to implement interpretation of a command line.