Archive for category Programming

Finding Your Center

Way back when I was in high school my typing teacher (yes, on a mechanical typewriter) taught us how to center blocks of text on a page. This has been a useful skill as I got into web development and programming as not everything has a built-in “center” alignment property.

I have never been asked how to do this, so it may be common knowledge, but I thought I would share anyway since I have not been blogging much. Basically, think about your viewing area as a page and what you are centering as a rectangle drawn on that page. Now fold that page in half and you will see that half of your rectangle is contained on half the page… makes sense. You are finding the horizontal position (x coordinate) of the left edge of your rectangle by subtracting half of its width from half the width of the page:

1
x = [page_width]/2 - [item_width]/2

or after a little simplification

1
x = ( [page_width] - [item_width] )/2

This is exactly the same way you would center vertically. The equation from above expressed with more meaningful terms:

1
y = ( [page_height] - [item_height] )/2

Now to bring this into the Java world you can center a JFrame in the center of your monitor screen:

1
2
3
4
5
Dimension frameSize = new Dimension(800,600);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screenSize.width-frameSize.width)/2;
int y = (screenSize.height-frameSize.height)/2;
frame.setBounds( x, y, frameSize.width, frameSize.height );

Not too bad at all, but it has always surprised me that Swing does not provide helper methods to center components inside of other components.

Popularity: 1% [?]

  • Share/Bookmark

Tags: ,

Sorting in JavaScript

Every now and then you need to sort something in JavaScript and though, it’s not all that hard to do, it is not the best-documented feature. Here is a quick little summary of how to do it.

You call the sort function of an array with your comparator. A JavaScript comparator is just a function that returns -1, 0, or 1 depending on whether a is less than b, a is equal to b, or a is greater than b:

1
2
3
4
5
6
7
8
9
myarray.sort(function(a,b){
    if(a < b){
        return -1;
    } else if(a == b){
        return 0;
    } else { // a > b
        return 1;
    }
});

This is just an example, your function can base the comparison on whatever you want, but it needs to return -1,0,1. Say you had a set of custom JavaScript objects that you want sorted by age:

1
var people = [{name:'Bob',age:21}, {name:'Fred',age:34}, {name:'Dan',age:19}];

You could easily sort them using

1
2
3
4
5
6
7
8
9
people.sort(function(a,b){
    if(a.age < b.age){
        return -1;
    } else if(a.age == b.age){
        return 0;
    } else { // a > b
        return 1;
    }
});

Not too hard to do. It’s actually very similar to the Java Comparator interface.

Popularity: 3% [?]

  • Share/Bookmark

Tags: ,

Java Hosting?

I love Java. I love the language. I love the JVM and I love the ever-increasing list of languages that run on the JVM. One thing that I really don’t like is the high cost of hosting Java web applications. Yes, if you search around you can find some that say they provide Java hosting via Tomcat or Jetty, but unless you get a dedicated server you are not really getting much out of it and there tend to be a lot of limitations involved.

I pay about $72 annually for hosting, and with that I get very limited support for hosting Java web applications. Basically I get a shared Tomcat instance that I cannot configure or restart myself, which is pretty useless beyond very simple applications. I don’t even have java command line access to run my own server from my account. In order to get true, useful, Java hosting you need to bump up your monthly cost quite a bit. Real Java hosting generally starts around $300 per year and goes up from there if you really need to get serious with it (adequate RAM, and JVM configurations). Google App Engine is on the right track but it’s limiting; you are limited to JPA or JDO and not even the full power of either of those along with other limitations. Where is the affordable yet functional Java web hosting for the developer or hobbyist with no real budget?

I then decided to look into some of the other web development languages and found that Ruby (on Rails) has a lot of the same issues with good inexpensive hosting. That struck me as odd since I would think RoR would have lower memory and system requirements. I also looked into Python and found that there seems to be very few options available for it. The big winner in the hosting support I guess should come as no surprise… PHP. PHP has come standard with every hosting package I have ever had or have ever really looked into… at no extra cost. I guess this is why it remains to be so popular.

I think I will have to dig deeper into PHP for some of my personal web projects. If not that, I may have to look at setting up my own server outside my firewall, which just brings up all kinds of other problems.

Popularity: 3% [?]

  • Share/Bookmark

Tags: , ,

Project Consolidation

I have been consolidating all of my personal projects and prototypes trying to get everything setup on Git and GitHub. I have used SourceForge for years, but have lately found their project management model a bit on the heavy side. I have really taking a liking to Git for my personal projects, so GitHub was an easy choice. GitHub provides good Git integration with lightweight wiki and bug-tracking as well as some other handy features like code archive downloading.

I have most of my projects converted over, though most of them will be going through some refactoring soon (package names, testing, personal code reviews, etc) so that they are all brought up to at least some minimum level of quality. I will also need to update some of my archived blog posts so that they point to the correct project repositories.

In general, I don’t think anybody else really cares about most of this stuff, but there is some useful code in there among the fluff and flair. There are a number of prototype and proof-of-concept type projects in there that I am not sure even work any more… so, I have some work to do. :-)

My GitHub Dashboard is located at: http://github.com/cjstehno, just be warned, currently all of the code is in a state of flux.

Enjoy!

Popularity: 3% [?]

  • Share/Bookmark

Tags: ,

Finding Duplicate Ints: Ruby and Groovy

I am going back to my old standard playtime function, finding the duplicated integer in a set of integers. I have been playing around a lot more with Groovy lately and I realized that I had never really done a Groovy version of that little function.

1
2
3
4
5
6
def findDups( n ){
    n.sort()
    for( i in (1..n.size())){
        if(n[i] == n[i-1]) return n[i]
    }
}

In this case, I am allowing null to be the value returned when no duplicate is found. It does seem to be a more realistic value for Groovy. It’s a pretty straight forward function, along the same lines as the other languages. I thought maybe I could find some really cool feature of Groovy that would make this radically different from the Java version… nope. It does collapse nicely down to a single line though:

1
def findDups( n ){ n.sort(); for( i in (1..n.size()) ) if(n[i] == n[i-1]) return n[i] }

If you like that sort of thing.

Shortly after, I decided to do a quick little Ruby version as well:

1
2
3
4
5
6
7
def findDups( n )
    n.sort!()
    for i in (1..n.size())
        if(n[i] == n[i-1]) then return n[i] end
    end
    return nil
end

Nothing exciting in either case, but worth doing for completeness.

Popularity: 3% [?]

  • Share/Bookmark

Tags: , , ,

My Final Answer

I use the Java ‘final’ keyword quite a bit and I often get asked why. I guess the quick answer would be, “why not”?

I tend to use ‘final’ for instance variables, method parameters and local variables. The keyword can also be used to make classes and methods final but I leave that for the cases when I actually want that specific functionality.

Final instance variables (private fields) are useful for case when you want to specify the value once and then never again. This is helpful when configuring an object through Constructor dependency injection:

1
2
3
4
5
6
7
8
9
10
public class MyController implements Controller {

    private final MyService myService;

    public MyController(final MyService myService){
        this.myService = myService;
    }

    // other methods
}

This allows you to configure the service object in the controller and not have to worry about any of the other methods overwriting it.

Using final for method parameters is quite handy since it keeps you from unexpectedly overwriting one. Consider the following code:

1
2
3
4
5
6
7
8
9
public int count(List<String> list, String name){
    int count = 0;
    Iterator<String> names = list.iterator();
    while(names.hasNext()){
        name = names.next();
        if(name.equals(name)) count++;
    }
    return count;
}

which contains a possibly hard to find variable overwrite error, which becomes quite obvious when you use final

1
2
3
4
5
6
7
8
9
public int count(final List<String> list, final String name){
    int count = 0;
    Iterator<String> names = list.iterator();
    while(names.hasNext()){
        String nme = names.next();
        if(nme.equals(name)) count++;
    }
    return count;
}

Local variables are made final for basically the same reason.

Now, I know that simply because a variable is final does not mean it’s internal data cannot change, such as

1
2
3
final Map<String,Date> dates = new HashMap<String,Date>();
dates.get("Anniversary"); // will work fine
dates.put("Birthday");    // will work fine

The final keyword does not make them immutable, you just cannot overwrite them. Final makes you think a bit before overwriting a variable with a new object and it can sometimes point out, and save you from, potential bugs.

Eclipse Save Actions

Making your IDE do the work for you. If you use Eclipse (or one of its derivatives) you can have it automatically add ‘final’ to your code. Go into the Preferences and search for “Save Actions” and you should get something like what is show here. I generally auto-final method parameters and local variables since I have found that making private fields final can cause issues with some reflection and/or byte-code manipulation techniques.

Once you have the save actions setup, you will automatically have final added every time you save a file. I would imagine IntelliJ and NetBeans both have some similar functionality available.

Ultimately, the use of final comes down to personal preference. I find it useful and helpful to use the final keyword throughout my code. If you don’t then you really don’t have to use it unless you find a case where it’s absolutely necessary. To me, though, I figure why not use it?

And that’s my final answer.

Popularity: 4% [?]

  • Share/Bookmark

Tags: , , ,

Groovy Unit Testing: Tools

The Java Metroplex User Group meeting last night was a presentation on unit testing and mocking with Groovy, presented by Venkat Subramaniam, a well-known author and consultant… and a great presenter to watch, by the way. In his presentation he showed various techniques for using Groovy to write unit testing for both Java classes and other Groovy classes.

Count me among the converted, but I was not sure just how easy it would be to bring Groovy into a Java project while still maintaining good Eclipse and Maven support. So, I did a quick little experiment and found out that the integration is trivial.

Say you have a maven project, we’ll call it “groover”, already hapily running maven under Java 6 and Maven 2. Add the following dependencies (assuming you dont already have JUnit 4):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.6</version>
    <type>jar</type>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy</artifactId>
    <version>1.7.0</version>
    <type>jar</type>
    <scope>test</scope>
</dependency>

You now have maven setup to run unit tests written in Groovy (assuming you have Groovy 1.7 installed locally as well).

To get everything working in Eclipse, import your project (if it’s not already in Eclipse) and be sure you have the Groovy Eclipse plug-in installed. You may also want/need the Maven Eclipse plug-in, but that is not a requirement. Once the project is imported, right click on the project name and convert it to a Groovy project. Now Eclipse is ready to go too.

Let’s proove that it works by writing a simple little class and a Groovy test for it:

1
2
3
4
5
6
7
package foo;

public class Something {
    public String doIt(String in){
        return in.concat(" gabadata!");
    }
}

and then the test is:

1
2
3
4
5
6
7
8
9
10
11
12
package foo

import org.junit.Test
import static org.junit.Assert.*

class SomethingTest {
    @Test
    void doIt(){
        def result = new Something().doIt('foo')
        assertEquals "foo gabadata!", result
    }
}

Run the test using Ctrl+Alt+X T (normal JUnit run command in Eclipse) and it works just like any other JUnit test. Run the test in a console with maven with “mvn test” and it still works just like normal.

My next thought was that surely it would not work with my coverage tools! I was wrong, coverage worked fine in both the IDE and in maven.

So, by writing unit tests in Groovy I get to write less code, have built in powerful mocking support, and no tool integration issues? Sign me up!

Popularity: 47% [?]

  • Share/Bookmark

Tags: , , ,

Shortcutting Search Loops

A simple mistake I have seen a lot is not breaking out of a search loop once you have found what you are searching for. Take the code below, for example:

1
2
3
4
5
6
7
8
9
10
11
public User findUser(String name){
    User foundUser = null;
   
    for( User user : product.getUsers() ){
        if( name.equals(user.getName()) ){
            foundUser = user;
        }
    }
   
    return foundUser;
}

This code will loop through every user even after you have found the user you are looking for, which for large sets of data can get very inefficient. You can shortcut the loop with a break statement:

1
2
3
4
5
6
7
8
9
10
11
12
public User findUser(String name){
    User foundUser = null;
   
    for( User user : product.getUsers() ){
        if( name.equals(user.getName()) ){
            foundUser = user;
            break;
        }
    }
   
    return foundUser;
}

which will drop the control out of the loop once your user has been found. You could also simply return the user when found, such as

1
2
3
4
5
6
7
8
public User findUser(String name){
    for( User user : product.getUsers() ){
        if( name.equals(user.getName()) ){
            return user;
        }
    }
    return null;
}

This version causes there to be two exit points in the method, which is often frowned upon. Personally, I don’t see a problem with this in short simple methods.

Lastly, if you are a couple levels deep in a loop and cannot simply use a “return” for some reason, you can use a label to break out of the loop. Consider this example of a Map of Lists (something that you generally should not do):

1
2
3
4
5
6
7
8
9
10
User foundUser = null;
Iterator<List<User>> lists = users.values();
finder: for( List<User> list : users.values() ){
    for( User user : list){
        if( name.equals(user.getName()){
            foundUser = user;
            break finder;
        }
    }
}

which will break out of the loop labeled “finder” (the outer loop).

There are, of course, other ways of breaking out of loops, but these are the most general and cleanest, in my opinion.

Popularity: 2% [?]

  • Share/Bookmark

Tags: , ,

Blissful Development

I have been working on a personal project to create a movie catalog database for our collection of movies. Yes, there are a handful of both desktop and web-based applications available to do this, though, they all seem to be lacking in one feature or another… and I needed an interesting useful project. This project has been one of my most enjoyable personal development projects; if you have ever seen my project graveyard, you know there have been quite a few that didn’t get very far for one reason or anther, usually time and/or complexity.

I owe my development-bliss on this project to something not usually found on modern software projects (at least in my experience)… simplicity. No, not simplicity of the project goals, but of the tools and the environment. For development I am using my favorite text editor, Notepad++, Cygwin (yes, I am doing this on Windows… I have not yet found a good solid text editor for Linux, perhaps I will have to make peace with vi)… and that’s it unless you want to count Firefox. But, wait… where is the IDE, the pile of plug-ins, and tools? Well, okay… I am also using Grails along with JQuery and JQueryUI. That’s the key… Grails.

With this environment I have been able to focus on building my application, not plumbing and other mundane details. I have an almost instant turn-around on changes to domain and controller classes, as well as a simple yet flexible syntax that allows for less IDE overhead, hence the text editor. Heck, most of my actual coding has been the HTML and JavaScript for the front-end; I have modified a few scaffold controller actions, and added a few of my own, which have all been simple and straightforward. It truly is a pleasant environment to work with.

Groovy itself is quite nice, providing a much more rich syntax while still maintaining total support of Java and Java syntax. One of the features of Grails I have always appreciated is that you always have Java to fall back on if you need a bit more performance, or access to something that cannot be accessed through Groovy itself. The two languages really coexist quite nicely.

I have the core JavaDocs pretty much burned into my memory (:-)), but I wonder how less-seasoned developers would find this setup. Without an IDE you don’t get code completion or the other helpful features that help to boost the productivity of more junior developers. It’s not meant to be a hard-core developer test; I am not into that kind of stuff. I am all about making development easier… and this just feels right for Grails (and Groovy).

Java web application development has gotten too hard somewhere along the way.

Popularity: 1% [?]

  • Share/Bookmark

Tags: , , , ,

Collapsible Divs With JQuery

I coded up a nice little collapsible-group side bar thingy using JQuery and it was surprisingly easy. Say you have a sidebar with collapsible group content such as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<div class="container">
    <div class="group">
        <div class="group-title">Group A</div>
        <div class="group-content">
            This is where you would put the content for Group A.
        </div>
    </div>
    <div class="group">
        <div class="group-title">Group B</div>
        <div class="group-content">
            This is where you would put the content for Group B.
        </div>
    </div>
    <div class="group">
        <div class="group-title">Group C</div>
        <div class="group-content">
            This is where you would put the content for Group C.
        </div>
    </div>
</div>

where you have group block titles and group content that you want to be able to toggle the visibility of. With a couple lines of JavaScript and JQuery it’s a sinch:

1
2
3
$('div.group-title').bind('click',function(evt){
    $(evt.target).parent().find('.group-content').slideToggle(500);
});

which will be put inside an onload handler (also using JQuery). When the group title is clicked, the group-content block will toggle by sliding up or down in about half a second. With this model you can also place any number of these “components” on a page without the concern about event collision since the event handling is based on the click location.

Add in a little CSS and you end up with:

Popularity: 8% [?]

  • Share/Bookmark

Tags: , , ,

Switch to our mobile site