Showing posts with label design pattern. Show all posts
Showing posts with label design pattern. Show all posts

Monday, 4 June 2018

Can I use a builder to build many objects?

I recently questioned if it is okay to use a builder to make multiple objects. The software was designed in such a way that this is possible, but I hesitated because I did not know if it was a good idea.

I know for a fact that a lot of builders in our software, might not be suitable for this use case, as they have too many dependencies (that shouldn't be there) on using the proper sequence.

That said, the following quotes are good to take to heart when designing builders1 2:

“The Builder pattern is flexible. A single builder can be used to build multiple objects. The parameters of the builder can be tweaked between object creations to vary the objects. ”
“The builder object is responsible for constructing a valid object but the object is not constructed until you call the build() method. This means the same builder can be used multiple times to construct completely different objects.”

I especially like the last quote.

References

[1] StackOverflow - How to use a single builder to build multiple objects?
https://stackoverflow.com/questions/14429043/how-to-use-a-single-builder-to-build-multiple-objects
[2] Effective Java 2
Joshua Blog

Thursday, 16 June 2016

Creating special F dependent on class A

Current situation:

New situation required:

We don't wish to touch the intervening classes, as they are called from different parts of the application for different reasons.

Solutions:
  1. provide a boolean flag all up/down the chain
  2. provide a "nicer" boolean flag, for example an enum or a Factory that determines which f should be created
  3. use a static flag in f2, in class a2 just set the flag appropriately -> completely unthreadsafe.
  4. use the ThreadLocal storage to store the boolean in a/a2 and read it in f/f2.
  5. in e -> call up the stacktrace and check for the existence of class a2.
  6. in e -> throw exception, call up the stacktrace and cehck for the existence of class a2.

However, the underlying problem is of course, that the two classes are too far apart, and there is too much tight coupling between the intervening classes and the rest of the system.

Also, the whole problem might go away with Functional Programming, but I'm not sure about that.

What do the experts say?

Thursday, 3 March 2016

Abstraction Considered Harmful

One of the more thought-provoking pieces I have read in a long time, and one I happen to fully agree with, having seen myself what too much Abstraction can lead to:

http://bravenewgeek.com/abstraction-considered-harmful/

I like the quote:
“duplication is far cheaper than the wrong abstraction”

Thursday, 1 October 2015

Calling super constructors

So, a constructor in a subclass, if it needs to call the constructor in the super class, is required to do this in the first line of the body of the constructor1.

If it does not, Java will insert a call to the default super constructor. If it does not exist, you get a compile time error.

So, what if you need to do things, before the super call takes place?

As the object is in the process of being constructed (that's why it's called a constructor), the object is in a non-valid state. This likely explains why the language designers felt that a call to another constructor should be the first part of the body of a constructor.

Well, apparently the only solution is to do everything you need inside the expressions that take the place of the super constructor arguments.

I was forced to do just that in my MudWebException.

So, there's an easy workaround, but it feels clumsy.

Take care not to access any of the methods or properties of the object that is being constructed, as it is in a non-valid state. As a matter of fact, I think it's a really bad idea to call methods in the object from within your constructor.

References

[1] JLS 8.0 Section 8.8.7. Constructor Body
https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#d5e14100
StackOverflow - Why does this and super have to be the first statement in a constructor?
http://stackoverflow.com/questions/1168345/why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor

Monday, 26 January 2015

Should I use an ORM?

Martin Fowler has a very nice article about why you should use an ORM, when you should not, and what alternatives there are.

See http://martinfowler.com/bliki/OrmHate.html.

Of course, as I have often said (but not always, never always), think before you blindly pick something to use. Is it appropriate? Is there something better?

Monday, 29 December 2014

My Enum Frustration

At work, there is a bit of Legacy around.

The following example of several Enum classes we have, is what is currently frustrating me (and I try actively to change them).

Let's enumerate (oh, look, I made a joke) the issues:
Replacing magic numbers with constants and enums is, of course, one of the Good Thingstm.

But in this example, they seem to have totally missed the point.

Not only have they replaced magic numbers with "magic enums", it's an eyesore to use the underscore in the Enum instances.

When you have to take refuge in the use of underscores to make things work, it is a sure sign that you are doing something seriously wrong.

Saturday, 19 July 2014

Successfully completed Functional Programming Principles in Scala

I earned 97.7% with distinction.

Evaluation

One can tell that the subject matter was Academic, with a firm grounding in Mathematics, which appealed to me.

The assignments provided a lot of information on what is expected, so there are no surprises, but you do need to read carefully.

The one assigment that provided the most difficulty was assignment 6, regarding the discovery of Anagrams of a sentence.

I had to wrestle a bit with the Scala syntax. It's new for me.

I especially found foldLeft and foldRight counter-intuitive sometimes.

I learned a lot on the following topics, in no specific ordering.
Scala Programming Language
by the creator, Martin Odersky, himself.
Functional Programming
one of the main subjects of the course
Domain Specific Language
Scala provides several ways to program according to a domain model2, instead of a technical/software model
Mathematics - Set Theory
the code is very close to the mathematical theory. Purposefully crafted that way, of course. It means we can actually use mathematical operators (some of the time).
Behaviour Driven Development
you can write tests that read more naturally
Test Driven Development
assignments had to pass certain tests (that are unknown), so your own tests had better be complete/sufficient
Recursion
we used a lot of recursion, you do not see that in "normal" programming languages.
It was a huge amount of fun to do, both to learn a new Programming Language1 and to learn a new Programming Paradigm.

References

[1] Coursera - Functional Programming Principles in Scala, by Martin Odersky
https://class.coursera.org/progfun-004
[2] Wikipedia - Domain Model
http://en.wikipedia.org/wiki/Domain_model

Monday, 30 June 2014

Hibernate and Caching

One of the major problems of debugging, is that sometimes there are bugs, but they only happen some of the time1.

This makes it hard to fix, unless you can spot the pattern required for the bug to appear.

The Problem

My colleague at work had such a one.

Sometimes the software threw an exception and complained that the table in the database did not actually exist. Sometimes the program provided the data required, and went merrily on its way.

It's crazy for a database table to exist only some of the time.

It made sense in this case that the table didn't exist. Because that table wasn't in the database. The Entity was purely used as a 'View' and several methods gathered the information to load an instance of the Entity.

The Explanation


Hibernate provides caching, meaning that a lookup by Identifier for an Entity returns the Entity from the Cache without hitting the database, if the Entity has been loaded already once.

Turns out our method, which loaded an Entity, totally didn't work at all! It just happened to return a Cached instance in some cases without problems.

A cached instance that was loaded by using another method that did not rely on findByIdentifier (for example via "select new Constructor()").

References

[1] The Kingdom of Transformation
http://www.csd.uwo.ca/~magi/personal/humour/Computer_Audience/The%20Kingdom%20of%20Transformation.html
[2] Hibernate - Object Identity
http://docs.jboss.org/hibernate/orm/4.3/devguide/en-US/html/ch02.html#d5e824

Thursday, 24 April 2014

Coursera - Functional Programming Principles in Scala

On the 25th of April, meaning this Friday, I start my course on Scala.

I found Coursera1, an education platform that partners with universities to provide courses online for free.

I am really excited in finding out how Scala differs from Java, and what new programming methods I'll learn.

The fact that the Course2 has been set up by the creator of the language, Martin Odersky of École Polytechnique Fédérale de Lausanne, is a big plus.

I hope I can meet the deadlines.

References

[1] Coursera
https://www.coursera.org/
[2] Coursera - Functional Programming Principles in Scala
https://www.coursera.org/course/progfun

Tuesday, 7 January 2014

Model-View-Controller

I have always had a problem understanding the Model-View-Controller pattern. Perhaps because I always thought the Controller should be in between the Model and the View. In reality, there are flows between all the different components.

Date and Time


One of the things that in my mind would be a perfect example is Date and Time. The reason that I think it is an excellent example, is the way the Model part is exceedingly simple, and the View part is exceedingly complex. The Model part is nothing more or less than a Long indicating the number of milliseconds since Jan 1, 1970 GMT. The View part is split up into years, months, days, hours, minutes, seconds, milliseconds, timezone, daylight savings time, leap years, and God knows what else. While the Model part is simple and convenient for a computer, the View part is complex, but required if you want your date/time to be meaningful to your users.


References


Wikipedia: Model-View-Controller
http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

Sunday, 27 October 2013

Trainwreck vs. Method Chaining

I thought it worth while to expound on the differences between a train wreck and method chaining.

Whereas a trainwreck is a bad idea, method chaining is an excellent idea. This blog will try to explain why these two are polar opposites on the good/bad scale, even though the syntax differs very little.

Trainwreck


A trainwreck is a bad idea. It provides an Object A with in depth knowledge of several other objects. Knowledge that should be contained in the individual objects instead of Object A.

In code it would look like follows:

public class A
{
    public void someMethod(B b)
    {
        b.getC().getD().getE().doThing();
    }
}

A Trainwreck breaks the Law of Demeter[1] (and everyone knows, if you break a law, you have to go to jail).

A solution would be to just tell B to do it, and let it figure it out.
public class A
{
    public void someMethod(B b)
    {
        b.doThing();
    }
}

Method Chaining


Method chaining is an excellent idea. The methods used always return the Object itself. It's a good way of constructing an Object without having to resort to multiple different Constructor methods with varying (large amount of) parameters.
public class Person
{

    private long id;
    private String firstName;
    private String lastName;
    private String address;
    private String telephone;
    private String title;

    public Person(long id)
    {
        this.id = id;
    }

    public Person setFirstName(String firstName)
    {
        this.firstName = firstName;
        return this;
    }

    ...
}

public static void main(String[] args)
{
    Person mrBear = (new Person(1l)).setFirstName("B.").
              setLastName("Bear").setTitle("Mr.");
}

Method Chaining does not break the Law of Demeter[1]. It doesn't even talk to friends (in this case), but only to itself.

Here I have used a simplified example. Mostly you'd create a PersonBuilder to make Persons.[4]

For some great uses of method chaining check out [2] and [3].

References

[1] Glossary
http://randomthoughtsonjavaprogramming.blogspot.nl/p/glossary.html
[2] FluentInterface
http://martinfowler.com/bliki/FluentInterface.html
[3] Expression Builders
http://martinfowler.com/bliki/ExpressionBuilder.html
[4] Too Many Parameters in Java Methods, Part 3: Builder Pattern
http://marxsoftware.blogspot.nl/2013/10/too-many-parameters-in-java-3-builder-pattern.html

Wednesday, 2 October 2013

Red Soup

Recently had a real life experience that I could map to Software Design.

Occasionally, I or one of my colleagues gets beverages for everyone. The scheduling is: the one who wants to have a beverage gets some for the rest as well and queries their preference beforehand.

In this case, the job landed on one of my colleagues.

The conversation went something like:
Guy1: What would you like?
Me: I'd like some Red Soup.
Guy1: What kind of Red Soup?
Me: Red Soup! You're the Factory, figure it out.
Me: Convention Over Configuration!
Guy2: Should he draw you an UML diagram? As long as it implements or extends RedSoup.
Guy1: With Cream?
Me: That's an implementation detail. Not interested! Red Soup! Go!

It left me in stitches, I'm geeky like that.

(added an overview of the different arrows in UML. I always get confused.)

Sunday, 9 October 2011

Different Ways to use JPQL

Introduction

There are several ways in which to execute JPQL (Java Persistence Query Language). I'll introduce the "old way" first, with JDBC and direct connections to the database, before branching off into the ways used by ORMs (Object Relational Mapping).

Each way has its advantages and disadvantages.

The old way:
  • direct database access
  • database connection pool
Using an ORM
  • hql in java code
  • named queries in annotations
  • named queries in xml
  • Criterion API
  • retrieving the object by its primary key

The Old Way

Direct Database Access

This is an example of direct database connection with jdbc. Setting it up, sending the query, reading the result, close the resultset and shutting down the connection.


/**
 * Connects to the database using an url. The url looks something like
 * "jdbc:mysql://localhost.localdomain/mud?user=root&password=". Uses the
 * classname in Constants.dbjdbcclass to get the right class for interfacing
 * with the database server. If the database used is changed (or to be more
 * specific the jdbc driver is changed) change the constant.
 * 
 * @throws InstantiationException
 *             happens when it is impossible to instantiate the proper
 *             database class, from the class name as provided by
 *             Constants.dbjdbcclass.
 * @throws ClassNotFoundException
 *             happens when it is impossible to find the proper database
 *             class, from the class name as provided by
 *             Constants.dbjdbcclass.
 * @throws IllegalAccessException
 *             happens when it is not possible to create the database class
 *             because access restrictions apply.
 * @throws SQLException
 *             happens when a connection to the database Server could not be
 *             established.
 */

public Macro runQuery() throws SQLException, InstantiationException,
    ClassNotFoundException, IllegalAccessException
{
  Macro result = null;
  try
  {
    Class.forName(Constants.dbjdbcclass).newInstance();

    // jdbc:mysql://[host][,failoverhost...][:port]/[database]
    // [?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
    String theUrl = Constants.dburl + "://" + Constants.dbhost
      + Constants.dbdomain + "/" + Constants.dbname + "?user="
      + Constants.dbuser + "&password=" + Constants.dbpasswd;
    theConnection = DriverManager.getConnection(theUrl);

    PreparedStatement statGetMacro = null;
    statGetMacro = theConnection.prepareStatement(sqlGetMacro);
    statGetMacro.setString(2, macroname);
    res = statGetMacro.executeQuery();
    if (res != null && res.next())
    {
      result = new Macro(res.getString("macroname"), res.getString("contents"));
      res.close();
    }
    statGetMacro.close();
  } catch (Exception e)
  {
    throw new MudDatabaseException(Constants.DATABASECONNECTIONERROR, e2);
  }
  finally
  {
    if (theConnection != null) {theConnection.close();}
  }
  return result;
}
Advantages:
  • complete control
  • very little libraries required
Disadvantages:
  • sql syntax spread throughout the java code
  • lots of error-prone boiler plate code required
  • expensive in setting up new database connections for every query
  • sytax of query not checked, until method called
  • changing the query requires source code change, recompilation, repackaging, etc

Database Connection Pool

This is example of database connection with jndi resource pool, where the only thing required is the jndi name. In this case it is irrelevant which connection we receive from the connection pool. The actual theConnection.close() does nothing, but returns the connection back to the pool.


public void runQuery() throws Exception
{
  Connection con=null;
  ResultSet rst=null;
  PreparedStatement stmt=null;

  try
  {
    Context ctx = new InitialContext();
    DataSource ds = (DataSource) ctx.lookup("jdbc/mmud");
    con = ds.getConnection();

    stmt=con.prepareStatement("select * from links where type = 1 order by creation");
    rst=stmt.executeQuery();
    while(rst.next())
    {
        out.println("<li><A HREF=\"" + rst.getString("url") + "\">" +
          rst.getString("linkname") + "</A> (<i>" +
          rst.getString("name") + "</i>)<P>");
    }
    rst.close();
    stmt.close();
  }        
  finally
  {
    if (rst != null) {try {rst.close();} catch (Exception e){}}
    if (stmt != null) {try {stmt.close();} catch (Exception e)}}
    if (con != null) {try {con.close();} catch (Exception e){}}
  }
}

Advantages:
  • database connection resource pool
  • no need to open and close connection, connections are reused
Disadvantages:
  • sql syntax spread throughout the java code
  • still a lot of error-prone boiler plate code required
  • sytax of query not checked, until method called
  • if connections/resources not properly released, the pool will run out of connections/resources
  • changing the query requires source code change, recompilation, repackaging, etc

Using an ORM

hql in java code

@Override
public void deleteAddress() 
{
  StringBuilder queryBuilder = new StringBuilder();
  queryBuilder.append("DELETE Address address ");
  queryBuilder.append("WHERE  address.country = 'Italy' ");
  queryBuilder.append("AND NOT EXISTS (SELECT '' ");
  queryBuilder.append("            FROM Customer cust ");
  queryBuilder.append("            WHERE cust.address = address ");
  queryBuilder.append("           ) ");

  Query query = em.createQuery(queryBuilder.toString());
  query.executeUpdate();
}

Unfortunately, the code above is what I encounter frequently in the source of my employers current software product.

Advantages:
  • none
Disadvantages:
  • a StringBuffer is created every time the method is called, at the very least this should be a constant
  • jpql is created and parsed and compiled every time the method is called
  • sql/hql/jpql syntax spread throughout the java code
  • sytax of query not checked, until method called
  • changing the query requires source code change, recompilation, repackaging, etc


Named queries in annotations

Queries can be defined in the annotations on top of Entity classes. The annotation would look a little like the one below.

@NamedQueries({
    @NamedQuery(name = "Character.findAll", query = "SELECT c FROM Character c"),
    @NamedQuery(name = "Character.findByName", query = "SELECT c FROM Character c WHERE c.name = :name")})

One of the problems often heard is that the annotation has to be on an Entity class, when you perhaps would prefer to have it someplace else. In that case, it might be an idea to define the constants as strings in a different part, like a Service or a DAO or what have you, and refer to them in the NamedQuery annotations. Like in the two-part example below.

As the name of a named query is global within the persistent provider, it is essential to create unique names within the application. That is why in most cases, the name of a named query is prefixed with the class name.

/**
 * Game bean.
 * @author Mr. Bear
 */

@Stateless
@Remote(GameBeanRemote.class)
public class GameBean implements GameBeanRemote
{
    public static final String character = "Character";

    /**
     * label for the find all characters query.
     */

    public static final String FINDALLCHARS_QUERYNAME = character + ".findAll";

    /**
     * query for the find of all characters query.
     */

    public static final String FINDALLCHARS_QUERY = "SELECT c FROM Character c";

    /**
     * label for the find character based on name query.
     */

    public static final String FINDCHAR_QUERYNAME = character + ".findByName";

    /**
     * query for the find of character based on name query.
     */

    public static final String FINDCHAR_QUERY = "SELECT c FROM Character c WHERE c.name = :name";

    @PersistenceContext(unitName = "datasource")
    private EntityManager em;
/**
 * The Character entity.
 * @author Mr. Bear
 */

@Entity
@Table(name = "mm_usertable")
@NamedQueries({
   @NamedQuery(name = GameBean.FINDALLCHARS_QUERYNAME, query = GameBean.FINDALLCHARS_QUERY),
   @NamedQuery(name = GameBean.FINDCHAR_QUERYNAME, query = GameBean.FINDCHAR_QUERY)})
public class Character implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 20)
    @Column(name = "name")
    private String name;

Using the named queries in code is as simple as getting the entity manager and telling him the name of the NamedQuery you wish to use, add the parameter values, and request the result. You can refer to the NamedQueries by name, hence the name, get it?

@Override
public CommandOutput retrieveCharacter(String name)
{
    itsLog.entering(this.getClass().getName(), "retrieveCharacter");
    Query q = em.createNamedQuery("Character.findByName", Character.class);
    q.setParameter("name", name);
    Character c = (Character) q.getSingleResult();
    if (c == null)
    {
        itsLog.exiting(this.getClass().getName(), "retrieveCharacter");
        return new CommandOutput("""""");
    }
    CommandOutput co = new CommandOutput(c.getName(), c.getArm(), c.getBeard());
    itsLog.exiting(this.getClass().getName(), "retrieveCharacter ", co);
    return co;
}

The great part of NamedQueries is that they are checked and pre-compiled by Hibernate when the server starts, so you get instant messages if you screwed up the syntax.

Advantages:
  • the Persistence provider might be able to precompile them, and this can help catch bugs before deployment
  • sql syntax no longer spread throughout the java code
  • sql queries externalised to the java code
  • there's a central place for queries, making them easy to find and easy to re-use.
Disadvantages:
  • named queries in annotations can only be added to the Entity classes or the SuperMapClass. This is especially awkward when you have a query spanning multiple entities.
  • named queries are referenced using a key, which is global to the application.
  • named queries are a little difficult to debug, as a change requires an application server reboot.
  • changing the query in the annotation requires source code change, recompilation, repackaging, etc

In the examples below, JBoss is used in combination with Hibernate. The first example is the jboss log when things go wrong, and the second example is when things go right.

09:19:23,635 ERROR [SessionFactoryImpl] Error in named query: FullAddress.findAddressesOfCustomers
org.hibernate.QueryException: could not resolve property: entitynr of: mrbear.entity.Address [DELETE Address address WHERE address.country = 'Italy' AND address.entitynr > 1000 AND NOT EXISTS (SELECT '' FROM Customer cust WHERE cust.address = address) ]
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:67)
09:23:10,946 INFO [AnnotationBinder] Binding entity from annotated class: mrbear.entity.Address
09:23:10,948 INFO [QueryBinder] Binding Named query: FullAddress.findAddressesOfCustomers => DELETE Address address WHERE address.country = 'Italy' AND address.entityNr > 1000 AND NOT EXISTS (SELECT '' FROM Customer cust WHERE cust.address = address)

Let me point you especially to the fact that HQL (or JPQL for that matter), contrary to SQL, is case-sensitive (for the most part). It would have to be, as it has a direct link to java classes and these are also case-sensitive.

In the example above, the getter and setter for entity number was specified as getEntityNr and setEntityNr, hence the problem with the casing in the first example.

According to Gavin King [1]:
We leave it up to you if you want to utilize the named query feature. However, we consider query strings in the application code (except if they're in annotations) to be the second choice; you should always externalize query strings if possible.

Named queries in xml

If you do not like to have your JPQL in your code at all, there is always the possibility of putting the queries into the xml files that are a part of the configuration of the jar file.

There is no reason why you cannot have both, both named queries in your annotations and queries in your xml persistence configuration files.

One of the great things is that the named queries in the persistence xml files take precedence over the named queries in the annotations. This means, that, when deployed in a specific production environment, it is possible to change the named queries, without having to touch/recompile/build/package the java source code. So, you can do convention over configuration.

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="mmud" transaction-type="JTA">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <jta-data-source>mmud</jta-data-source>
    <!-- Named JPQL queries per entity, but any other organization is possible  -->
    <mapping-file>META-INF/jpql/Character.xml</mapping-file>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties/>
  </persistence-unit>
</persistence>
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings version="1.0" xmlns="http://java.sun.com/xml/ns/persistence/orm"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm http://java.sun.com/xml/ns/persistence/orm_1_0.xsd "
>

    <named-query name="Character.findByName">
        <query>
            SELECT
                c
            FROM
                Character c
            WHERE
                c.password = :name
            OR
                c.name = 'Midevia'
        </query>
    </named-query>
</entity-mappings>

So in the code example that uses annotations, when using these two persistence xml files displayed above, suddenly "Midevia" is retrieved from the database, instead of the name you requested.

Advantages:
  • the Persistence provider might be able to precompile them, and this can help catch bugs before deployment
  • sql syntax no longer anywhere in the java code
  • there's a central place for queries, making them easy to find and easy to re-use.
  • named queries can be spread through many different xml files, making them more easy to categorise.
Disadvantages:
  • named queries are referenced using a key, which is global to the application.
  • named queries in xml, can be changed, if you don't mind hacking your way through xml.
  • named queries are a little difficult to debug, as a change requires an application server reboot.

Criterion API

@Override
public CommandOutput retrieveCharacter(String name)
{
    itsLog.entering(this.getClass().getName(), "retrieveCharacter");

    // setup criteria builders/queries
    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery criteriaQuery = criteriaBuilder.createQuery();

    // add from
    Root<Character> from = criteriaQuery.from(Character.class);
    CriteriaQuery<Character> select = criteriaQuery.select(from);

    // add predicate
    Predicate predicate = criteriaBuilder.equal(from.get("name"), name);
    criteriaQuery.where(predicate);

    // create the select query
    TypedQuery<Character> typedQuery = em.createQuery(select);

    // get the results
    List<Character> resultList = typedQuery.getResultList();

    if (resultList == null || resultList.size() != 1)
    {
       itsLog.exiting(this.getClass().getName(), "retrieveCharacter");
       return new CommandOutput("""""");
    }
    CommandOutput co = new CommandOutput(
            resultList.get(0).getName(),
            resultList.get(0).getArm(),
            resultList.get(0).getBeard());
    itsLog.exiting(this.getClass().getName(), "retrieveCharacter ", co);
    return co;
}
Advantages:
  • the Persistence provider might be able to precompile them, and this can help catch bugs before deployment
  • sql syntax no longer anywhere in the java code
  • the query is dynamic, making it easy to change depending on input from the user
  • it is java, so every tool and compiler can aid in the development, like syntax checking and type checking and the like
Disadvantages:
  • fairly unreadable

Retrieving the object by its primary key

Ideally, we do not wish to use SQL or HQL or the Criteria API at all. If possible, we just want to tell the Entity Manager to get the objects we need. In most cases, this is not easy. But for some concepts, like getting an object based on its primary key (so we are always sure there's just one (or zero) available) there's a much more straightforward way.

@Override
public CommandOutput retrieveCharacter(String name)
{
    itsLog.entering(this.getClass().getName(), "retrieveCharacter");
    Character c = em.find(Character.class, name);
    if (c == null)
    {
        itsLog.exiting(this.getClass().getName(), "retrieveCharacter");
        return new CommandOutput("""""");
    }
    CommandOutput co = new CommandOutput(c.getName(), c.getArm(), c.getBeard());
    itsLog.exiting(this.getClass().getName(), "retrieveCharacter ", co);
    return co;
}
Advantages:
  • no SQL/HQL/JPSQL of any kind required
  • the JPA implementation can cache the object and retrieve is quickly.
Disadvantages:
  • only for specific uses, like retrieving objects by primary key.

Conclusion

I hope to have demonstrated the different uses that exist in retrieving data from a database using any kind of ORM, compatible with the JPA. As you are no doubt aware from this piece, I strongly consider the last four examples to be good practices of creating JPQL queries in your application.

As always, each has its strong and weak points, and therefore are applicable to different situations. Evaluate the situation and pick the one that is best suited for the job.

References


[1] Java Persistence with Hibernate
Christian Bauer, Gavin King
[2] chapter 2.3 - Hibernate Community Documentation
http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/
[3] Organize Your Named JPQL Queries
http://eubauer.de/kingsware/2011/03/25/organize-your-named-jpql-queries/
[4] Hibernate: Criteria vs. HQL
http://stackoverflow.com/questions/197474/hibernate-criteria-vs-hql
[5] Are Hibernate named HQL queries (in annotations) optimised?
http://stackoverflow.com/questions/2641997/are-hibernate-named-hql-queries-in-annotations-optimised
[6] GlassFish Project - Java Persistence Example
http://glassfish.java.net/javaee5/persistence/persistence-example.html
[7] Use string constants in annotations
http://javahowto.blogspot.com/2009/04/use-string-constants-in-annotations.html
[8] Java Persistence 2.0 Public Draft: Criteria API
http://blogs.oracle.com/ldemichiel/entry/java_persistence_2_0_public1
[9] Dynamic, typesafe queries in JPA 2.0
http://www.ibm.com/developerworks/java/library/j-typesafejpa/
[10] Where to put named queries in JPA?
http://jdevelopment.nl/put-named-queries-jpa/
[11] Java Glossary
http://randomthoughtsonjavaprogramming.blogspot.com/p/glossary.html

Wednesday, 14 September 2011

Addendum on Post "Decrease Indentation"

This is a small addendum to my post on Decrease Identation

I noticed that the same thing can be done in for-loops and the like, by means of continue. I just don't know if it's in common use at the moment.

Bad example:
/**
 * Process the proper states.
 */

public void processStates()
{
    List<State> stateList = new ArrayList<State>();
   
    for (State state : stateList) 
    {
        if (!state.equals(State.INVALID))
        {
            Capital capital = State.getCapital();
            if (capital != null && capital.size() > 1000000)
            {
                stateList.add(state);
            }
        }
    }
    stateService.processStates(stateList);
    refresh();
}

Good example (bad example refactored):
/**
 * Process the proper states.
 */

public void processStates()
{
    List<State> stateList = new ArrayList<State>();
   
    for (State state : stateList) 
    {
        if (state.equals(State.INVALID))
        {
            // invalid state!!!
            continue;
        }
        Capital capital = State.getCapital();
        if (capital == null || capital.size() <= 1000000)
        {
            // capital doesn't exists or not impressive enough!
            continue;
        }
        stateList.add(state);
    }
    stateService.processStates(stateList);
    refresh();
}

Wednesday, 6 July 2011

Decrease Indentation

And when I talk about indentation, I mean nested if statements, another one of my pet peeves.

This specific refactoring is called: Replace Nested Conditional with Guard Clauses[1].

Preconditions (GuardClauses) are a great example of where it is okay to return early at the start of the function.

It is very convenient to prevent the ArrowAntiPattern.

Here a bad example:

public boolean getPayment(String a, Double b)
{
    boolean result = false;
    if (a != null && b != null && !a.equals("") && b >= 0.0)
    {
        User user = getUser(a);
        if (user != null && user.getAccountValue() >= b))
        {
            user.setAccountValue(user.getAccountValue() - b);
            return true;
        }
        else
        {
            log.debug("User account not found or insufficient funds.");
            result = false;
        }
    }
    else
    {
        log.debug("Bad values.");
        result = false;
    }
    return result;
}

Here a good example (bad example refactored):

public boolean getPayment(String a, Double b)
{
    // preconditions
    if (a == null || b == null)
    {
        log.debug("Null values");
        return false;
    }
    if ("".equals(a) || b <= 0.0)
    {
        log.debug("Bad values");
        return false;
    }
    User user = getUser(a);
    if (user == null)
    {
        log.debug("User account not found.");
        return false;
    }
    if (user.getAccountValue() < b)
    {
        log.debug("Insufficient funds.");
        return false;
    }
    user.setAccountValue(user.getAccountValue() - b);
    return true;
}

One important skill here is the proper negation of an expression. You'd be surprised how many people lack this skill.

References


[1] Refactoring - Improving the design of existing code
Martin Fowler