Tag: Java Frameworks

  • Java Tip #9: Use CollectionUtils for evaluation and manipulation of Collections

    After quite some time this is another instance of the [Java Tips][1]. It’s an addition to the [Apache Commons][2] related [framework tips][3] which are guiding into the direction that as a developer you should take advantage of existing and proven frameworks and know their features to leverage your development efficiency. This time complexity of the given example is a bit higher than in the previous tips.


    ##Advice Use [Apache CollectionUtils][4] for evaluation and manipulation of Collections.

    ##Code-Example A short spoiler for the following code: This is a routine which checks a given set of categories against a set of category-permissions for a user. The result is a set of categories, which the user is allowed to access.

    Before

    ...
    public boolean hasPermissionsToAccessCategory(String category) {
        return (this.permissions != null && this.permissions.contains(category));
    }
    ...
    
    ...
    public Set
    getCategoriesAllowedToViewBySearchFilter() { Set result = null; if ((this.filter != null && this.filter.getCategory() != null) && (!this.filter.getCategory().isEmpty())) { result = new HashSet (); for (String category : this.filter.getCategory()) { if (this.hasPermissionsToAccessCategory(category)) { result.add(category.toString()); } } if(result.size() == 0) { result = null; } } else { result = this.getAllCategories(); } return result; } …. After … public Set getCategoriesAllowedToViewBySearchFilter() { Set result = null; if (this.filter != null && this.permissions != null && CollectionUtils.isNotEmpty(this.filter.getCategory())) { // get only categories, which are both in permissions and filter categories result = new HashSet (CollectionUtils.intersection(this.permissions, this.filter.getCategory())); // if no results, return null if(result.isEmpty()) { result = null; } } else { result = this.getAllCategories(); } return result; } … ##Benefit Huge readability gain and a safety gain. The code and intention is much clearer here and also has a smaller footprint. The maintainability has been raised because for a developer not familiar with the routine it needs a bit of brainpower to find out what the initial code really does. The removal of the additional method and usage of *CollectionUtils.intersection()* makes it much easier to understand, how the two sets are compared to each other to retrieve the correct results. ##Remarks None if you are initially writing similar logic. If you’re refactoring a method which seems to be better off with framework-provided functionality be careful and think over it a second time. Re-evaluate the code until you’re really sure because it’s easy to overlook a small detail which changes the results for a certain special case. [1]: http://kosi2801.freepgs.com/cgi-bin/mt-search.cgi?blog_id=8&tag=Java%20Tips&limit=20 [2]: http://commons.apache.org “Apache Commons” [3]: http://kosi2801.freepgs.com/cgi-bin/mt-search.cgi?blog_id=8&tag=Java%20Frameworks&limit=20 [4]: http://commons.apache.org/collections/apidocs/org/apache/commons/collections/CollectionUtils.html “CollectionUtils (Commons Collections)”
  • Java Tip #8: Use StringUtils for concatenating Strings from Arrays or Lists

    And we’re continuing with our next Java Tip. Back on using frameworks for our convenience, I present another often useful possibility to let the StringUtils handle lots of work for you.


    ##Advice Use Apache StringUtils for concatenating Strings from Arrays or Lists, also when you need to delimit them with an arbitrary string.

    ##Code-Example Before

    ...
    SQL_WHERE += " AND V.cat_display_name IN (";
    boolean addComma = false;
    for (String category : filter.getCategories()) {
      if (addComma) {
        SQL_WHERE += ", ";
      }
      SQL_WHERE += "'" + category + "'";
      addComma = true;
    }
    SQL_WHERE += ") ";
    ...
    
    ...
    String SQL = "";
    for(String category: filter.getCategories()) {
        SQL += val + ", ";
    }
    SQL = SQL.substring(0, SQL.length()-2);
    ....

    After

    ...         
    SQL_WHERE += " AND V.cat_display_name IN (";
    SQL_WHERE += "'" + StringUtils.join(filter.getCategories(), "', '") + "'";
    SQL_WHERE += ") ";
    ...

    ##Benefit Huge readability gain and a safety gain. The code and intention is much clearer and the possibility to hide bugs in the loop-logic (which I have seen often) is not present. Also, depending on the length of the Array or List, it may also present a small performance gain (see Java Tip #2) but that’s in most such cases neglibigle.

    ##Remarks None.

  • Java Tip #5: Use Apache Commons DateUtils when dealing with dates

    Tip #5 in my Java Tips series is again focussing around the Apache Commons framework. In the same manner the StringUtils simplifies many common operations on Strings (see also Java Tip #3), DateUtils ease some of the pain when working with Java Date objects.


    Advice

    Use Commons DateUtils to manipulate and calculate dates.

    Code-Example

    Before

    ...
    private static Date add(Date date, int field, int amount) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(field, amount);
        return cal.getTime();
    }
    ...
    public static Date getNextDay() {
        return add(getCurrentDay(), Calendar.DATE, 1);
    }
    ...

    After

    ...
    public static Date getNextDay() {
        return DateUtils.addDays(getCurrentDay(), 1);
    }
    ...

    Benefit

    Huge readability gain. By using DateUtils for calculating and manipulating Dates the code footprint gets smaller and easier to read. Furthermore by using explicit methods like addDays() it is clearer which part of a date is to be modified, compared to the partly ambiguous constants in the Calendar class. DateUtils also contains methods to round or truncate Dates to certain parts of the date, eg. truncate() by Calendar.HOUR sets minutes, seconds and miliseconds to zero.

    Remarks

    None.

  • Java Tip #3: Use Apache Commons StringUtils for String checks

    The next tip in my series of Java Tips deals with the usage of Java frameworks. Some people still have a certain hatred against Java frameworks because many of them have been not easy to deal with in in their past. Nevertheless, while those have either disappeared or evolved in a more usable shape, there have always been some frameworks which were rock-solid and widely accepted as simple and extremely useful. One of those is the Lang package in the library collection of the Apache Commons. In my opinion this one is a must-have for almost every Java project or application. Use it. Period.


    Advice

    Use Commons StringUtils for checking Strings content for null, emptiness or blankness.

    Code-Example

    Before

    if(str != null && !str.equals("")) { ... }
    if(str != null && !str.trim().equals("")) { ... }
    if("".equals(str)) { ... }
    if(str == null || "".equals(str.trim())) { ... }

    After

    if(StringUtils.isNotEmpty(str)) { ... }
    if(StringUtils.isNotBlank(str)) { ... }
    if(StringUtils.isEmpty(str)) { ... }
    if(StringUtils.isBlank(str)) { ... }

    Benefit

    Huge readability gain. Safety gain, as StringUtils methods are null-safe. By using the provided utility methods from StringUtils the intent of a condition is much easier and faster to recognize. Furthermore, since all methods of StringUtils are able to correctly process null Strings, there is no danger of an unexpected NullPointerException anymore because of a forgotten null-check.

    Remarks

    None.