I’ve been Nestified

Yesterday I made a big jump, I replaced the old hard-to-program programmable thermostats in my house with fancy new Nest Learning Thermostats.  They’re a snap to install and, currently, many energy companies are giving significant rebates when you buy one.  However, the real reason I got them was cause they’re freaking cool devices with lots of neat ways to interact with them.  Being able to control or check in on the temperature on your house from the phone is really very cool and the fact the Nest uses weather reports to help control the temperature in the house is even neater still. Once it’s been a few weeks I’ll write a little more in depth review about the Nest and if it is actually saving me any money on electricity bills. Until then, I’m saying it’s worth buying just for the tech alone. :)

@Autowired considered harmful

I guess I’m on an opinionated roll, after declaring my dislike of the Singleton design pattern, I’m taking a swing at @Autowired.

Spring is a great framework for application development for Java and even though it’s now arguably more complex than Java itself, it’s advantages far outweigh the problems.  The best part of it to me is the IoC container however, it has introduced one of the largest poxes (next to Singleton :)) to Java coders everywhere: @Autowired.  I’ve seen more problems occur in code due to the use of @Autowired and package scan.  In fact, Colin Yates of Expert Spring MVC + Webflow fame, has this to say about autowiring:

If you insist on sticking with autowiring, there are three different types of autowiring … bad, dangerous and terrible.

And I don’t think I can say it much better than that.

Musings on Career Improvement: Switching Jobs

This isn’t so much a programming post or even a post on how to make yourself better.  It’s a post musing about switching jobs and how people look at switching jobs.  The idea that you’ll stay with one company for your entire career is an idealism best left in the 1950s since it in no way matches how business is done today. It’s now up to you to guide your career. A career is a succession of jobs that move you toward a goal. In some cases, it might only take two jobs to make someone happy or feel that they’ve reached where they want to be. For others, it could be various jobs with multiple companies or a few jobs with one company and then a few more jobs with another one still. Point being, you can’t count on a company to be your career.

Singleton: A Design Pattern Past Its Time?

I recently had a conversation with someone and in passing I said something along the lines of singleton being a pointless design pattern and something that I’d try my best to not use. They said there were lots of reasons for a singleton, then we moved onto a different topic.  However, it’s gotten me thinking, is there really a reason for the use of a singleton?  I did some digging through StackOverflow and found a few reasons as to why to use one — but even then, it wasn’t a glowing endorsement.  Nothing I’ve seen has really made me change my mind from the fact that the singleton pattern is something with very limited usability and most people seem to view the singleton pattern as a pox on the programming world.

Personally, I’d stay as far as way as possible from them unless absolutely necessary.

What do y’all think?  Is it now an anti-pattern or is it something that is still useful?

Testing in Java: Part II – Writing a Fake

In the first part we talked about the domain objects and how to test a domain object.  Now it’s time to look at how to persist them to an in-memory data store for testing purposes.  We’ll be writing this in such a way that at a later date you can replace the in-memory representation with a strategy that persists the data to disk.  So, let’s jump right into the code starting with the data access object interface.

package com.laneholloway.unittestingexample.database.dao;

import com.laneholloway.unittestingexample.domain.MyItem;

import java.util.UUID;

/**
 * A simple Data Access Object
 */
public interface MyDao {
    public boolean exists(UUID guid);
    public MyItem get(UUID guid);
    public boolean save(MyItem item);
    public void delete(UUID guid);
}

Looking at the code you can easily tell that there are some simple CRUD operations and an exists command. Any datasource that we want to write the data to must implement these commands and inside the program, we should only use these commands to interact with the object. In order to facilitate the testing of the framework, I’ve created a simple in memory dao and placed it into the test directory that maven creates.

package com.laneholloway.unittestingexample.database.dao;

import com.laneholloway.unittestingexample.domain.MyItem;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * An in-memory representation of a datastore using MyDao
 */
public class MyInMemoryDao implements MyDao {
    private Map<UUID, MyItem> storedItems;

    public MyInMemoryDao() {
        this.storedItems = new HashMap<UUID, MyItem>();
    }

    @Override
    public boolean exists(UUID guid) {
        return this.storedItems.containsKey(guid);
    }

    @Override
    public MyItem get(UUID guid) {
        return this.storedItems.get(guid);
    }

    @Override
    public boolean save(MyItem item) {
        this.storedItems.put(item.getGuid(), item);
        return true;
    }

    @Override
    public void delete(UUID guid) {
        this.storedItems.remove(guid);
    }
}

The in memory dao uses a Map to hold the MyItem elements. As you can tell, the implementation is straight-forward and doesn’t pull any punches. It does exactly what it needs to do in order for us to test other parts of the system that require the use of the MyDao interface. In order for the other Maven modules to use this test implementation, we have to do a little work in Maven to expose this as a test class. In the POM file relating to the doa-interface module, we add this bit which creates a test jar file.

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

Now, using this test jar we can begin to test classes that use the MyDao interface. To use this test jar you modify the POM files for all modules that need access to this code with a dependency with it’s scope set to test.

In our case, we have the MyCommonInterface class which you’ll typically see in applications to give the consumers of the code a unified API to the CRUD operations abstracting away the DAO or DAOs that might make up the data storage of the application.

package com.laneholloway.unittestingexample.database.commoninterface;

import com.laneholloway.unittestingexample.domain.MyItem;

import java.util.UUID;

/**
 * A common interface to abstract away the various DAOs and allow the consumer of the API one interface to all
 * data.
 */
public interface MyCommonInterface {
    public boolean exists(UUID guid);
    public MyItem get(UUID guid);
    public boolean save(MyItem item);
    public void delete(UUID guid);
}

I’ve also supplied a simple implementation that uses a single DAO,

package com.laneholloway.unittestingexample.database.commoninterface;

import com.laneholloway.unittestingexample.domain.MyItem;
import com.laneholloway.unittestingexample.database.dao.MyDao;

import java.util.UUID;

/**
 * A very simple common interface
 */
public class MyCommonInterfaceForOneDao implements MyCommonInterface {
    private final MyDao dao;

    public MyCommonInterfaceForOneDao(MyDao myDao) {
        this.dao = myDao;
    }

    @Override
    public boolean exists(UUID guid) {
        return this.dao.exists(guid);
    }

    @Override
    public MyItem get(UUID guid) {
        return this.dao.get(guid);
    }

    @Override
    public boolean save(MyItem item) {
        return this.dao.save(item);
    }

    @Override
    public void delete(UUID guid) {
        this.dao.delete(guid);
    }
}

You can see that in the constructor, it expects a variable of type MyDao and then uses to perform CRUD operations. In order to properly test this, we need to use the in memory implementation so we don’t have to worry about creating a database, cleaning the database, and all the other database tasks needed just to test this interface. Using the this implementation, we can create a JUnit test class like this:

package com.laneholloway.unittestingexample.database.commoninterface;

import com.laneholloway.unittestingexample.database.dao.MyDao;
import com.laneholloway.unittestingexample.database.dao.MyInMemoryDao;
import com.laneholloway.unittestingexample.domain.MyItem;
import com.laneholloway.unittestingexample.domain.MyItemImpl;
import org.junit.Before;
import org.junit.Test;

import java.util.UUID;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class MyCommonInterfaceForOneDaoTest {
    private MyCommonInterfaceForOneDao myCommonInterfaceForOneDao;

    @Before
    public void setup() {
        MyDao myDao = new MyInMemoryDao();
        myCommonInterfaceForOneDao = new MyCommonInterfaceForOneDao(myDao);
    }

    @Test
    public void can_save_item() throws Exception {
        MyItem myItem = new MyItemImpl(UUID.randomUUID(),"Test Item");
        myCommonInterfaceForOneDao.save(myItem);
        assertTrue(myCommonInterfaceForOneDao.exists(myItem.getGuid()));
    }

    @Test
    public void can_delete_item() throws Exception {
        MyItem myItem = new MyItemImpl(UUID.randomUUID(),"Test Item");
        myCommonInterfaceForOneDao.save(myItem);
        myCommonInterfaceForOneDao.delete(myItem.getGuid());
        assertFalse(myCommonInterfaceForOneDao.exists(myItem.getGuid()));
    }
}

In the setup method, you can see that MyInMemoryDao is initialized and then injected into the MyCommonInterfaceForOneDao constructor which then allows these simple unit tests to be run verifying the correct operations. And with this, we’ve wrapped up the second section of the code, creating a data access layer that abstracts the database away from the production code and will allow multiple implementations of the data store to be used with minimal issues.

In later articles, I’ll show how to use Spring to simplify these tests and the application itself. Next time, we’ll talk about the business logic and REST layers of the code.

If you have any comments, concerns, or updates I should make to this, let me know in the comments below.

Book Review: How to Light Up A Room

After reading the not-so-hot Who Moved My Cheese?, I picked a book on how to be more charismatic.  I feel I’m a very good socializer and communicator, but at the same time, I also know I can become introverted. So, any book that can provide a tip or a hint is a good thing in my opinion.  There are a few things that this book really has going for it.  First, it’s cheap, at $2.99, it’s hard to really go wrong.  Secondly, it’s short.  I read the entire book in under a few hours.  However, don’t let the fact it’s short put you off.  A short book can be bad or it can be great when it’s to the point.  And that is the third thing I like about the book, it’s to the point.  No building up, just all the information you need to know and none that you don’t.

Now with the introduction, let’s get to the meat of the review — which I’ll keep short and sweet — much like the book itself.  It contains a very small introduction about the 55 tips discussed inside of the book and then jumps right into the tips which are split into six different categories but fall into two major ideas: being upbeat and interacting with people.  Each tip is a simple sentence with a paragraph or two of explanation of how to use the tip in day-to-day interactions.

Chances are you’ll blow through this book in one sitting and to me that is fine.  It saves me from having to read all the other books about building charisma since this book has already summarized the majority of these books.  For the $2.99 that it costs from Amazon.com (or free rental if you have a Kindle device), it’s well worth it.