shortcuts don’t

Forcefully moving to a new computer sometimes leads to windy ways of encountering things you once wrote. Thoughts flash through the mind. Is it possible to instantiate a singleton at class loading time? Is class loading thread safe? Could it be as easy as instantiating the singleton object in a static block just like… 

No. I’m possibly not the first one coming up with that shortcut. And class loading happens to be thread safe. That’s good. But a loaded class is identified by its fully qualified name in combination with the identification of the class loader that loads the class. That makes it possible – feasible even – that a class is loaded by more than a single class loader and consequently a static block in the class file is executed more than once.

See? There are no shortcuts. Just do it the ‘proper way’. 

static data, static methods, singletons, factories and utilities

I think that the Java keyword ‘static’ is an inheritance from C. Most of the time saying that a method is static is a way to say that the method is a class method – that is, a method that operates on the type – as opposed to an instance method – that is, a method that operates on an instance of the type.

One of the best examples of static methods are constructors. They only can operate on a class even if they create an instance of that class as a result.

Now let’s have a look at singletons, utility classes and factories.

Singletons

Singletons obviously rely on the fact that if one declares a class member static it can only occur once per class for every instance of that class. Combine that with the fact that a class is unique in the context of a program then you realize it is a good way to implement a singleton. Not the only one but a good one. Now, if you want to be able to access the singleton object then you can use a static method to do that. You don’t need to but it is the easiest way. As soon as one has access to the singleton object, everything returns to normal and you can use the object to call any instance methods as you wish. If you want to implement a singleton in a multithreaded environment make sure that the method to retrieve and instantiate the singleton on demand is synchronized so that instantiating more than one instance of the singleton class is ruled out. For what it is worth, in most cases the static method that gets the singleton instance is called getInstance():

public class Singleton {
    private static Singleton instance = null;
 
    // Make sure we cannot instantiate this class from the outside
    protected Singleton() {
    }

    // Retreive te instance creating it if necessary. Synchronize to prevent race conditions.
    public static synchronized getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

Utilities

Utility classes use class methods because it is a way to ‘scope’ global functions. Since Java requires the use of a class it is the only way to write something that resembles a regular function. I must say that scoping functions by their aspect is a good thing. Most of the time it turns out that this way the intent of a utility function is communicated in a better way.

Factories

Factories are in fact utility classes that ‘produce’ things. Objects of a certain class mostly. Because factories are collections of one or more utility functions that call a constructor based on a particular set of arguments without the need to have more than one instance it is convenient to implement that as a class solely containing a set of class methods.

double fail

Here is what is dubbed the ‘Apple Bug’:

static OSStatus
SSLVerifySignedServerKeyExchange(SSLContext *ctx, bool isRsa, SSLBuffer signedParams,
                                 uint8_t *signature, UInt16 signatureLen)
{
	OSStatus        err;
	...

	if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
		goto fail;
	if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
		goto fail;
		goto fail;
	if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
		goto fail;
	...

fail:
	SSLFreeBuffer(&signedHashes);
	SSLFreeBuffer(&hashCtx);
	return err;
}

So what is this? If you ask me it looks like a combination of stupid coding conventions,  a merge artifact and not enough coverage in unit tests. 

Coding conventions

A lot of coding conventions will tell you that you should use braces around blocks even if a block is only a single line. Would it have helped? Perhaps. If it would result in code like this:

	if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0) {
		goto fail;
		goto fail;
        }

It looks funny but in this case the double fail would be harmless. And a good compiler would have warned about unreachable code.

Merge artifact

Could be. Could even be caused by changes in whitespace – who knows.

Test coverage

This is a conclusion that makes me worry. This kind of error should have surfaced in unit testing this function. 

unit testing and time travel

Sometimes the solution for a thorny problem is easy. If you are writing unit tests for a piece of code that behaves differently before and after a certain point of time you wish you could do time travel with the computer you are using to run the tests. Adjusting the system date often is inconvenient. A lot of processes depend on proper timekeeping by the operating system and often a regular user cannot adjust time for simple lack of authorization. Take my advice and stay away from the system clock.

The solution is to use Joda Time. It has a class called DateTimeUtils with a static method setCurrentMillisFixed that effectively fixes the system time for the Joda Time library to a certain value. Returning to the present is done by calling setCurrentMillisSystem after you are done time traveling

    @Before
    public void before() {
        LocalDate pointInTime = new LocalDate().minusDays(10);
        DateTimeUtils.setCurrentMillisFixed(pointInTime.toDateTime(new LocalTime(0, 0, 0, 0)).getMillis());
    }

    @After
    public void after() {
        DateTimeUtils.setCurrentMillisSystem();
    }

Done.

Enjoy.

condition and return != condition && return

In dealing with the wisdom of rubocop to sanitize code I ran into the following: If you write 

redirect_to_somewhere and return

then the redirect will be followed by leaving the controller method but if you change that into 

redirect_to_somewhere && return

 as per rubocop’s instructions then it fails. Odd. What exactly is the difference between the two exactly? Of course the construct looks like a frequently used Bash idiom and in this case the two statements should be just on separate lines:

redirect_to_somewhere
return

However, http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/ learns us that there is a difference in precedence and that we really should use the &&-operator only 

iCloud Beta

Today I was invited to participate in iCloud Beta. The first experiment I did was to have a look at Pages. Really. I’m not easily impressed and I think a lot of people are going to miss bells and whistles but for an online word processor I say it is excellent. 

More about this later…

osx brew mysql-5.6.12 breaks building native extension for brianmario/mysql2

As soon as I updated mysql on my OSX machine to mysql-5.6.12 and subsequently wanted to install the brianmario/mysql2 Ruby gem hell broke loose. Precise examination of mkmf.log in the directory of the gem showed that a compiler flag was not recognized by the compiler. After mysql-5.6.10 two compiler flags are introduced in mysql_config that conflict with the gcc42 compiler needed to build gems against ruby-1.9.3 while building them against ruby-2.0.0 did not produce any problems. This is logical because the latter uses the llvm compiler instead of the gcc42 compiler to build native extensions.

The solution is to (temporarily) remove the -Wno-null-conversion -Wno-unused-private-field flags from the cflags and cxxflags in the mysql_config script located in /usr/ocal/Cellar/mysql-5.6.12/bin/ directory. 

The same error also pops up when building the mysql extension for python. Have a look at the stack overflow article that eventually lead me to the solution to the problem. Notice that there the problem starts with mysql-5.6.11 and also notice that using mysql-5.6.10 on my machine did not give trouble.

Also see: http://bugs.mysql.com/bug.php?id=69645

Enjoy!

search in rails

At the moment I’m doing a Java/Spring to Ruby/RAILS conversion for a client. That is a good opportunity to weed out old stuff from the existing application and introduce new technology to replace the old architecture. After all it’s impossible to just translate everything one-on-one from the old architecture to the new one. One of the challenges is finding a suitable replacement for the lucene-based search in Spring. After a bit of searching on the internet I found that there are basically two search engines currently used in RAILS applications and that are solr and Elasticsearch. After a bit of research I also found tire which constitutes a layer between RAILS on one end and Elasticsearch. I’m currently in the process of discovering how this works. I did discover already that Elasticsearch can do proximity searches which could be a nice extension to the system I’m currently converting…