Java – “Clean Code”: How to organize named queries

Architectureclean codeentityjava

Few days ago I started to read Robert C. Martin "Clean Code" book and it encouraged me to look more detailed at my code. After I opened eclipse I saw this:

entityManager.createNamedQuery("CarriageRouteEntity.listCarriageDirections");

and I decided to move string CarriageRouteEntity.listCarriageDirections to constant string. After quick fix I created something like this:

@NamedQueries({
        @NamedQuery(name = CarriageRouteEntity.LIST_CARRIAGE_DIRECTIONS, query = "just query ...") })
public class CarriageRouteEntity {
    public static final String LIST_CARRIAGE_DIRECTIONS = "CarriageRouteEntity.listDirections";
    // ...
}

so now I call it like this:

entityManager.createNamedQuery(CarriageRouteEntity.LIST_CARRIAGE_DIRECTIONS);

And here I started to wondering where should I put named queries constants. Is entity class good place for this? Maybe I should create new class with these constants like

public class CarriageRouteEntityNamedQuery {
        public static final String LIST_CARRIAGE_DIRECTIONS = "CarriageRouteEntity.listDirections";
}

but if another programmer will try to create named query will he knew where to look at it? What are your opinions? How to organize these constants? Maybe instead of creating CarriageRouteEntityNamedQuery class I should create enum and add method to entity CarriageRouteEntity called getNamedQuery() which will tell another programmer in which enum he/she should look for constants?

Best Answer

I've done both of the approaches you've mentioned and both are equally as useful. Depending on how your architecture is set up, there are some conditions you might want to consider:

1.) If you have less than 7 or 8 named queries, I would consider putting them as constants in the same class as your data access methods if and only if the named queries are used in that class.

2.) If you have more than 8 named queries or you have multiple named queries spread across multiple entity classes that you'd like to store in a single location, I would definitely put those in a separate class as constants.

Be sure to place your named query classes as close to your entity classes as possible.

Related Topic