Something I do on the NixMash Home Page is a Vermont Banner of the Day. Photos are licensed with a Creative Commons License, so you'll always see an attribution at the bottom of the page. The Banner changes every day, and in this post we're going to look at the logic of making that happen. And yes, it's more interesting that it sounds if you're a Java Coder.
A NixMash Home Page with banner at the top and attribution at the bottom.
I started the feature with 10 or so banners and added images over time, so the original logic was to use the image ID based on the day of the month. It was slightly more involved because banners could be deactivated, so the dayOfMonth retrieved from the Active SiteImage Array index. As a side point, notice the long but effective Spring JPA Named Method .findByBannerImageTrueAndIsActiveTrue().
This logic was fine as long as the number of images was less than the number of days in the month, but not so much when the number of images was larger. Time to bring in a random selection logic, but as simple a solution as possible. Remember, one banner per day, no more, no less.
The trick was to modify the SiteImage table to support an isCurrent Boolean and a fixed value for each record that changed by day, a dayOfYear Integer.
As an overview, the logic for displaying one-and-only-one Banner of the Day is the following:
Let's see what that looks like in an Integrated @Test method. We're going to go through a year's worth of banner displays in our 1-to-365 day iteration loop. We reset the table and confirm we don't have a currentSiteImage. Next we select a random image from our Active Banners and set it as our isCurrent SiteImage. Our final step is to retrieve a SiteImage object based on our isCurrent is true and current dayOfYear value.
Go Live Time, with the final Service Layer Method looking like this.
One of the things you strive for as a developer is perform tasks simply, and with Banner of the Day you see that in action.