Blog

  • 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.

  • New Skype Utility Page: Skype Contacts Overview

    In a boring moment recently I sat down and created another utility page for Skype on Windows which was wandering around my mind for some time already:

    Skype Contacts Overview

    I created this page because from time to time I wanted to have a quick overview of the Skype-IDs of my contacts (especially for fooling around with the Skype API ๐Ÿ˜‰ ). From within Skype I always had to open the contact details page for each contact and this became just too cumbersome over the time. And I can now also read the full mood-messages from all contacts even if they are too long to be displayed un-shortened in the Skype contact list.

    Another intention was to make information conveniently available which is maybe not even accessible from within the Skype client, such as the time when a contact has been seen online the last time which could help someone when there is the need to clean up old contact entries in the list.

    Again, the same restrictions as for my Skype Rich Mood Editor apply:

    • Page viewed in Internet Explorer
    • Skype Client with Extension Manager installed
    • Let IE access ActiveX on this page

    Feedback on this page is always welcome ๐Ÿ™‚

  • Java Tip #7: Minimize Map processing

    On to the next [Java Tip][1]. Again, this time I’m staying within the boundaries of the Sun JDK.


    ##Advice When traversing a Map, always use the minimum necessary methods to get keys/values out.
    *

    .entrySet()* vs. *.keySet()* vs. *.values()* ##Code-Example Before … for (String number : phoneBook.keySet()) { PhoneBookEntry name = phoneBook.get(number); if (name != null) { … … for (String parameterKey : paramMap.keySet()) { Object value = paramMap.get(parameterKey); … After … // if only values are needed for(PhoneBookEntry name : phoneBook.values()) { if (name != null) { … … // if key&value are needed for(Entry entry : paramMap.entrySet()) { String parameterKey = entry.getKey(); Object value = entry.getValue(); … ##Benefit Performance gain. Map is only searched once instead twice (and also the hashing for get() is avoided), or there is only the really required data extracted and returned from the map. Furthermore having only the required data around avoids later confusion on the original intent (“… is the key maybe used somewhere or just a leftover?…”). ##Remarks None. [1]: http://kosi2801.freepgs.com/cgi-bin/mt-search.cgi?blog_id=8&tag=Java%20Tips&limit=20
  • Stargate Universe Season 1 completed – Review ahead

    More than three years ago I had to give the sad news that SG-1 came to an end. But in the same posting I also mentioned that a new series was announced and that I hoped the best for it.

    Today the first season of Stargate Universe will come to an end. At least for those people in German-speaking countries, because the fans in the US will still have to wait until Friday night. This is a remarkable event, at least for me, because usually a seasons finale airs first in the same area where the season premiere came across.

    Not so this time, RTL2 spoils the season finale of SG-U two days ahead of SyFy.

    I’ll update this posting as soon as I’ve watched the finale S01E20 "Incursion (2)" or "Feindlicher รœbergriff (2)" to conclude my impression of Stargate Universes first season.

    Update/Review 2010-06-10

    Well, now that I’ve watched finale of SG:U season 1 I think, that SG-U is a worthy continuation of the Stargate franchise. If I had to compare it to something else, I think it’s the "Star Trek: Deep Space 9" of Stargate with a remote location, life progressing not strictly within the boundaries of law and common culture and always on the verge of death. Furthermore the different mindsets of military and civilian people add a level of friction and tension which allows a wide range of difficult situations and plots.

    What I also like is that many (leading) characters, especially Young, Rush and Telford, which are no clear black or white characters where you can say without even thinking that they’re on the good or bad side. Most of the other characters can easily be located on either the good or the bad side.

    Some criticism has to be told nevertheless, I think that a tad too much time was spent on character development so that the beginning of season 1 was (at least for me) somehow slow. But these were always freshed up with episodes with in my opinion exceptional plot ideas and also science/action components. I’m specifically thinking of "Light" and "Time" here. The aliens filled a debt which is necessary for a SG series but I don’t consider it to be an outstanding viewing experience so far. There was just too less friction with those and although Rush and Cloe had very close encounters I somehow think that there were just too short contacts and plot strings could have been followed a bit more.

    For the communication stones my opinion is that the implications they cause have been addressed too lightly and the usage of them has just become too common. I’m not sure if I’m comfort with the decision to let the characters keep their actors when having a mind-switch but it also takes out a lot of complexity for the viewers and I think its the better of two worse possibilities.

    In the second half of the season, action and science clearly got a better grip and the balancing between character and action was evened out better, also within episodes. And finally, the seasons two-parted (or even three-parted) finale is in my opinion one of the best I’ve watched so far in SciFi series. The leadup to the decisions and events was clear but still thrilling and the hefty turnarounds in "Incursion (2)" as well as the most upsetting cliffhanger ever(!) make this finale (and very probably also the following resolution in episode 1 of season 2) a must-have-seen event for almost any SG-fan.

    All in all I think, the change of the franchise in a darker and confined direction was a good one as it drives the mystery of the Stargates closer together with the personal and emotional conflicts of humans in extreme situations and gives back a lot of the military strictness and command structures which were softened up somehow over the last few seasons of SG-1.

    Sadly, as Joseph Mallozzi has already announced, the Kino Webisodes won’t continue in season 2, I always thought of them as a nice complement to better understand life in a group when you’re completely isolated in a hostile environment.

    So, I can say, SG has tightened the connection to me as a fan and although with this harsh cliffhanger, which possibly could ruin the experience for some people because of the long break, I will eagerly wait for it’s continuation this fall.

  • “Mood Music” or What I took from the Eurovision Song Contest 2010

    Surely you all know this situation. You hear a song or some tunes and within moments your mood just changes from whatever to what the song is about. For me this does not happen very often, maybe just a handfull of times a year or so. And most of the time it’s not even a new song but one which you already heard in the past and which you are somehow mentally connected to. Maybe it not only reliably triggers a certain mood but also some memories, good or bad ones.

    My personal repertoire of such "mood music" is not that big but maybe the connected emotions, moods and memories are more intense because of that. And I think it’s perfectly ok that way.

    For example one of those songs is High from the Lighthouse Family which instantly brings up memories of the first girl I’ve fallen in love quite seriously. Well, as many teenage affections this one was not returned and faded over time. But still, it was the first one. I don’t know exactly why it’s that song but I think I can remember it being played in the background when I had a close moment with that girl. Or another unrelated example, Das Boot from U96, the one song/melody which got me into listening to 90s-Techno and other electronic music.

    I think the last week has proven that I probably can add another song to my pack. It’s Madcon’s interpretation of their own song Glow for the Eurovision Song Contest 2010. Altough I missed most of the show, I accidentially tuned in for this break-filler. And boy, I didn’t regret. It took me totally unprepared and after the almost eight minutes of happiness overdose my not-so-great mood from the last few weeks has vanished and I’ve too been infected with an almost euphoric and happy state of mind. And it’s still that way today, even although I’ve listened to this song now a hundred times and I guess it will keep that way for some time.

    What’s strange though is that the full effect only hits if watching the video, especially in HD. Maybe it’s because it’s cutting and choreography is done so that you really see only happy and excited faces for eight minutes and there are so much details in the pictures that you can watch it often and still discover something new and funny. Perhaps its long enough and re-watchable enough so that the presented positive mood just seeps deep enough into your subconsciousness.

    But in the end it’s completely irrelevant how it works, just that it does! What about you, do you have any similar songs on your mind which are able to turn you completely around?

  • Beware of the ad-bundled freeware

    In the last few years I’ve recognized that many popular freeware applications have included ad-bundles into their installers. For those who don’t know what I’m talking about, these are freeware applications which can be downloaded and used without any restrictions but during the installation process there is a step where an "app-bar" or "browser-addon" for a better user experience is offered for installing and enabled by default. Although, this bar does nothing more than just add a search-bar to your browser or/and redirect the default homepage to an ad-supported page which, most of the time, just redirects its searches just to Google or Bing.

    But almost always it is possible to avoid the installation of these ad-addons. Either during some (sometimes not very logical) de-selecting during the installation process or by downloading a different and, most of the time, almost hidden "light"-version from the homepage.

    Some candidates from the former category, where you have to disagree or not accept licenses for the ad-supplement during the installation, are for example:

    • Foxit PDF Reader (Ask.com toolbar)
    • Winamp (Winamp Search(r) )

    And applications which secretly provide an ad-free version are:

    • SuMo (using the red-stroked R/K-icon on the download-page)
    • CCleaner (using the "slim" version from the builds page)

    I completely understand the freeware applications need for some funding, but what I just cannot stand are those sneaky attempts to get the ad-ware placed on the customers computers. I have been called for support to computers, where the Internet Explorer took almost a minute to start up and when finished had almost one third of its screen filled with various search-bars and rating-tools which suggest "interesting" websites.

    Instead of having to take care during every installation, I’d rather have a way to encourage users for support like Avira does (small ad-popup, once per virus-definition update). Another clever way is how the DonationCoder.com site uses for its tools (which I already talked about more than four years ago) where you’re presented with a small popup once per application start and where you can get a time-limited no-ad license (ie. for six months) for free from the website.

    Please dear freeware-developers, consider such alternatives more in the future!

  • Language affinity and my 5cents on the best programming language

    Every now and then the well known and never-ending discussion of the "best" programming language comes up. Often this drifts into the direction where people compare specific language capabilities and features and how specific problems can be solved so much easier than in the other language(s).

    When I’m caught in such a discussion people often assume that I’m a Java evangelist. But I always try to make clear, that I try to focus on solutions and problems rather than Java features. It’s just that when I need to make examples, I use Java because it is currently the language which I know best. This doesn’t mean that Java is the best language for the job.

    I always try to make clear that I think that different languages always have a specific goal or type of problem which they can handle better than other programming languages. Take for example C/C++ for creating fast and efficient binaries, Perl for excellent handling of large quantities of strings, Shell scripts for quick automation of system management activities, PHP for fast creating dynamic web content, and so on… Of course I know that every of these exercises can be solved with almost every other language as well but the difference is, how fast and understandable the result can be produced. Creating a webserver with shellscripts is possible but I certainly wouldn’t try it.

    So, once and for all: I think almost any language has its area of excellence and there is no such distinction like a better or worse language. ie. Java is not better than C# nor the other way round.

    Of course, if there hast to be a decision made on choosing a language this decision cannot be solely based on which language would be the best for the present problems. One has also to take into account, which languages are known by the developers and how well they know them. Furthermore one has also to be aware that available frameworks for languages often can change the capabilities of languages and how this language can be applied to certain types of problems.

  • Java Tip #6: Use the for-each of Java5 whenever possible

    The Java Tips series gets another entry, yay! I’ll keep within the plain Java language this time, no frameworks or other fancy tricks, just basic Java know-how.


    Advice

    Use Java5’s for-each loop instead of manually iterating over arrays or collections whenever it is possible.

    Code-Example

    Before

    ...
    // access using index
    for (int i = 0; i < offerList.getMembers().size(); i++) {
        CustomizedOfferOverviewDTO dto = (CustomizedOfferOverviewDTO)offerList.getMembers().get(i);
    ...
    }
    ...
    // access using iterator
    Iterator iter = m_elements.iterator();
    while (iter.hasNext()) {
        ILoadable loadable = (ILoadable)iter.next();
    ...
    }
    ...

    After

    ...
    for(CustomizedOfferOverviewDTO dto : offerList.getMembers()) {
    ...
    }
    ...
    for(ILoadable loadable : m_elements) {
    ...
    }
    ...

    Benefit

    Readability gain. The for-each makes it a lot easier to iterate over collections and arrays and to read and recognize the code. Furthermore the Java compiler might also be able to optimize the loop a bit better internally but in general this improvement is beyond measuring accuracy and therefore is not an argument in this case.

    Remarks

    This only works as long as it’s not modifying the collection or array beneath it. If deleting or replacing elements, you have to use the previous-style looping again where you have direct access to the Iterator.

  • Final piece of bathroom ordered

    It took quite a long time since the last major progress but now there has been another milestone reached. Yesterday I finally decided, after lots of thinking and measuring, which washing basin combination I’ll take to finish off the last missing piece for a 100% functional bathroom.

    A sample picture of the combo and how I ordered it (I hope this link lasts):

    Pelipal Roulette 09

    One catch still, it takes about six weeks until I receive it, the delivery is scheduled for July 5th. But then it’ll be great ๐Ÿ™‚

  • 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.