Basic AJAX in JSF

In this article I would like to describe how to send AJAX request to server, receive the response and update the page accordingly. As an example I will use a simple application which allows choosing country from a list. Once the country is chosen, the list of cities is automatically updated. The main screen of the application will look like this:
ajax-city

The good thing about AJAX in JSF is that all the work related to generating request, sending request, receiving response and processing it is hidden behind well-defined abstractions. Actually, it is often enough to specify the event which triggers the request, which parts of the page needs to be sent to server and which parts of the page needs to be updated after receiving response.

Optionally, error handlers and listeners may be specified apart from other things. Additionally, JSF performs the queueing of AJAX requests to ensure that next request is started after the previous one finishes.

Managed bean

Below is the managed bean used by the application. What is important here is that the bean has no knowledge that AJAX will be used.

package com.example.ajaxcities;

import java.io.Serializable;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.faces.model.SelectItem;
import javax.inject.Named;

@Named
@SessionScoped
public class Cities implements Serializable {
    private static final long serialVersionUID = 2347238972389L;
    private static final Logger LOGGER = Logger.getLogger(Cities.class.getName());

    @EJB
    private CityDAO cityDAO;
    
    private SelectItem[] countrySelectItems;
    private String country;
    
    private SelectItem[] citySelectItems;
    private String city;

    @PostConstruct
    public void init() {
        createCountrySelectItems();
        createCitySelectItems();
    }
    
    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
        createCitySelectItems();
        LOGGER.info(String.format("Selected country: %s", country));
    }

    public SelectItem[] getCountries() {
        return countrySelectItems;
    }
    
    private void createCountrySelectItems() {
        String[] countries = cityDAO.getAllCountries();
        if (countries != null && countries.length > 0) {
            country = countries[0];
            countrySelectItems = new SelectItem[countries.length];
            for (int i = 0; i < countries.length; i++)
                countrySelectItems[i] = new SelectItem(countries[i], countries[i]);
        } else {
            country = "";
            countrySelectItems = new SelectItem[0];
        }
    }
    
    public String getCity() {
        return city;
    }
    
    public void setCity(String city) {
        this.city = city;
    }

    private void createCitySelectItems() {
        String[] cities = cityDAO.getCities(country);
        if (cities != null && cities.length > 0) {
            city = cities[0];
            citySelectItems = new SelectItem[cities.length];
            for (int i = 0; i < cities.length; i++) {
                LOGGER.info(String.format("Adding to cities: %s", cities[i]));
                citySelectItems[i] = new SelectItem(cities[i], cities[i]);
            }
        } else {
            city = "";
            citySelectItems = new SelectItem[0];
        }
    }
    
    public SelectItem[] getCities() {
        return citySelectItems;
    }
}

The actual place where we use AJAX is the XHTML web page. It can be done in two ways.

Declarative AJAX

The first method is to put <f:ajax> tag inside XHTML element which triggers the AJAX request. It is very convenient because we don’t need to write any JavaScript code.

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:f="http://xmlns.jcp.org/jsf/core">
    <h:head>
        <title>#{msgs.ajaxCities}</title>
    </h:head>
    <h:body>
        <h:form>
            <h:panelGrid columns="2">
                #{msgs.country}
                <h:selectOneMenu id="countryList" value="#{cities.country}">
                    <f:selectItems value="#{cities.countries}" />
                    <f:ajax event="change" execute="countryList" render="cityList" />
                </h:selectOneMenu>
                
                #{msgs.city}
                <h:selectOneMenu id="cityList" value="#{cities.city}">
                    <f:selectItems value="#{cities.cities}" />
                </h:selectOneMenu>
            </h:panelGrid>
            <h:commandLink action="index" value="#{msgs.back}" />
        </h:form>
    </h:body>
</html>

The element

<f:ajax event="change" execute="countryList" render="cityList" />

informs JSF engine that once the JavaScript event specified in event attribute will occur, the components specified in execute attribute will be executed on server and the components specified in render attribute will be rendered (updated on the web page).

The possible values of event attribute are the same as in JavaScript but without on prefix. In our case the AJAX request will be sent every time the country is changed.

Attribute execute contains space-separated list of HTML identifiers of the elements that will be executed on server. In our case element with identifier countryList will be executed which means that its value will be set in bean. Attribute execute may also contain four special values: @this, @form, @all and @none. If execute attribute is not specified, default value of @this will be used.

Attribute render contains space-separated list of HTML identifiers of the elements that will be updated on the web page once the AJAX response is received. It also supports four special values as execute attribute but the default value is @none.

AJAX using JavaScript library

Tag <f:ajax> is very convenient but it also has some limitations which may be an issue in more advanced cases. Luckily, it is also possible to directly use JavaScript library to send AJAX requests to server.

First the library must be referenced from the web page using construction:

<h:outputScript library="javax.faces" name="jsf.js" />

Once it is done we can execute AJAX request using JavaScript when an event happens:

<h:selectOneMenu id="countryList" value="#{cities.country}"
      onchange="jsf.ajax.request(this, event, {
                  execute: 'main:countryList',
                  render: 'main:cityList' });">
      <f:selectItems value="#{cities.countries}" />
</h:selectOneMenu>

Actually, this does not seem much different from using <f:ajax> tag but it gives us more control over what is being sent. For example it allows us to pass additional parameters in AJAX request apart from execute and render and then process them on the server.

Conclusion

AJAX is becoming more and more popular because it gives faster and smoother user experience without constantly reloading the web page. This makes it a great alternative to using value change listeners. I hope you will find it useful in your own projects.

All the code for this example was tested on Glassfish and is available at Github

Posted in AJAX, Java, Java EE, JSF | Tagged , , , , , , , | 2 Comments

Assertions in Java

One of the rules of defensive programming is to detect the errors as soon as they appear. The main idea behind this is that we can get precise information about the location of the error and the event which caused the error. If we would have ignored the error and therefore let it propagate further through the system, we would receive another error sooner or later. But this time the information about its location and the root cause would be misleading. Moreover, the error may have caused so much damage to the system state and possibly also data so that the only solution would be to restart the system or even restore of the data from backup.

Since Java 1.4 we can use assertions to check for various erroneous situations. Assertion in Java (and also C and C++ to name a few) is a precondition which must be met at a given point of the execution. If the precondition is met, the application continues normally. However, if the precondition is not met, error AssertionError is thrown which immediately aborts the execution of the application. AssertionError may contain additional information describing why the precondition failed.

The typical usage of assert is as follows:

package com.example;

public class Sorter {
    public void sort(int[] array, int left, int right) {
        assert array != null : "Array is not null";
        assert (left >= 0 && left < array.length) : "Invalid left index";
        assert (right >= 0 && right < array.length);
        assert left < right;
    }

}

Keyword assert is followed by a condition which should evaluate to true if everything is fine. The condition may be optionally followed by a colon and the message that should become part of AssertionError and will be presented to user. If the message is omitted, it may be sometimes difficult to precisely identify which assertion failed. Therefore, it is suggested to always provide the message for assertion.

In Java assertions are not checked by default. To force JVM to check them, JVM must be started with -enableassertions or -ea:

[robert@epsilon ~]$ java -ea com.example.Sorter

It is also possible to achieve higher granularity by enabling assertions for selected packages only:

[robert@epsilon asserts]$ java -ea:com.example... com.example.Sorter

or selected classes:

robert@epsilon asserts]$ java -ea:com.example.Sorter com.example.Sorter

There are also options to disable assertions: -disableassertions or -da. The common use case for this would be to have assertions enabled globally but disable them only for specific packages or classes. Though, I personally don’t find this feature useful.

Main uses

Asserts are commonly used to check preconditions, postconditions and invariants inside a method. The preconditions are present at the beginning of the method and usually check arguments passed to the method but they may also check internal state of the object.
Postconditions are present at the very end of the method and ensure that the actions executed in given method did not break internal state of the object and left it in a good shape.
Conditions inside methods are often used to document assumptions made during development.
To make it clear let’s take a look at the example of list which keeps only even values – if value is odd it is rounded up to the nearest even value.

package com.example.blogtest;

import java.util.ArrayList;
import java.util.List;

public class EvenList {
    
    private List<Integer> list = new ArrayList<>();
    
    public void addAllWithRounding(int[] array) {
        // check preconditions
        assert array != null : "Array not null";

        final int oldListSize = list.size();
        for (int value : array) {
            if (value % 2 == 0)
                list.add(value);
            else {
                // document our assumption that the value here would be always odd
                assert value % 2 == 1 : "Value is odd";
                list.add(value + 1);
            }
        }

        // check postconditions
        assert list.size() == oldListSize + array.length : String.format(" %d == %d + %d", list.size(), oldListSize, array.length);
        for (int i = 0; i < list.size(); i++)
            assert list.get(i) % 2 == 0 : String.format("%d is even", list.get(i));
    }
}

Here we have preconditions that check if the passed argument is right. We also have condition that documents and verifies our assumption that at this point of execution the value must be odd. In this case the assumption is trivial but in reality it may not be that obvious. Additionally, at the end of the method we have two postconditions: first checks if the size of the list is correct and the other if the list still contains only even values. Also note that the message for assertion does not have to be a constant but may be dynamically created.

Choosing between assert and throwing exception

If you look at the Sorter or EvenList classes above, you may wonder why not just throw the exception (NullPointerException or IllegalArgumentException) instead of wasting time with assertions (not to mention the need to pass additional option to JVM). The truth is that there is no simple rule defining which to choose and it depends on the concrete situation.

I find assertions to be very useful in postconditions and to document assumptions made inside methods. The usage in preconditions depends strongly on how I expect the method to be called. If the method is private or I control every point from where it can be called and can ensure that the arguments will be always valid, I prefer assert. However, if the method is a part of public interface and can be called by some other people (e.g. is part of library), it is definitely better to throw exceptions.

Assertions in production

The common practice regarding the assertions is that assertions are enabled during development and testing but they are disabled when the final product is installed into production environment. It is sometimes quoted that “removing assertions is a bit like wearing a life-jacket to practice in the harbour, but then leaving the life-jackets behind when your ship leaves for open ocean”. In my opinion this practice somehow conflicts with rules of defensive programming but on the other hand it prevents the situation that the software crashes in front of the customer due to unmet precondition.

Posted in Defensive programming, Java, Software development practices | Tagged , , , | Leave a comment

Assertions on Android

If you program in Java on Android, you know that Android has its own virtual machine called DalvikVM which is not compatible with JVM from Oracle. In fact, the difference is so big that you cannot run plain Java application on Android and vice-versa. Moreover, because you cannot run the JVM directly, it is impossible to enable assertions by passing ‘-enableassertions’ or ‘-ea’ parameters. In this post I would like to describe several ways how to go around this issue.

The first method is to verify precondition using if and throw exception (e.g. IllegalArgumentException, NullPointerException or AssertionError) if the condition is not met:

import java.util.ArrayList;

public class Chain {

	private final ArrayList<ChainCommand> chainCommands = new ArrayList<ChainCommand>();

	public void addChainCommand(ChainCommand cmd) {
		if (cmd == null)
			throw new AssertionError("Null command");
		chainCommands.add(cmd);
	}
}

It is less convenient and longer to write than plain assert but it just works out of the box. Of course, you can write your own method which encapsulates it.

Another popular method is to use various assert methods from JUnit Assert class. It is shorter than previous one and also just works.

import java.util.ArrayList;
import junit.framework.Assert;

public class Chain {

	private final ArrayList<ChainCommand> chainCommands = new ArrayList<ChainCommand>();

	public void addChainCommand(ChainCommand cmd) {
		Assert.assertNotNull(cmd);
		chainCommands.add(cmd);
	}
}

The disadvantage of this solution is that assertions cannot be disabled when you want to release your application to public (e.g. on Google Play) unless you use ProGuard to strip them.

Third way (which is what you are probably looking for) is to use assert normally in your code:

import java.util.ArrayList;
import junit.framework.Assert;

public class Chain {

	private final ArrayList<ChainCommand> chainCommands = new ArrayList<ChainCommand>();

	public void addChainCommand(ChainCommand cmd) {
		assert cmd != null : "Command is null";
		chainCommands.add(cmd);
	}
}

and enable assertions on your device (e.g. telephone, tablet or emulator) by setting debug.assert property to 1:

[robert@epsilon ~]$ adb shell setprop debug.assert 1

The assertions will be enabled for all applications until the device is rebooted. There are also few other ways to enable assertions and some of them require the device to be rooted but these three mentioned above should be enough for daily work.

Posted in Defensive programming, Java, Software development practices | Tagged , , , , , | 5 Comments

Try-with-resources

Java is widely known and respected for its automatic memory management. It makes the programs easier and faster to write because the developers does not have to manually track which objects are no longer used and can be freed or deleted from memory. In Java it is the responsibility of garbage collector (GC) to track unused objects and deallocate them.

However, in vast majority of applications there are more types of resources used than just memory – programs open files, connect to other applications via sockets or access databases via various IPC mechanisms. All of these resources are not managed by GC and are more scarce than memory. For example operating system may enforce limits on the number of concurrently opened file descriptors. Assuming that the limit is quite low (on my system it is 1024) and the application sometimes “forget” to close file, in short time the operating system may prevent the application from opening files any more because it reached the limit of opened file descriptors. The result is obvious – the application stops working and has to be restarted. This problem is most visible in applications that run for hours or days like servers or services. But even in small applications, one should still properly close resources.

How it should never be done

Let’s take a look at the first simple example how you should NEVER handle resources:

package com.example.blogtest;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class WriteFileWrong {

    private final static int bufferSize = 1024;
    private byte[] buffer = new byte[bufferSize];

    public void copyFile(String srcPath, String destPath) throws IOException {

        InputStream is = new FileInputStream(srcPath);
        OutputStream os = new FileOutputStream(destPath);
        while (true) {
            int readBytes = is.read(buffer);
            if (readBytes == -1) {
                break;
            }
            os.write(buffer, 0, readBytes);
        }
        is.close();
        os.close();
    }
}

First thing to notice is that we are pushing IOException up to the caller. It is fine and is a very common practice if we don’t know how to handle it. The problem in this example is that if constructor of FileOutputStream will throw IOException (quite likely), we will exit the method prematurely without closing first stream. The similar problem happens for read and write methods but the exception is less likely to appear.

Unfortunately, I often see such code in examples and books. What’s worse I even saw the code that does not even try to close the resource. It’s quite sad that they are teaching wrong practices even though doing it properly is not difficult.

Try-with-resource in Java 7

There are many ways to properly handle resource closing in Java but I would like to first show you the easiest one which was introduced in Java 7 – try-with-resources.

Try-with-resources construct automatically closes the resources, which were specified at the beginning of try block, after try block finishes (either normally or as a result of exception). There is no longer need to manually close the resource. The example should explain almost everything:

package com.example.blogtest;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class WriteFileTryWithResources {

    private final static int bufferSize = 1024;
    private byte[] buffer = new byte[bufferSize];

    public void copyFile(String srcPath, String destPath) throws IOException {

        try (InputStream is = new FileInputStream(srcPath);
             OutputStream os = new FileOutputStream(destPath)) {
            
            while (true) {
                int readBytes = is.read(buffer);
                if (readBytes == -1) {
                    break;
                }
                os.write(buffer, 0, readBytes);
            }
        } finally {
            // is and os streams will be closed automatically now even if exception occurs
        }
    }
}

If everything goes fine and no exception will be raised, is and os streams will be closed automatically as soon as the try block finishes.
If the exception is raised by FileOutputStream constructor, the execution will jump to finally block and the is stream, which was opened before, will be automatically closed.
If the exception is raised by read or write methods, the execution will jump to finally block and both is and os streams, which were opened before, will be automatically closed.

Requirements on resources in order to use them in try-with-resources

If you want to use the resource in try-with-resources block, it must implement AutoClosable interface. The definition of AutoClosable interface is pretty obvious:

package java.lang;

public interface AutoCloseable {
    void close() throws Exception;
}

If you take a look at AutoClosable you will notice that (almost?) all resources provided as part of Java 7 (including file streams, sockets and many more) implement this interface either directly or via Closable interface (which in turn extends AutoClosable interface). This means that we don’t have to worry about this unless we want to use our own class as resource.

Suppressed exception

If you take a close look at AutoClosable interface, you may notice that close() method may throw exception if an error appear while closing the resource. Because we cannot throw multiple exceptions at once in Java, you may wonder what happens to this exception or the original exception thrown in try block (if it occurs). Actually, the exception which appeared first will be thrown further and the rest of the exceptions will be attached to it and can be retrieved from it using Throwable.getSuppresed() method.

To visualize it let’s implement our own autoclosable resource:

package com.example.blogtest;

import java.io.IOException;

public class IntReader implements AutoCloseable {

    private int value;
    
    public IntReader(int value) {
        this.value = value;
    }

    public int readPositiveValue() throws IOException {
        if (value > 0)
            return value;
        else
            throw new IOException("Cannot read because value is not positive");
    }
    
    @Override
    public void close() throws Exception {
        if (value <= 0)
            throw new IOException("On close value was invalid");
    }
    
}

and use it in try-with-resources block:

package com.example.blogtest;

public class WriteFileOwnResource {
    
    public void readAndPrintExceptions() {
        try {
            read();
        } catch (Exception e) {
            System.out.printf("Exception occured: %s\n", e.getMessage());
            for (Throwable th : e.getSuppressed())
                System.out.printf("Suppressed exception: %s\n", th.getMessage());
        }
    }
    
    private void read() throws Exception {
        try (IntReader readerOk = new IntReader(10);
             IntReader readerFail = new IntReader(-1)) {
            readerOk.readPositiveValue();
            readerFail.readPositiveValue();
        }
    }
}

Object instance readerOk will not throw any exception because its value is positive but readerFail will throw first exception during call to readPositiveValue and another one when leaving the try block (when close() method will be automatically called on it). The first exception will be the main exception and the exception thrown by close() method will be available as suppressed exception. Therefore, the output of the code will be:

Exception occured: Cannot read because value is not positive
Suppressed exception: On close value was invalid
Posted in Java | Tagged , | Leave a comment

Test driven development

Test driven development is an important and valued part of agile practices. In test driven  development (in short TDD) developers first write tests for new functionality (e.g. a class) and later they implement it. The order is crucial and I will explain later why.

Let’s assume that the developer needs to implement new class PathCalculator which calculates distance between 2 points. The developer has a general idea about the class, that he wants to implement, and could start implementation of it method by method. If he is smart and the problem is not very complicated, he will do it without big problem. Then the class can be integrated into the existing application structure and the new version of the system can be tested. This was easy but many issues can arise if the problem is more complicated:

  1. the developer may have a vague  idea about how this class should be accessed from outside (not to mention how to implement it!)
  2. after the code for the class is finished, the developer could find out that one or more important methods are missing or the existing methods miss parameters (or something else) to integrate it successfully into existing application structure
  3. after integration, the new functionality misbehaves or even breaks other functionality for some unknown and hard to trace reason

All of these problems could have be more-or-less avoided (actually TDD is not a silver bullet which solves all problems) if TDD was used.

Basics of TDD

In TDD we first write one or more tests for the new class to find out the how it should be accessed from outside and how it should behave in certain situations. We should specify the usage in typical situation and in certain border cases. Of course, it is impossible to catch all such cases but we should at least try. Let’s look at the implementation of it using Java and JUnit.

package com.example;

import org.junit.Test;
import static org.junit.Assert.*;

public class PathCalculatorTestCase {

    private static final double DELTA = 0.001;

    @Test
    public void test1() {
        PathCalculator pathCalc = new PathCalculator(PathCalculator.Type.EUCLIDAN);
        double distance;

        distance = pathCalc.getDistance(1, 1, 6, 7);
        assertEquals(distance, Math.sqrt(5 * 5 + 6 * 6), DELTA);

        distance = pathCalc.getDistance(1, 1, 1, 2);
        assertEquals(distance, 1.0, DELTA);

    }

    @Test
    public void test2() {
        PathCalculator pathCalc = new PathCalculator(PathCalculator.Type.EUCLIDAN);
        double distance = pathCalc.getDistance(7, 8, 7, 8);
        assertEquals(distance, 0, DELTA);
    }

}

At the moment our code does not compile at all because we are missing class PathCalculator. The most important thing is that we defined how the new class should behave and we decided on its interface. Let’s add a stub for PathCalculator class with empty methods:

package com.example;

public class PathCalculator {

    enum Type {
        EUCLIDAN,
        MANHATTAN
    }

    public PathCalculator(Type type) {
        // TODO:
    }

    public double getDistance(int x1, int y1, int x2, int y2) {
        // TODO:
        return 0;
    }

}

Running tests with Maven

In order to run the tests just create own project directory, put PathCalculatorTestCase class in project directory under src/test/java/com/example/PathCalculatorTestCase.java, put PathCalculator class in project directory under src/main/java/com/example/PathCalculator.java and finally add pom.xml file in the project directory with following contents:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>javatest</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>javatest</name>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>      
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.13</version>
            </plugin>
        </plugins>
    </build>

</project>

Once it is done the tests can be run like this:

robert@epsilon blogt]$ mvn test
(...)
-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.example.PathCalculatorTestCase
Tests run: 2, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.069 sec <<< FAILURE!
test1(com.example.PathCalculatorTestCase)  Time elapsed: 0.01 sec  <<< FAILURE!
java.lang.AssertionError: expected:<0.0> but was:<7.810249675906654>
(...)

The code should compile and all the tests will be run but they will fail because the methods are just empty. It is completely OK for now. The last step is to implement the empty methods and run the tests again to check if the tests finish successfully. In practice it is necessary to run the tests many times to implement the code right.

Additionally, tests limit the number of issues during integration of the class into existing application because many of the bugs were found by tests during implementation step. They also allow us to assume certain behaviour from the class and easier spot the rest of the bugs.

How to write the tests

The general idea is to have each class method called at least once in tests with typical arguments (e.g. list with few elements) and also call it few times with border cases (e.g. null value, empty list, list with one element). The reason should be obvious. There is no need to test getters and setters, if the only thing they do is just calling return or setting value. If they do some calculations or propagate the value further, we should test them.

The other important thing is that each test should be concise and should test only one thing. Don’t try to write a big master test which tests it all but split it into many specific tests. Remember, that you can always create many methods in *TestCase class and when it becomes too big, you can create additional *TestCase class with new tests.

Maintenance

The importance of tests does not finish after implementing the class and integrating it into existing application. In real world the requirements are often changing so they may be a need to adapt the class to new requirements after a month or half a year. In this case modify the existing tests or add new ones so they match new requirements. The tests will be failing again but the next step is obvious – modify the implementation of the class so that the tests succeed again.

The tests are also important when changing the implementation of the class. It may be fixing a bug, improving performance or refactoring. Before committing code into SCM, run the tests again to make sure they succeed (in which case we can more-or-less assume that we did not break something else). Of course, it is advised to run the tests more often. Additionally, if we are fixing a bug we should add additional test (called regression test) which verifies if the bug was resolved and will not appear in the future (you would be surprised to see how often bugs fixed long ago reappear).

Sum up

I would like to sum up the article by listing the advantages and disadvantages of TDD.
Advantages:

  • Encourage designing interface and defining usage and behaviour before coding the implementation
  • Gives general overview how the class should be used
  • Automatically verify if new modification to class does not break some other functionality
  • Automatically verify if refactoring step does not change the visible behaviour of the application

Disadvantages:

  • Require additional time to write the tests and maintain them
  • Require additional time to run the tests
  • Require additional time to change the tests if the interface of tested class changes

In my opinion additional time spent for tests is an investment which will return quickly in increased testability and quality of the software. Always remember that the TDD is not solver bullet – it does not solve all problems and even though your tests are passing, it does not mean that there are no bugs.

Posted in Java, Software development practices | Tagged , , , , | 2 Comments

Time configuration in Windows/Linux dual-boot.

Many Linux users still have Windows installed on their machines for some reason (playing games, using specialized Windows-only applications and so on). The coexistence of Windows and Linux on the same physical machine is called dual-boot.

One of the main issues when dual-booting is time configuration. It is because Windows is often known not to support RTC being in local-time. For this reason the common configuration is like this:

  • RTC clock is set to local-time in BIOS Setup
  • Windows is left untouched and still treats RTC as being in local-time
  • Linux is reconfigured to treat RTC as being in local-time

However, for some time now, Windows can be configured to treat RTC clock as being in UTC time. It can be done by setting the following registry key

HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation\RealTimeIsUniversal

to a DWORD value 1 and restarting the Windows. After restart the time shown in Windows may be invalid and shifted by a few hours from the real time, so it needs to be corrected either in BIOS Setup or under Linux using date or ntpdate commands.

This is known to work generally fine in Windows Vista SP2 and Windows 7 but there are still some known issues:

  1. Windows is unable to modify RTC clock when RealTimeIsUniversal=1 which means that any time change done in Windows will not persist after the reboot. It is not a big problem because the persistent time change can be done directly in BIOS Setup or in Linux.
  2. The time may be shown wrongly after resuming a suspended or hibernated Windows.
  3. The old DOS application may show the time wrongly.

References:
1. IBM PC Real Time Clock should run in UT

Posted in Linux | Tagged , , | Leave a comment