Constants with functionality and more on type safe storage.

1. Study materials

1.1. Tutorials to study

Study the Oracle tutorial on Enum and Generics:

2. Exercises

Why do you fight the compiler? The compiler is your friend. She only talks a bit wierd.

This week’s exercises are all about enum and generics. This means you have to fight the Java compiler, but of course after you have written your tests.

One of the often forgotten purposes of generics is to make the Java programming language safer, but letting the compiler do some hard thinking. And as the compiler is statically testing your code, a compiler error counts as a red, solving the issue (in the generics proper way) is a green.

Start with the first (simplest) exercise and work your way down.

2.1. A Box for many things

Before you learnt that generics exist, you had to get by. You needed classes that store information for you and let you retrieve it, too. So after a semester of Java, you have a bunch of classes in which you store stuff. For example, you have the class IntegerBox:

public class IntegerBox {
  private Integer value;

  public void putIntegerInBox(Integer anInt) {
    value = anInt;
  }
  public Integer getInteger() {
    return value;
  }
}

This little box class is pretty straight-forward. It has an Integer field at which you store the Integer that you put in the box, and you have a getter (getInteger) and a setter (putIntegerInBox) method to store and retrieve your Integers.

The trouble is, this box can’t deal with Double. Or String. Or anything that is not an Integer. So calling myBox.putIntegerInBox("Text") will not work. That means that for every new kind of variable, you need a new class. Quickly, your list of classes grows: IntegerBox, StringBox, DoubleBox, ListBox, StudentBox, BoxBox…​ this is very inefficient.

This is where you and Java generics come in:

  • Create a class named Box that can take any type using a type parameter.

  • Inside that class, have a private field that stores the same any type.

  • Create getter and setter methods for the class

Test your implementation by using this main method:

public static void main(String[] args) {

   Box<Integer> iBox = new Box<Integer>();
   Box<String> sBox = new Box<String>();

   iBox.putIn(5);
   sBox.putIn("Some Text");

   System.out.println("My integerBox contains: "+ iBox.getStored());
   System.out.println("My stringBox contains: "+ sBox.getStored());
}
ExtraChallenge EXTRA CHALLENGE: Create a class called Pair, that can take two different type parameters, store them in two separate fields and return them as well.

2.2. Shape Filters

The shapes project template is in your repository, wk04.

In package shapes.basic you have multiple shapes, among which are:

  • Disk which extends Circle. Disk contains an image.

  • Sphere which extends Disk. Sphere creates a 3D like image of a sphere or Ball.

The essential detail here is that Disk and Sphere are sub classes of Circle. There is no need to change anything in this package. Just check if you understand the inheritance hierarchy and the use of interfaces and abstract classes.

2.2.1. Shape filter

This part is about generics. Remember the PECS acronym. In the ShapeManager test-driven develop two methods:

  • void addShapes(Collection …​ shapesToAdd) Make sure to use the proper Collection definition with generics. The idea is that each collection of shapes (e.g. a collection of Circles, a collection of Disks, a collection of Shapes can be processed).

  • boolean collectShapesOfType( Collection<…​> consumer, Class<…​> type ) This method takes two methods, a collection (like a list) in which you can put shapes and the type of shape you want filter. For example, you’re passing an empty list that is filled with all Circles.


2.3. Drinkers A.K.A. Bad Bar Dreams

The drinkers project template is in your repository, wk04.

This is an exercise about enums, exceptions and generics. It is about drinks, quantities and things being thrown and how to keep all this generic.

2.3.1. Implement the enum class BeerQuantity

Implement the enum class BeerQuantity according its javadoc.

2.3.2. Implement testGetBeer() and getBeer()

The bartender (Bart) is a cautious guy: he checks the beer stock every time before he draws a serving. If the stock does not suffice he throws an AlmostOutOfBeerException in the method getBeer(…​).

Write the testGetBeer() method in the BarTenderTest class. Afterwards, change the implementation of the getBeer() method in the BarTender class to let the test pass.

2.3.3. Big Business Bartender

ExtraChallenge Challenging exercise: Booze is a recurring topic here.
drinkers
Figure 1. drinkers peacefully in a class diagram

Note that the diagram above is not a real class diagram, but something the BarTender understands.

The BigBusinessBartender is a special Bartender that serves several types of drinks and serves guests (a list of Drinkers) by the busloads. The BigBusinessBartenderTest class is given, as well as the serveByTheBusLoad(…​) method implementation in class BigBusinessBartender.

Implement the consumer methods below:

  • Implement serveBeer( drinker )

  • Implement serveLemonade( drinker )

  • Implement serveWhisky( drinker )


3. Code Coverage in NetBeans IDE

3.1. What is Code Coverage?

To see if your tests use all the code your write, you can add a plugin to netbeans that can show so called coverage data. Coverage is the percentage of lines and branches that is executed, shown in a report and in the IDE.

In this case a red (red background) means the code was not executed.

workercoverage
Figure 2. coverage when testing only the lucky path

3.2. How to install a code coverage plugin in NetBeans

The plugin is called TikiOne JaCoCoverage and can be installed form NetBean’s default plugin repository. Read JaCoCoverage as Java Code Coverage.

Use the NetBeans Plugin Dialog to add it to your own installation.

tikioneplugin
Figure 3. plugin dialog of installed TikiOne JacocCoverage plugin

A plugin like this will be available on the exam stick as well, so use to your advantage.

4. Adding your own code templates to NetBeans IDE

Productivity can be helped big time, if you add code templates to netbeans. Quite a few are predefined but you can add your own too.

Go to Tools > Options > Editor > Code Templates.

You get this dialog:

codetemplatedialog

You can add one with the new buttpn, Duh.

I find this one quite convenient:

definition of my codetemplate jutm
@Test
public void test${Method}() {
    ${cursor}
    Assert.fail("test method test${Method} reached its end, you can remove this line when you aggree.");
}
Adding Code templates