Author Archives: erik

Singletons: Bill Pugh Solution or Enum

In this blog post, Harinath Kuntamukkala discusses different approaches to the Singleton pattern. The first implementation he goes over is the Bill Pugh Solution, which is similar to the implementation we learned in class except it uses a static inner helper class as in the example below:

public class Logger {
    private Logger() {
        // private constructor
    }
    // static inner class - inner classes are not loaded until they are
    // referenced.
    private static class LoggerHolder {
        private static Logger logger = new Logger();
    }
    // global access point
    public static Logger getInstance() {
        return LoggerHolder.logger;
    }
    //Other methods
}

This would be the best approach but it’s possible for more than one instance to be created with the use of Java reflection. For example:

public class LoggerReflection {
    public static void main(String[] args) {
        Logger instance1 = Logger.getInstance();
        Logger instance2 = null;
        try {
            Constructor[] cstr = Logger.class.getDeclaredConstructors();
            for (Constructor constructor: cstr) {
                //Setting constructor accessible
                constructor.setAccessible(true);
                instance2
                    = (Logger) constructor.newInstance();
                break;
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println(instance1.hashCode());
        System.out.println(instance2.hashCode());
    }

The solution to the problem suggested by Joshua Bloch, is to use Enum. The reason we use Enum is because Java ensures that any Enum value is instantiated only once. Using Enum, this is what the Logger class would look like


public enum Logger {
    INSTANCE;
    //other methods
}

It’s still possible for more than once instance to be created if a singleton object is serialized, then deserialized more than once. In order to avoid this you can implement a readResolve() method in the Logger Singleton class:


public class Logger implements Serializable {
    //other code related to Singleton
    //call this method immediately after De-serialization
    //it returns an instance of singleton
    protected Object readResolve() {
        return getInstance();
    }
}

The reason I chose this resource is because we are currently learning about design patterns and just reviewed the singleton pattern. This post goes into the best implementations of the singleton pattern and why that is, I would like to stay on-top of the most effective, clean and efficient implementations of design patterns. I think this is a useful post, and learned about the Bill Pugh Solution and the Enum solution to ensure there’s only one instance of a singleton object. The author concluded that the Enum approach is the best solution as it is

“functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiations, even in the face of sophisticated serialization or reflection attacks.”

I expect to take what I learned in this article and use it whenever implementing the singleton design pattern, and I might rework the code I have now to make use of the Enum approach talked about in the article.

The post Singletons: Bill Pugh Solution or Enum appeared first on code friendly.

From the blog CS@Worcester – code friendly by erik and used with permission of the author. All other rights reserved by the author.

Single Statement Unit Tests: Making tests more object oriented

In a post by Yegor Bugayenko, Single Statement Unit Tests,

“..I believe, can help us make our tests, and our production code, more object-oriented. Here it is: a test method must contain nothing but a single assert.”

He makes use of the assertThat() that is available from Hamcrest. Benefits to using assertThat() are: Reusability. Classes needed to create test assertions are reusable in other test methods and test cases. Brevity. Shorter and readable code that’s easy to understand. Readability. Using a single assert, the intent of the test will always be apparent. Immutability. No need for setters or getters if we limit use of algorithmic code in tests.

He uses and example method RandomStreamTest from OpenJDK 8, created by Brian Goetz:

@Test
public void testIntStream() {
final long seed = System.currentTimeMillis();
final Random r1 = new Random(seed);
final int[] a = new int[SIZE];
for (int i=0; i < SIZE; i++) { a[i] = r1.nextInt(); } final Random r2 = new Random(seed); final int[] b = r2.ints().limit(SIZE).toArray(); assertEquals(a, b); }

In this example there are two parts, the algorithm which creates two arrays of integers and the assertion which compares them using assertEquals(). The author recommends modifying the code to look like this:

@Test
public void testIntStream() {
final long seed = System.currentTimeMillis();
assertEquals(
new ArrayFromRandom(
new Random(seed)
).toArray(SIZE),
new Random(seed).ints().limit(SIZE).toArray()
);
}
private static class ArrayFromRandom {
private final Random random;
ArrayFromRandom(Random r) {
this.random = r;
}
int[] toArray(int s) {
final int[] a = new int[s];
for (int i=0; i < s; i++) { a[i] = this.random.nextInt(); } return a; } }

The change is the test is that there is only one statement in the method now.

Yegor notes

"The biggest benefit we get when this principle is applied to our tests is that they become declarative and object-oriented, instead of being algorithmic, imperative, and procedural."

I chose this resource because it's an interesting way to design tests and the benefits of using assertThat() might be of use to me in the future. I think it is important to keep up on the best unit-testing practices if I want to write good code to match. I'm also interested in looking more into Hamcrest.

Using assertThat() allows you to write relatively short test cases that are clear what is being tested. Sometimes tests can become bogged down with too many assertEquals() and setters and getters. Using assertThat() allows you to simply compare two immutable objects. I plan on using this, or at least trying to implement it whenever writing tests in the future along with whatever makes writing tests more readable, understable and object oriented.

The post Single Statement Unit Tests: Making tests more object oriented appeared first on code friendly.

From the blog CS@Worcester – code friendly by erik and used with permission of the author. All other rights reserved by the author.

The Importance of Patterns in DDD

In this post, Jan Stenberg describes a conference in Amsterdam lead by Cyrille Martraire, Founder of the Paris Software. Martraire stresses the importance of knowing and evolving design patterns. Noting a few examples,

“…Exceptional Value which makes it possible to write code as a business domain statement by removing all need for special case handling like dealing with illegal or zero values. Another pattern that he has found particularly interesting is Diagnostic Query, a pattern which suggests that an object should be able to describe how it reached its current state, a diagnostic ability that replaces the need for logging and debugging. A Money object with a value of 100 EUR could then describe that the amount came from adding a certain amount of GBP with an amount of USD.”

In reference to modeling domain concepts and their relationships, Martraire found these patterns to be very useful:

Composite for composing objects into tree structures and letting a client treat individual objects and compositions uniformly.
Interpreter for evaluating sentences in a language.
Flyweight that uses sharing to support large numbers of fine-grained objects.
Strategy for separating algorithms themselves from their usage.

Martraire says that learning and implementing new and sometimes more simple design patterns will help you apply them in new domains.

The post The Importance of Patterns in DDD appeared first on code friendly.

From the blog CS@Worcester – code friendly by erik and used with permission of the author. All other rights reserved by the author.

The Business Case for Unit Testing

In this post, Erik Dietrich talks about the importance of making sure developers are well-trained in writing units tests.

“If you have developers writing good unit tests, you’ll develop a nice, robust unit test suite over the course of time. Developers will run this test suite constantly, and they’ll even have the team build to run it in a production-like environment.”

Making sure your units tests are well written and easy for maintainers to understand helps prevent regression, like a developer editing code and breaking functionality elsewhere.

“Testable code is better code, as measured by how easy it is to change that code.”

Writing better unit tests allows for bugs to be caught earlier and increases functionality and modularity, saving businesses money and making you a better developer with a more productive team.

The post The Business Case for Unit Testing appeared first on code friendly.

From the blog CS@Worcester – code friendly by erik and used with permission of the author. All other rights reserved by the author.

first post on cs-443

Hi everybody, this is my first post on CS-434 Software Quality Assurance and Testing.

The post first post on cs-443 appeared first on code friendly.

From the blog CS@Worcester – code friendly by erik and used with permission of the author. All other rights reserved by the author.

first post on cs-343

Hi everybody, this is my first post on CS-343 Software Construction, Design and Architecture.

The post first post on cs-343 appeared first on code friendly.

From the blog CS@Worcester – code friendly by erik and used with permission of the author. All other rights reserved by the author.