Design Patterns: The Builder Pattern

2017 December 4 @ 10:21pm by erik


In this blog post, Riaan Nel goes over an example of the Builder Pattern, a creational pattern used to create and configure objects. The following example is from Effective Java by Joshua Bloch.

The Problem

In this example, we are part of a Java team working on software for a bank. We need a way to represent banks accounts.

BankAccount.java

public class BankAccount {
    private long accountNumber;
    private String owner;
    private String branch;
    private double balance;
    private double interestRate;

    public BankAccount(long accountNumber, 
                       String owner,
                       String branch,
                       double balance,
                       double interestRate) 
       {
        this.accountNumber = accountNumber;
        this.owner = owner;
        this.branch = branch;
        this.balance = balance;
        this.interestRate = interestRate;
   }
    //Getters and setters omitted for brevity.
}

We run into two problems in the about code:

  • Too many constructor arguments
  • Incorrect object state

The Pattern

The builder pattern “allows us to write readable, understandable code to set up complex objects. It is often implemented with a fluent interface, which you may have seen in tools like Apache Camel or Hamcrest.” The builder will


public class BankAccount {
    public static class Builder {
        private long accountNumber; 
        private String owner;
        private String branch;
        private double balance;
        private double interestRate;

        public Builder(long accountNumber) {
            this.accountNumber = accountNumber;
        }

        public Builder withOwner(String owner){
            this.owner = owner;
            return this; 
        }

        public Builder atBranch(String branch){
            this.branch = branch;
            return this;
        }

        public Builder openingBalance(double balance){
            this.balance = balance;
            return this;
        }

        public Builder atRate(double interestRate){
            this.interestRate = interestRate;
            return this;
        }

        public BankAccount build(){
            BankAccount account = new BankAccount(); 
            account.accountNumber = this.accountNumber;
            account.owner = this.owner;
            account.branch = this.branch;
            account.balance = this.balance;
            account.interestRate = this.interestRate;
            return account;
        }
    }
    //Fields omitted for brevity.
    private BankAccount() {
        //Constructor is now private.
    }
    //Getters and setters omitted for brevity.
}

We can create new account with the following code:


BankAccount account = new BankAccount.Builder(1234L)
            .withOwner("Marge")
            .atBranch("Springfield")
            .openingBalance(100)
            .atRate(2.5)
            .build();
BankAccount anotherAccount = new BankAccount.Builder(4567L)
            .withOwner("Homer")
            .atBranch("Springfield")
            .openingBalance(100)
            .atRate(2.5)
            .build();

This makes code clearer and more verbose. Using the Builder pattern is a good solution if you find yourself having to add more and more parameters to the constructor resulting in error-prone and hard to read code. I chose this resource because I wanted to learn more about design patterns, and I did not know much about this pattern. I learned how the Builder pattern can help simplify code that may get too complex and hard to read. The content of the post is good quality and the example used was simple and easy to understand, making learning how the Builder pattern works easier. I plan to use this information when in my professional career whenever the Builder pattern would be the best solution.

0 comments

Java: The Factory Method Pattern

2017 November 27 @ 11:12pm by erik


In this blog post, Justin Albano talks about the Factory Method Pattern and gives us an example.

The Textbook Definition

According to the Gang of Four book that defined the technique, the intent of the Factory Method pattern is as follows:

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Using the Factory Method involves creating two sets of interfaces: “(1) the product interface that constitutes the object to be created and (2) the creator interface that constitutes the object that will instantiate the product.” The UML diagram for the Factory Methods is below:

The author explains the UML diagram as the following:

Using the general pattern, we build a Creator interface, which includes one or more Factory Methods, as well as any number of other methods. This interface may also be an abstract class with defined methods or even a default implementation of the Factory Method that returns a default instance of Product. From this interface, a set of ConcreteCreator classes are created that return desired ConcreteProduct instances that implement the Product interface.

An Example in Java

  • We create an encryption mechanism that allows the user to supply a string of text and a file name, which is then encrypted and written to disk. Using the Factory Method allows us to use multiple encryption algorithms.
  • We create implementations for two encryption algorithms: (1) SHA-256 and (2) SHA-512. “For both implementations, we will use the Apache Commons encryption implementations (org.apache.commons.codec.digest.DigestUtils).”
  • In the end you should be able to do something like this:
    PersistedFile file =
       new PersistedFile("/foo/bar/text.txt", "Hello, world!", new Sha256Encryptor());

    View complete example here

    Colloquial Definition

    A method whose sole responsibility is to abstract the creation process of an object and return that object.

    I chose this resource because I am interested to learn new implementations of popular design patterns such as the Factory Method. This resource gave a detailed explanation along with other patterns that can be good alternatives to the Factory Method pattern like the Template Method pattern and Strategy Pattern. I believe the content of the article is very detailed and informative. The example they used is very interesting and I’m going to implement the code myself to test it out. I plan to use this and many other design patterns in the future. I learned more about the Factory Pattern method and when it is appropriate to use it.

    0 comments

    What Is Project Valhalla?

    2017 November 20 @ 11:24pm by erik


    In this blog post, Justin Albano explains what Project Valhalla is.

    “Project Valhalla is an OpenJDK project started in 2014 and headed by Brian Goetz with the purpose of introducing value-based optimizations to Java Development Kit (JDK) 10 or a future Java release. The project is primarily focused on allowing developers to create and utilize value types, or non-reference values that act as though they are primitives. In the words of Goetz: Codes like a class, works like an int.”

    “Project Valhalla has a very specific purpose: To cease the requirement that Java developers choose between performance and abstraction.”

    What Are Value Types?

    “Value types are groups of data whose immediate value is stored in memory, rather than a reference (or pointer) to the data.” Doing this means saving memory otherwise taken up by overhead data. “Taking data and directly placing its value into memory (rather than a reference) is called flattening and its benefits are more acutely demonstrated with arrays.” “In an array of value types, the values are directly placed into the array and are guaranteed to be in contiguous memory (which increases locality and, consequently, the chance of cache hits). This idea is illustrated in the figure below:

    The benefits to using Value Types are listed by the author:

    • Reduced memory usage: There is no need for additional memory used to store object metadata.
    • Reduced indirection: Because objects are stored as reference types in Java, each time you access it, it first must be dereferenced, causing additional instructions to be executed.
    • Increased locality Using flattened value objects removes indirection, increasing likelihood values are adjacently stored in memory.

    One of the major differences between reference types and value types:

    “The identity of a reference type is intrinsically bound to the object while the identity of a value type is bound to its current state”

    The reason I picked this resource is because I did not know about Project Valhalla and it seemed like an interesting article to learn about. It’s not quite ready to be released in JDK but it’s a useful addition to Java that increasing performance and saves memory. I feel the content of the post was interesting and informative. I learned the benefits of using Value Types versus using pointers and the improvements that have been made to Java. Value Types may soon be released in an upcoming JDK and I would like to know how to utilize them when saving memory is crucial.

    Additional resource: Minimal Value Types article

    0 comments

    API Design with Java 8

    2017 November 13 @ 10:42pm by erik


    In this blog post, Per-Åke Minborg talks about the fundamentals of good API design. His inspiration for writing this article is a blog post by Ference Mihaly which is essentially a check-list for good Java API design.

    “API combines the best of two worlds, a firm and precise commitment combined with a high degree of implementation flexibility, eventually benefiting both the API designers and the API users.”

    Do not Return Null to Indicate the Absence of a Value

    Using the Optional class that was introduced in Java 8 can alleviate Javas problem with handling nulls. An example below shows the implementation of the Optional class.

    Without Optional class

    public String getComment() {
    
        return comment; // comment is nullable
    
    }


    With Optional class

    public Optional getComment() {
    
        return Optional.ofNullable(comment);
    
    }

    Do not Use Arrays to Pass Values to and From the API

    “In the general case, consider exposing a Stream, if the API is to return a collection of elements. This clearly states that the result is read-only (as opposed to a List which has a set() method).”

    Not exposing a Stream

    public String[] comments() {
    
        return comments; // Exposes the backing array!
    
    }

    Exposing a Stream

    public Optional getComment() {
    
        return Optional.ofNullable(comment);
    
    }

    Consider Adding Static Interface Methods to Provide a Single Entry Point for Object Creation

    Adding static interface methods allows the client code to create onjects that implement the interface. “For example, if we have an interface Point with two methods int x() and int y(), then we can expose a static method Point.of(int x, int y) that produces a (hidden) implementation of the interface.”

    Not using static interface methods

    Point point = new PointImpl(1,2);

    Using static interface methods

    Point point = Point.of(1,2);

    I selected this resource because it relates to design principles, and it’s something that I do not know well. I would like to learn more about APIs and good practices for designing them using Java. The article had useful information and topics that I didn’t know well. A few more pointers from the article I learned:

    • Favor Composition With Functional Interfaces and Lambdas Over Inheritence – Avoid API inheritance, instead use static interface methods that take “one or several lambda parameters and apply those given lambdas to a default internal API implementation class.”
    • Ensure That You Add the @FunctionalInterface Annotation to Functional Interfaces – signals that API users may use lambdas to implement the interface
    • Avoid Overloading Methods With Functional Interfaces as Parameters – Can cause lambda ambiguity on the client side.

    I would like to learn more about using AWS Lambdas, and learning more about APIs in general. I plan to use this information if I am ever to work on Java APIs which is possible. I want to make sure I have the best practices and the check list mentioned in the start of the article seems like a good starting point.

    0 comments

    Java: The Strategy Pattern

    2017 October 30 @ 10:33pm by erik


    In this blog post, Justin Albano talks about the basic Strategy pattern and the “fundamental principles that make for solid strategy implementations.” He also goes into the use of Dependency Injection (DI) “to select a strategy implementation” along with a walkthrough of a basic payment system using the Strategy pattern.

    The purpose of the Strategy pattern is “to decide the algorithm used in a specific context” by encapsulate algorithms into classes with the same interface, and by using the same interface, we allow the algorithms to be interchangeable based on what is needed. The following is a UML class diagram of the Strategy pattern:

    The way the author makes sense of the Strategy pattern is to see the Context class as a desk, “where the Strategy interface represents a slot in the desk that accepts drawers” and each the concrete strategy implementations “can be thought of as actual drawers, where some are completely undivided, and others have various divider configurations; some may be good at storing papers, while others may be better at organizing pens, pencils, and paper clips. Each serves its own purpose and excels in a specific context, but vary only in their internal configuration: The external configuration of each drawer is the same so that it can be accepted by the desk.”

    I selected this article because I wanted to learn more about the Strategy patterns, and design patterns as a whole. This post had topics that I didn’t know about like Dependency Injection, using the Introduce Parameter Object refactoring technique. It also goes well into detail an implementation of a payment system showing both the Strategy pattern and Factory pattern. I feel my knowledge of the Strategy pattern has improved after reading this article, and seeing it implemented in a new way helps me understand it more. The author is very detailed and explains the topic clearly. I learned about the importance of selecting the appropriate strategy, whether it’s more appropriate to have a run-time selection (a conditional run-time selection will require logic whose complexity is proportional to the number of possible concrete strategies) or a static selection (Strategy is selected once when the application starts-up and is never reinitialized for the duration of the execution of the application. I plan on using the Strategy pattern when I am developing software, the Strategy pattern has many uses in the world of software development and will continue to be utilized.

    0 comments

    The Technical Skills You Need to Have as a Software Developer

    2017 October 16 @ 10:51pm by erik


    In this blog post, John Sonmez talks about “soft skills” and how they can help you become a better software developer. Here are some tips from the author:

    • Instead of trying to learn several programming languages at the same time it’s better to have one language that you know in and out, that you are comfortable writing.
    • Structure your code well by writing “good, clear, understandable code that doesn’t require a large amount of comments because the code itself is communicative.” – John Sonmez
    • Having a good understanding of object-oriented design and managing complexity as most popular languages rely heavily on object-oriented design and analysis.
    • Understanding how to create algorithms, and how to modify known algorithms to match your specific needs.
    • Understanding of data structures like arrays & vectors, linked-list, stacks, queues, trees, hashes and sets. These are important to know well, especially if you are being interviewed.
    • Knowing a development platform well is a good idea because some places design for specific platforms (PC, Mac, etc)
    • Learning a framework, or a complete stack. “A framework is simply a set of libraries that are used to develop code on a particular platform or on multiple platforms.” and “A stack is a set of technologies, usually including a framework, that are commonly used together to create a full application.”
    • Basic Database Knowledge, how to add, modify, delete and work with different database systems.
    • Source Control, understanding how to use tools like GIT.
    • Testing, more often projects are being created in small increments and tested as they go, this is allowing developers to catch bugs before they begin to cascade.

    I chose this resource because I’m always looking for information on becoming a better software developer and want to become an asset to wherever I dedicate my work. Some of the information is general information but I do think it’s important to work on maintaining these core skills to improve the quality of your work. I learned the importance of working on knowing at least one language very well, along with knowing one platform very well knowing how to implement popular data structures, writing good algorithms and knowing when to use what. I learned the importance of object oriented design and how prevalent it is today. I learned about frameworks and stacks and what they are, and the importance of understanding how databases work. I also learned that more recently developers are being expected to know how to test their code, especially with agile testing.

    0 comments

    Singletons: Bill Pugh Solution or Enum

    2017 October 9 @ 08:25pm by erik


    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 up to date on 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.

    0 comments

    First Post On CS-343

    2017 September 7 @ 01:54am by erik


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

    0 comments
     

    by erik christensen - powered by wordpress