Ads 468x60px

freak2code is the blog about latest geek news,software reviews ,trends in technology and more informative stuff......

Monday, 13 August 2012

Pyramid traversal: almost useful

Pyramid is, to skip a lot of history, a successor to Pylons. It’s a Web framework for Python. (And there goes half my audience.) This post is about dispatch: mapping URLs to the code you want to run. (There goes the other half.)

Pyramid traversal: almost useful

Pyramid supports traditional URL routing, which looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
config.add_route('cats.list', '/cats')
config.add_route('cats.view', '/cats/{id}')

@view_config(route_name='cats.list', renderer='cat_list.mako')
def cat_list(context, request):
    return dict()

@view_config(route_name='cats.view', renderer='cat_view.mako')
def cat_view(context, request):
    cat = get_cat(request.matchdict['id'])
    if not cat:
        raise NotFound()
    return dict(cat=cat)
Gosh that’s a lot of things. The idea here is:
  • If you visit /cats, Pyramid will find the route called cats.list. That route is attached to the cat_listfunction, which will run, return a dict, and pass that off to the cat_list.mako template for rendering.
  • If you visit /cats/123, Pyramid will find cat_view instead. The id (here 123) will be inrequest.matchdict; the function has to find the cat with that id and bail if it doesn’t exist. Then template blah blah blah.
Following? Excellent.
The immediate problem with this approach is what happens when you have a lot of cat-related URLs. Maybe you want to show a cat’s owner history and innoculations and cross-reference with funny cat videos on YouTube. Now you have:
1
2
3
4
5
6
config.add_route('cats.list', '/cats')
config.add_route('cats.view', '/cats/{id}')
config.add_route('cats.owners', '/cats/{id}/owners')
config.add_route('cats.shots', '/cats/{id}/shots')
config.add_route('cats.youtubes', '/cats/{id}/youtubes')
config.add_route('cats.hurpdurp', '/cats/{id}/hurpdurp')
That’s not too bad, except that now you have to do the get_cat runaround in every one of these functions. For simple views, that’s going to be half the code you even run.
Okay, you say, so put that in a function called… uh, real_get_cat. Great, except now what about when we expand our site to funny dog videos? Now we have another wrapper for getting a dog, and maybe one for getting rabbits. Meanwhile, we’re copy-pasting the /cats/{id} prefix in all the routes—if we wanted to be more specific that ids are numeric, it gets even worse, with /cats/{id:\d+}.
Consider URL generation, as well: you need to call request.route_url('cats.view', id=cat.id). Not so bad, I suppose, but manually plucking out the id everywhere you make a URL is a bit tedious. And it might be different for every kind of object; maybe dogs’ URLs use their names instead. You can add a pregenerator to the add_route call, though.
So now we have:
1
2
3
4
5
6
7
8
9
10
11
config.add_route('cats.list', '/cats')
config.add_route('cats.view', '/cats/{id:\d+}', pregenerator=make_cat_url)
config.add_route('cats.owners', '/cats/{id:\d+}/owners', pregenerator=make_cat_url)
config.add_route('cats.shots', '/cats/{id:\d+}/shots', pregenerator=make_cat_url)
config.add_route('cats.youtubes', '/cats/{id:\d+}/youtubes', pregenerator=make_cat_url)
config.add_route('cats.hurpdurp', '/cats/{id:\d+}/hurpdurp', pregenerator=make_cat_url)
config.add_route('dogs.view', '/dogs/{id:\d+}', pregenerator=make_dog_url)
config.add_route('dogs.owners', '/dogs/{id:\d+}/owners', pregenerator=make_dog_url)
config.add_route('dogs.shots', '/dogs/{id:\d+}/shots', pregenerator=make_dog_url)
config.add_route('dogs.youtubes', '/dogs/{id:\d+}/youtubes', pregenerator=make_dog_url)
config.add_route('dogs.hurpdurp', '/dogs/{id:\d+}/hurpdurp', pregenerator=make_dog_url)
This makes me kind of sad.
Alas, there is one last kink: I have shared comment functionality. You can have comments on cats, or comments on dogs. And there are several URLs relating to comments, for viewing and replying and so forth. So I need to put all those as well, once for each kind of thing comments can be attached to, and flail wildly to get the right kind of object in the actual comment code.

Enter traversal

Traversal is the thing Pyramid did before it had routing. The idea is that it works like a filesystem would:/foo/bar/baz really means “find the foo directory, then find the bar directory in that, then find something calledbaz in that”. In Pyramid, this is done with dictionary access: that same path is treated as root['foo']['bar']['baz'].
So you might built your site like this:
1
2
3
4
5
site_root = dict(
    foo=dict(
        bar=dict(),
    ),
)
Pyramid would look up each chunk of the path in order until it ran out of chunks or couldn’t go any further. Our example URL would reach that inner empty dictionary, which would become the “context”. The “view name” would be the next unused part, baz, and anything else is considered the “subpath”. (There aren’t any other chunks here, so the subpath is an empty tuple.)
Instead of a route name, the view name and context’s class get used for finding the code to run. In practice, the above example isn’t very useful; you can’t easily tell those dicts apart. You might want something more like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Root(object):
    def __getitem__(self, key):
        if key == 'cats':
            return CatList()
        raise KeyError

class CatList(object):
    def __getitem__(self, key):
        # Find a cat
        cat = get_cat(key)
        if cat:
            return cat
        else:
            raise KeyError

site_root = Root()

@view_config(context=CatList, renderer='cat_list.mako')
def cat_list(context, request):
    return dict()

@view_config(context=Cat, name='', renderer='cat_view.mako')
def cat_view(context, request):
    return dict(cat=context)

@view_config(context=Cat, name='owners', renderer='cat_owners.mako')
def cat_owners(context, request):
    return dict(cat=context)
Note that the context argument is the traversal context: the last thing Pyramid found. I included the argument in the routing example, too, but it wasn’t anything useful there.
Now when we ask for /cats/123/owners, the following happens:
  1. Start at the site_root.
  2. Check for the key cats. Get a CatList object back.
  3. Check for the key 123. Get a Cat object back.
  4. Check for the key owners. Cat objects don’t support subscripting, so stop here. The Cat is the context;owners is the view name; the subpath is empty again.
This is looking kind of promising. It’s more verbose, but since it’s all classes, I can add new ones with less effort than it takes to make a new set of routes. The code for finding a cat or bailing is in one obvious place; I have less copy/paste of arcane route declarations; and I can do my comments structure fairly easily, by just making bothCat and Dog return a CommentList sort of object that remembers the cat/dog I already found.

The Bad, The Ugly

So I tried actually applying this to floof. It seemed like such a nice idea, really. Obviously I wouldn’t be writing this if I hadn’t hit a ton of roadblocks.
  • The subpath. There’s no way to match against it in @view_config, nor any way to disable it. This means that /cats/123/owners does exactly the same thing as/cats/123/owners/durp/blah/foo/junk/whatever. The extra stuff just gets tucked away inrequest.subpath. Maybe I shouldn’t care, but this really bothers me.
  • There’s no way to force a 404 within traversal; a node/resource can only say “I contain this” or “I don’t contain this”. So if you request /cats/456, but there’s no cat number 456, Pyramid will make CatListthe context and 456 the view name.
  • Naturally, it’s possible to take a context object and get back a URL: request.resource_url(cat, 'owners') for cat number 123 will theoretically generate /cats/123/owners.
    Alas, this works by looking at __name__ and __parent__ properties on the context object; here __name__should be 123 and __parent__ should be some CatList(), which will have its own name and parent. If you’re using some existing classes as context (say, SQLAlchemy objects), then these properties won’t be there! You can add a @property to the classes to generate them, but why on Earth would I want my data to contain references to my URL structure?
    Another alternative is to create a CatPage class to wrap the actual cat object and put the special properties on that class, instead… but then you can’t call resource_url() on an arbitrary cat object! You have to wrap it manually, instead.
  • request.resource_url(cat, 'owners') produces /cats/123/owners. request.resource_url(cat)produces /cats/123/. The rationale is something about “relative URLs in your page” that makes no sense to me at all.
  • If you write request.route_url('cats.foo'), and cats.foo isn’t a known route name, the page will just fail to render. This is fantastic: you can catch bad URLs almost immediately. Unfortunately,request.resource_url(cat, 'foo') won’t check whether there’s a view named foo for Cat objects; you’ll just find out, maybe, when it 404s.

Dammit

Neither routing nor traversal seems to reflect how anyone builds Web applications—or at least not how I build Web applications.
Routing works well for a few pages with specific URLs, but doing anything structured requires a lot of repetition—and while you could wrap routing in loops and functions, that rapidly becomes confusing to read, losing one of the advantages of routing in the first place.
Traversal works well for serving files from a directory, but… honestly, not much else! Every problem listed above seems to reflect a bias towards serving an actual filesystem.
Pyramid does have a lot of hooks; it’s possible to replace the traversal mechanism entirely. I just don’t really want to do that to get around these strange little problems. A lot of the resource stuff also assumes pretty firmly that you’re using the __parent__ mechanism.

Continuous Android testing with Guard


Continuous Android testing with Guard

Because it’s my bag, I’ve been spending a lot of time these days deep in Ruby code. Nevertheless, from time to time, I do find myself ensconced in Java via the Android platform. Jumping back and forth between various languages like Ruby, Java, and JavaScript can be a lot of fun; what’s more, doing so broadens one’s view on various practices, idioms, and influences conveyed by a particular community.
Something that I found missing in Java’s community, in the form of a concrete easy to use library, is something like Ruby’s Guard. Guard is “a command line tool to easily handle events on file system modifications.” In essence, Guard makes continuous testing possible with a minimum amount of effort.
For example, with Guard, you can create a Guardfile that watches your file system (naturally, you can select which types of files to watch — .rb files, etc); what’s more, when those target files change (i.e. you added some code) a trigger can be invoked, such as running a test suite, invoking a Rake command, etc. Thus, with Guard, you can set up a process that executes a test suite (or an individual test) whenever you change a source file — this alleviates you from having to manually invoke a Rake task or do something else to trigger a test run.
As you can imagine, once you’ve set this up, it becomes highly addictive — why would anyone ever manually invoke Rake test again? It’s always running anyway!
Setting up Guard to invoke Ant, for example, couldn’t be any easier. You first must have Ruby installed, followed by RubyGems and Bundler. Next, in your Gemfile, you need to include guard as follows:
source :rubygems
group :development do
gem 'guard'
gem 'growl'
end
Because I’m on a Mac, I’m also using Growl, which is an OS-level notification mechanism (i.e. a popup dialog that informs you that your test suite has passed, failed, etc).
Next, you need to create a Guardfile — in this case, I’m going to create an inline Guardfile as there isn’t a plugin available (yet) to support running something like Ant. My inline Guardfile looks like this:
require 'guard/guard'
module ::Guard
class Ant< ::Guard::Guard
def run_all
invoke_ant
end
def run_on_changes(paths)
invoke_ant
end
def start
invoke_ant
end
def stop
end
def invoke_ant
system 'ant clean test'
end
end
end
guard 'ant' do
watch(%r{^src/*/(.+)\.java$})
end
As you can see, this Guardfile simply watches any .java file and if any change, run’s ant clean test — theGuard base class is fairly straightforward — there are a series of hook methods you can implement. In this case,start is called the first time you fire up Guard. run_on_changes ideally is used to run a single test as you have access to the incoming file path of what’s changed; however, in this case, I’ve chosen to run the suite again as parameter passing into Ant & invoking a special JUnit task with single tests is somewhat painful (but it could be certainly done). Finally, run_all is called at special points, such as after you fix a failing test, etc. In essence, these are lifecycle methods and you have complete control over what happens when they are invoked.
Continuous testing in Java isn’t new. Yet, it seems that the wealth of tools and thought regarding continuous testing results in a shift towards Continuous Integration or worse, the IDE. For instance, a simple search on continuous testing tools in Java yields Infinitest and JUnit Max — both are great tools (Ben Rady, the originalInfinitest guy is one of the sharpest guys I know). These tools, however, are plugins for an IDE, like Eclipse. I abandoned Eclipse some time ago in favor of IntelliJ (and Infinitest certainly supports IntelliJ); thus, these days, I do all Android development using IntelliJ, however, I tend to rely on Ant for building Android artifacts (even though there is a Maven library for Android).

Singleton Design Pattern. All flavours explained.


Singleton Design Pattern. All flavours explained.

Hi!
This design pattern is used for controlling the number of instances of a class (to one in general). This is maybe the first, the most used and the easiest design pattern out there.
Beware that this control ( controlling the number of instances of a class ) is available per classloader, and not for JVM, not to say more when thinking at distributed topologies. This is because the final static instance variable – being static is per class basis. As you know now, in a JVM you can have more than one classloader – meaning you can load the same Singleton implementing class more than once (once per classloader). Loading more than once the Singleton implementing class results in the possibility of having n instances controlled by the singleton per JVM, where n represents the number of the loads of the Singleton implementing class, so will need at least n classloaders.
In a multiple JVM topology ( cluster deployed application ) special algorithms must be taken into consideration for controlling the number of instances of a class. These can be fine-tuned depending on the needs of the application requirements.
From the point of view of the memory and processor usage that can be impacted depending from one implementation to the other, I would categorize them into the following:
• standard form – the memory savvy version: I consider it a memory savvy version because the instance is created only on a per-need basis, which is trivial. No one needs it, no instance is created: save memory.
class Singleton {
private static Singleton INSTANCE;
private Singleton()
{
//do complicated initialization stuff
}
public static Singleton getInstance()
{
if (INSTANCE == null)
INSTANCE = new Singleton();
return INSTANCE;
}
}
• less standard form – the processor savvy version: Well this version will initialize the instance of the Singleton implementing class regardless someone needs it or not! It will be created at the primordial moment of loading the Singleton class by the classloader into the JVM memory.
Why would you use this? If you have some large quantity processor killing initialization tasks and you don’t want the first time an instance is needed to put the rest of the application and the user on hold until this completes, you create it at the very most starting point of the application, such that, when a user triggers the need of this singleton she/he would not have to wait. Think at the compile time for jsp’s – it’s something similar . Beam me out!
class Singleton{
private static final Singleton INSTANCE = new Singleton();
private Singleton()
{
//do complicated initialization stuff
}
public static Singleton getInstance()
{
return INSTANCE;
}
}
some notes have to be added here :
- notice the final modifier has appeared – that’s because the initialization is made before the statics are finished loading into the memory and now we actually can make use of it! (Theory says that any final has to be initialized before the constructor finishes – that’s for non-statics – aaand – for statics is before the attributes are loaded into the memory – in other words, before the classloader finishes loading the class). Proof? Try initing the static final variable on a different line than the declaration like – take for example in a static field =>compiles; delete the static field =>fail. Conclusion: having a final in the memory savvy version would yield a compile time error because the “The blank final field s may not have been initialized” – which makes sense since if it wouldn’t you maybe forgot about it and then it should be automatically assigned – and then, when calling the getInstance you would choke with a runtime error since a final cannot be changed!
- This version can also be used when you wouldn’t want to miss with the synchronized version coming up next, but you would still want to have a thread-safe Singleton implementation. Explanations right after the break in the least standard form.
• least standard form – the synchronized version:
class Singleton{
private static final Singleton INSTANCE;
private Singleton()
{
//do complicated initialization stuff
}
public static Singleton getInstance()
{
if (INSTANCE == null)
{
synchronized(Singleton.class) {
if (INSTANCE == null)
INSTANCE = new Singleton();
}
}
return instance;
}
}
Notice the getInstance() method alters the value of the instance variable – this is highly sensitive when in a multithreaded environment because we could hit the fan while in the if(instance==null) line. Two or more threads could enter this if scope and then manage their way to the sweet initialization block – hence more than wanted (in this case more than 1) instances will be created. For this issue, we add an additional if(instance==null) which we synchronize access to in order to lock the access to the assignment line. Some of us might ask ourselves why there are 2(two) if’s? That’s because if we remove the 1st if(the unsynchronized one) we’ll introduce unneeded interlocking processes using directly the synchronized block. Considering the fact that the synchronized block is need only ONE TIME (in this case, or a finite times in other cases when we need more than one controlled instance) and that’s when the initialization is made, putting the first if in the code(the unsynchronized one) eliminates the interlocking mechanisms after the initialization block is finished – in other words, once the instance variable is set, any number of threads accessing the if(instance != null) will get false and they’ll not get further to the synchronized interlocking after the initialization. If you hate synchronization you can pick the processor savvy version and initialize the instance variable in the static context directly and avoid the multithreaded headache. You should still think at the architecture of your solution and ponder if that’s better or not to save memory or processor.

Undocumented Oracle JVM HttpServer Properties


Undocumented Oracle JVM HttpServer Properties

I have blogged before on the utility of the HttpServer provided with the Oracle HotSpot JVM. One of the general challenges associated with its use is the lack of documentation. Fortunately, its open source implementationallows certain features to be discovered. In this post, I look at some apparently undocumented properties that are used by the HttpServer's source code.
A colleague (thanks Jim!) pointed out the existence of these properties as discovered in the source code. There are multiple places from which the relevant source code can be acquired and reviewed. One easily accessible location is Docjar. For example, the code listings for sun.net.httpserver.ServerConfig andsun.net.httpserver.ServerImpl are hosted there. Other similar sites include Open Source Java Code(ServerConfig) and grepcode (ServerConfig).
The static initialization block of the sun.net.httpserver.ServerConfig class includes the setting of several static variables based on specific Java properties or based on a default if no property is provided. The next code listing comes from that class and indicates the default values for these static variables.
static final int DEFAULT_CLOCK_TICK = 10000 ; // 10 sec.
/* These values must be a reasonable multiple of clockTick */
static final long DEFAULT_IDLE_INTERVAL = 30 ; // 5 min
static final int DEFAULT_MAX_IDLE_CONNECTIONS = 200 ;
static final long DEFAULT_MAX_REQ_TIME = -1; // default: forever
static final long DEFAULT_MAX_RSP_TIME = -1; // default: forever
static final long DEFAULT_TIMER_MILLIS = 1000;
static final long DEFAULT_DRAIN_AMOUNT = 64 * 1024;
As the code and comments above indicate, the default idle interval is 300 seconds (5 minutes). The default request and response times are "forever" indicated by -1.
Although defaults are available as indicated in the above code listing, these can be overridden via the specification of Java properties. These properties are not well documented, but can be gleaned from the code. The following is a list of them as extracted from the ServerConfig class with notes about each property based on other portions of the code.
Properties for Configuring HotSpot HttpServer
  • <a href="https://forums.oracle.com/forums/thread.jspa?threadID=1147904">sun.net.httpserver.idleInterval</a>
  • sun.net.httpserver.clockTick
  • sun.net.httpserver.maxIdleConnections
  • sun.net.httpserver.drainAmount
  • sun.net.httpserver.maxReqTime
    • Replaces sun.net.httpserver.readTimeout
  • sun.net.httpserver.maxRspTime
    • Replaces sun.net.httpserver.writeTimeout
  • sun.net.httpserver.timerMillis
  • <a href="http://stackoverflow.com/a/9984009">sun.net.httpserver.debug</a>
Note that the property sun.net.httpserver.selCacheTimeout is no longer used, but does not have its replacement spelled out in the code comments or logged messages.
The Oracle JVM HttpServer allows for configuration based on Java properties. These properties are not well advertised, but the open source nature of the HttpServer implementation makes it possible to browse the code to determine which properties are available.

NetBeans 7.2: Refactoring Parameterized Constructor As Builder


NetBeans 7.2: Refactoring Parameterized Constructor As Builder

Shortly after the Second Edition of Josh Bloch's Effective Java was released, I borrowed a colleague's copy to browse it and consider purchasing a copy of my own despite already owning a copy of the first edition. It did not take me long to realize that the Second Edition was worth purchasing. In particular, the usefulness of the first new item in the Second Edition (Item #2 "Consider a builder when faced with many constructor parameters") struck me. This item addressed many issues I had run into during my Java development in a nice fashion. In this post, I look at the approach described in that chapter and look at how NetBeans 7.2 provides refactoring support for this approach.
As outlined in Item #2 of the Second Edition of Effective Java, there are several disadvantages to using constructors with large parameter lists. To help illustrate, I include a code listing below.
Employee.java
package dustin.examples;
/**
* Simple employee class intended to illustrate NetBeans 7.2 and refactoring
* constructor to use Builder pattern as discussed in Item #2 of the Second
* Edition of Joshua Bloch's <em>Effective Java</em>.
*
* @author Dustin
*/
public class Employee
{
private String lastName;
private String middleName;
private String firstName;
private long id;
private int birthYear;
private int birthMonth;
private int birthDate;
private int hireYear;
private int hireMonth;
private int hireDate;
public Employee(
final String newLastName,
final String newMiddleName,
final String newFirstName,
final long newId,
final int newBirthYear,
final int newBirthMonth,
final int newBirthDate,
final int newHireYear,
final int newHireMonth,
final int newHireDate)
{
this.lastName = newLastName;
this.middleName = newMiddleName;
this.firstName = newFirstName;
this.id = newId;
this.birthYear = newBirthYear;
this.birthMonth = newBirthMonth;
this.birthDate = newBirthDate;
this.hireYear = newHireYear;
this.hireMonth = newHireMonth;
this.hireDate = newHireDate;
}
}
Employee's parameterized constructor includes numerous parameters and this presents a challenge to clients of this class that need to create a new instance of it. This particular constructor is particularly tricky for clients because it has three consecutive String parameters and numerous consecutive int parameters. It is all too easy for a client to mix up the order of these same-typed parameters in the invocation.
Suppose that business logic is such that an employee should be instantiable with only a last name, first name, and ID provided. In other words, suppose that all attributes of the class are optional except for the three just mentioned. In such a case, with only a constructor like that one above, the client would need to pass null for the middle name String and zeroes or some other number without meaning. The numeric types could be reference types rather than primitives, but the clients would still need to pass null for each optional argument.
One might argue that a three-argument constructor could accepting the three required attributes' values could be supplied and then appropriate set methods could be invoked to set each optional attribute. However, this approach has drawbacks. For one, it makes it easier for the client to accidentally instantiate an instance with a bad or partial state. In some cases, it is not desirable to change the state of the object after instantiation, but the presence of the set methods make it more mutable than desired. Indiscriminate supplying of set methods hasseveral drawbacks in the world of concurrency and object-oriented interfaces.
An elegant approach that allows a client to only supply optional parameters that are meaningful without supplying otherwise unnecessary set methods is the Builder pattern. NetBeans 7.2 makes it easy to refactor the constructor with the long parameter list in the above example to take advantage of an instance of Builder. The next screen snapshot shows how I can use NetBeans 7.2 to accomplish this by hovering over the parameterized constructor, right-clicking on it, and selecting the option "Replace constructor with Builder...".

When this option is selected a popup similar to that shown in the next screen snapshot appears.

The refactoring tool only allows parameters passed to the constructor being refactored to be set in the builder. I can check the boxes of the optional attributes. When I make an attribute optional without supplying a default value, a warning appears as shown in the next screen snapshot.

If I supply default values (null for the String and zero for the integers that should never be zero for valid values), the warnings go away.

It is worth pointing out here that the refactor tool allows the refactor to continue when only warnings (no errors) are present. An error might be caused, for example, by declaring a package and class name of the builder to be generated with a name used by an existing class.
The "Preview" button can be clicked to see what the class would look like without actually creating the class file. When the "Refactor" button is clicked, a new Java class with the package and class name indicated in the "Builder Class Name" text field is created. The result in this case is shown in the next screen snapshot with the generated code listed in a listing following the snapshot.

NetBeans 7.2-Generated EmployeeBuilder.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dustin.examples;
public class EmployeeBuilder
{
private String newLastName;
private String newMiddleName = null;
private String newFirstName;
private long newId;
private int newBirthYear = 0;
private int newBirthMonth = 0;
private int newBirthDate = 0;
private int newHireYear = 0;
private int newHireMonth = 0;
private int newHireDate = 0;
public EmployeeBuilder()
{
}
public EmployeeBuilder setNewLastName(String newLastName)
{
this.newLastName = newLastName;
return this;
}
public EmployeeBuilder setNewMiddleName(String newMiddleName)
{
this.newMiddleName = newMiddleName;
return this;
}
public EmployeeBuilder setNewFirstName(String newFirstName)
{
this.newFirstName = newFirstName;
return this;
}
public EmployeeBuilder setNewId(long newId)
{
this.newId = newId;
return this;
}
public EmployeeBuilder setNewBirthYear(int newBirthYear)
{
this.newBirthYear = newBirthYear;
return this;
}
public EmployeeBuilder setNewBirthMonth(int newBirthMonth)
{
this.newBirthMonth = newBirthMonth;
return this;
}
public EmployeeBuilder setNewBirthDate(int newBirthDate)
{
this.newBirthDate = newBirthDate;
return this;
}
public EmployeeBuilder setNewHireYear(int newHireYear)
{
this.newHireYear = newHireYear;
return this;
}
public EmployeeBuilder setNewHireMonth(int newHireMonth)
{
this.newHireMonth = newHireMonth;
return this;
}
public EmployeeBuilder setNewHireDate(int newHireDate)
{
this.newHireDate = newHireDate;
return this;
}
public Employee createEmployee()
{
return new Employee(newLastName, newMiddleName, newFirstName, newId, newBirthYear, newBirthMonth, newBirthDate, newHireYear, newHireMonth, newHireDate);
}
}
As the screen snapshot and code listing above indicate, NetBeans 7.2 generated a builder based on the constructor. This was easily done, but there are a few things I don't like about it as much as the builders I have generated by hand. For the builders I have built by hand, I have chosen to have required attributes be part of the builder's constructor so that they must be supplied (I had expected this to happen for the parameters that I did not check the box for optional on). This is shown in the next code listing, which is an adaptation of the generated code shown above. The only thing changed from above is the builder's constructor. It now takes parameters for the Employee class's required attributes.
Adapted EmployeeBuilder.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dustin.examples;
public class EmployeeBuilder
{
private String newLastName;
private String newMiddleName = null;
private String newFirstName;
private long newId;
private int newBirthYear = 0;
private int newBirthMonth = 0;
private int newBirthDate = 0;
private int newHireYear = 0;
private int newHireMonth = 0;
private int newHireDate = 0;
public EmployeeBuilder(
final String newBldrLastName, final String newBldrFirstName, final String newBldrMiddleName)
{
this.newLastName = newBldrLastName;
this.newFirstName = newBldrFirstName;
this.newMiddleName = newBldrMiddleName;
}
public EmployeeBuilder setNewLastName(String newLastName)
{
this.newLastName = newLastName;
return this;
}
public EmployeeBuilder setNewMiddleName(String newMiddleName)
{
this.newMiddleName = newMiddleName;
return this;
}
public EmployeeBuilder setNewFirstName(String newFirstName)
{
this.newFirstName = newFirstName;
return this;
}
public EmployeeBuilder setNewId(long newId)
{
this.newId = newId;
return this;
}
public EmployeeBuilder setNewBirthYear(int newBirthYear)
{
this.newBirthYear = newBirthYear;
return this;
}
public EmployeeBuilder setNewBirthMonth(int newBirthMonth)
{
this.newBirthMonth = newBirthMonth;
return this;
}
public EmployeeBuilder setNewBirthDate(int newBirthDate)
{
this.newBirthDate = newBirthDate;
return this;
}
public EmployeeBuilder setNewHireYear(int newHireYear)
{
this.newHireYear = newHireYear;
return this;
}
public EmployeeBuilder setNewHireMonth(int newHireMonth)
{
this.newHireMonth = newHireMonth;
return this;
}
public EmployeeBuilder setNewHireDate(int newHireDate)
{
this.newHireDate = newHireDate;
return this;
}
public Employee createEmployee()
{
return new Employee(newLastName, newMiddleName, newFirstName, newId, newBirthYear, newBirthMonth, newBirthDate, newHireYear, newHireMonth, newHireDate);
}
}
The code used to call the adapted builder shown in the last code listing is exemplified in the following code listing. This code listing demonstrates how readable ("fluent" in the more trendy vernacular) the client code is with the builder and demonstrates that the object is never in a partial or inconsistent state.
package dustin.examples;
import java.util.Calendar;
/**
* Example calling adapted employee builder to get an instance of employee.
*
* @author Dustin
*/
public class Main
{
public static void main(final String[] arguments)
{
final Employee employee =
new EmployeeBuilder("Coyote", "Wile", "E.")
.setNewBirthMonth(Calendar.SEPTEMBER)
.setNewBirthDate(17)
.setNewBirthYear(1949)
.createEmployee();
}
}
The most significant drawbacks to the builder implementation are potential performance impacts of extra object instantiation (probably not an issue for most Java applications) and the extra code verbosity.
Although I don't show it here, the other thing I like to do with my builder implementations is to include them as nested classes in the class they build. This is how the code example in the second item of the Second Edition of Effective Java implements it, but I don't see anyway in NetBeans 7.2 to generate the builder as a nested class rather than as a standalone class.

NetBeans 7.2: Refactoring Parameterized Constructor As Builder


NetBeans 7.2: Refactoring Parameterized Constructor As Builder

Shortly after the Second Edition of Josh Bloch's Effective Java was released, I borrowed a colleague's copy to browse it and consider purchasing a copy of my own despite already owning a copy of the first edition. It did not take me long to realize that the Second Edition was worth purchasing. In particular, the usefulness of the first new item in the Second Edition (Item #2 "Consider a builder when faced with many constructor parameters") struck me. This item addressed many issues I had run into during my Java development in a nice fashion. In this post, I look at the approach described in that chapter and look at how NetBeans 7.2 provides refactoring support for this approach.
As outlined in Item #2 of the Second Edition of Effective Java, there are several disadvantages to using constructors with large parameter lists. To help illustrate, I include a code listing below.
Employee.java
package dustin.examples;
/**
* Simple employee class intended to illustrate NetBeans 7.2 and refactoring
* constructor to use Builder pattern as discussed in Item #2 of the Second
* Edition of Joshua Bloch's <em>Effective Java</em>.
*
* @author Dustin
*/
public class Employee
{
private String lastName;
private String middleName;
private String firstName;
private long id;
private int birthYear;
private int birthMonth;
private int birthDate;
private int hireYear;
private int hireMonth;
private int hireDate;
public Employee(
final String newLastName,
final String newMiddleName,
final String newFirstName,
final long newId,
final int newBirthYear,
final int newBirthMonth,
final int newBirthDate,
final int newHireYear,
final int newHireMonth,
final int newHireDate)
{
this.lastName = newLastName;
this.middleName = newMiddleName;
this.firstName = newFirstName;
this.id = newId;
this.birthYear = newBirthYear;
this.birthMonth = newBirthMonth;
this.birthDate = newBirthDate;
this.hireYear = newHireYear;
this.hireMonth = newHireMonth;
this.hireDate = newHireDate;
}
}
Employee's parameterized constructor includes numerous parameters and this presents a challenge to clients of this class that need to create a new instance of it. This particular constructor is particularly tricky for clients because it has three consecutive String parameters and numerous consecutive int parameters. It is all too easy for a client to mix up the order of these same-typed parameters in the invocation.
Suppose that business logic is such that an employee should be instantiable with only a last name, first name, and ID provided. In other words, suppose that all attributes of the class are optional except for the three just mentioned. In such a case, with only a constructor like that one above, the client would need to pass null for the middle name String and zeroes or some other number without meaning. The numeric types could be reference types rather than primitives, but the clients would still need to pass null for each optional argument.
One might argue that a three-argument constructor could accepting the three required attributes' values could be supplied and then appropriate set methods could be invoked to set each optional attribute. However, this approach has drawbacks. For one, it makes it easier for the client to accidentally instantiate an instance with a bad or partial state. In some cases, it is not desirable to change the state of the object after instantiation, but the presence of the set methods make it more mutable than desired. Indiscriminate supplying of set methods hasseveral drawbacks in the world of concurrency and object-oriented interfaces.
An elegant approach that allows a client to only supply optional parameters that are meaningful without supplying otherwise unnecessary set methods is the Builder pattern. NetBeans 7.2 makes it easy to refactor the constructor with the long parameter list in the above example to take advantage of an instance of Builder. The next screen snapshot shows how I can use NetBeans 7.2 to accomplish this by hovering over the parameterized constructor, right-clicking on it, and selecting the option "Replace constructor with Builder...".

When this option is selected a popup similar to that shown in the next screen snapshot appears.

The refactoring tool only allows parameters passed to the constructor being refactored to be set in the builder. I can check the boxes of the optional attributes. When I make an attribute optional without supplying a default value, a warning appears as shown in the next screen snapshot.

If I supply default values (null for the String and zero for the integers that should never be zero for valid values), the warnings go away.

It is worth pointing out here that the refactor tool allows the refactor to continue when only warnings (no errors) are present. An error might be caused, for example, by declaring a package and class name of the builder to be generated with a name used by an existing class.
The "Preview" button can be clicked to see what the class would look like without actually creating the class file. When the "Refactor" button is clicked, a new Java class with the package and class name indicated in the "Builder Class Name" text field is created. The result in this case is shown in the next screen snapshot with the generated code listed in a listing following the snapshot.

NetBeans 7.2-Generated EmployeeBuilder.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dustin.examples;
public class EmployeeBuilder
{
private String newLastName;
private String newMiddleName = null;
private String newFirstName;
private long newId;
private int newBirthYear = 0;
private int newBirthMonth = 0;
private int newBirthDate = 0;
private int newHireYear = 0;
private int newHireMonth = 0;
private int newHireDate = 0;
public EmployeeBuilder()
{
}
public EmployeeBuilder setNewLastName(String newLastName)
{
this.newLastName = newLastName;
return this;
}
public EmployeeBuilder setNewMiddleName(String newMiddleName)
{
this.newMiddleName = newMiddleName;
return this;
}
public EmployeeBuilder setNewFirstName(String newFirstName)
{
this.newFirstName = newFirstName;
return this;
}
public EmployeeBuilder setNewId(long newId)
{
this.newId = newId;
return this;
}
public EmployeeBuilder setNewBirthYear(int newBirthYear)
{
this.newBirthYear = newBirthYear;
return this;
}
public EmployeeBuilder setNewBirthMonth(int newBirthMonth)
{
this.newBirthMonth = newBirthMonth;
return this;
}
public EmployeeBuilder setNewBirthDate(int newBirthDate)
{
this.newBirthDate = newBirthDate;
return this;
}
public EmployeeBuilder setNewHireYear(int newHireYear)
{
this.newHireYear = newHireYear;
return this;
}
public EmployeeBuilder setNewHireMonth(int newHireMonth)
{
this.newHireMonth = newHireMonth;
return this;
}
public EmployeeBuilder setNewHireDate(int newHireDate)
{
this.newHireDate = newHireDate;
return this;
}
public Employee createEmployee()
{
return new Employee(newLastName, newMiddleName, newFirstName, newId, newBirthYear, newBirthMonth, newBirthDate, newHireYear, newHireMonth, newHireDate);
}
}
As the screen snapshot and code listing above indicate, NetBeans 7.2 generated a builder based on the constructor. This was easily done, but there are a few things I don't like about it as much as the builders I have generated by hand. For the builders I have built by hand, I have chosen to have required attributes be part of the builder's constructor so that they must be supplied (I had expected this to happen for the parameters that I did not check the box for optional on). This is shown in the next code listing, which is an adaptation of the generated code shown above. The only thing changed from above is the builder's constructor. It now takes parameters for the Employee class's required attributes.
Adapted EmployeeBuilder.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dustin.examples;
public class EmployeeBuilder
{
private String newLastName;
private String newMiddleName = null;
private String newFirstName;
private long newId;
private int newBirthYear = 0;
private int newBirthMonth = 0;
private int newBirthDate = 0;
private int newHireYear = 0;
private int newHireMonth = 0;
private int newHireDate = 0;
public EmployeeBuilder(
final String newBldrLastName, final String newBldrFirstName, final String newBldrMiddleName)
{
this.newLastName = newBldrLastName;
this.newFirstName = newBldrFirstName;
this.newMiddleName = newBldrMiddleName;
}
public EmployeeBuilder setNewLastName(String newLastName)
{
this.newLastName = newLastName;
return this;
}
public EmployeeBuilder setNewMiddleName(String newMiddleName)
{
this.newMiddleName = newMiddleName;
return this;
}
public EmployeeBuilder setNewFirstName(String newFirstName)
{
this.newFirstName = newFirstName;
return this;
}
public EmployeeBuilder setNewId(long newId)
{
this.newId = newId;
return this;
}
public EmployeeBuilder setNewBirthYear(int newBirthYear)
{
this.newBirthYear = newBirthYear;
return this;
}
public EmployeeBuilder setNewBirthMonth(int newBirthMonth)
{
this.newBirthMonth = newBirthMonth;
return this;
}
public EmployeeBuilder setNewBirthDate(int newBirthDate)
{
this.newBirthDate = newBirthDate;
return this;
}
public EmployeeBuilder setNewHireYear(int newHireYear)
{
this.newHireYear = newHireYear;
return this;
}
public EmployeeBuilder setNewHireMonth(int newHireMonth)
{
this.newHireMonth = newHireMonth;
return this;
}
public EmployeeBuilder setNewHireDate(int newHireDate)
{
this.newHireDate = newHireDate;
return this;
}
public Employee createEmployee()
{
return new Employee(newLastName, newMiddleName, newFirstName, newId, newBirthYear, newBirthMonth, newBirthDate, newHireYear, newHireMonth, newHireDate);
}
}
The code used to call the adapted builder shown in the last code listing is exemplified in the following code listing. This code listing demonstrates how readable ("fluent" in the more trendy vernacular) the client code is with the builder and demonstrates that the object is never in a partial or inconsistent state.
package dustin.examples;
import java.util.Calendar;
/**
* Example calling adapted employee builder to get an instance of employee.
*
* @author Dustin
*/
public class Main
{
public static void main(final String[] arguments)
{
final Employee employee =
new EmployeeBuilder("Coyote", "Wile", "E.")
.setNewBirthMonth(Calendar.SEPTEMBER)
.setNewBirthDate(17)
.setNewBirthYear(1949)
.createEmployee();
}
}
The most significant drawbacks to the builder implementation are potential performance impacts of extra object instantiation (probably not an issue for most Java applications) and the extra code verbosity.
Although I don't show it here, the other thing I like to do with my builder implementations is to include them as nested classes in the class they build. This is how the code example in the second item of the Second Edition of Effective Java implements it, but I don't see anyway in NetBeans 7.2 to generate the builder as a nested class rather than as a standalone class.

JTT iOS Powered Remote Control Cockroach


JTT iOS Powered Remote Control Cockroach

Guide the cockroach with your iPhone to your sister’s coffee cup and see what will happen. Maybe you will earn terrible scream. Feel not bad? Let’s go on checking JTT iOS powered remote control cockroach.
JTT iOS Powered Remote Control Cockroach

This is a hilarious remote control toy that measures 3 x 1.4 x 1.4 inches and weights 0.8 oz. As we can see from the images, the remote control toy is shaped as an evil little cockroach along with realistic colors and details, but the loathsome “creature” is powered by built-in rechargeable battery instead of bioelectricity. Moreover, using accompanying infrared transmitter and iOS app, you can easily control the little creature via your iPhone, iPod touch or iPad. Apart from that, the RC toy also comes with a USB cable for charging.
JTT iOS Powered Remote Control Cockroach
The JTT iOS powered remote control cockroach is priced at $76 USD. If you’re interested, jump to Japan Trend Shop for more details or check out the following demo video first.

HumanToolz Mobile Stand for the New iPad


HumanToolz Mobile Stand for the New iPad

Want to comfortably enjoy your favorite games, apps, videos on your new iPad? Apparently you need a holder-integrated case or a versatile iPad stand such as the following HumanToolz Mobile Stand.
HumanToolz Mobile Stand for the New iPad

HumanToolz Mobile Stand is a versatile, lightweight iPad stand that only weights 2.5 ounces, and designed for the new iPad. As we can see from the images, the new iPad stand features ultra portable, form-fitting design, and is made of high strength aluminum with gorgeous sliver coating for durability and premium looks. Moreover, the iPad stand supports both portrait and landscape viewing modes along with any desired viewing angle. Apart from that, the iPad stand also protects the four corner and rear cover of your iPad 3, and compatible with Apple Smart Cover.
HumanToolz Mobile Stand for the New iPad
HumanToolz Mobile Stand for the New iPad
HumanToolz Mobile Stand for the New iPad
HumanToolz Mobile Stand for the New iPad
At present, the designers of HumanToolz Mobile Stand is raising fund on Kickstarter. Pledge $65 will let you own the versatile iPad stand. If you’re interested, jump to Kickstarter for more details or check out the following demo video first.

The Android Mini PC and TV Box


The Android Mini PC and TV Box

Apparently this kind of Android powered TV box is getting popular now. If you also want to enjoy your favorite HD videos, exciting mobile games with a large screen, the Android mini PC should be able to meet your requirements.
The Android Mini PC and TV Box

This is an ultra portable Android mini PC and TV box that measures approx 81 x 26 x 14mm and weights 26g. As we can see from the images, the TV adapter features USB drive-like design, and has a HDMI connector in order to connect with your HDTV. The Android powered TV box runs on Google Android 4.0 mobile operating system, and comes with a Cortex A5 1.0GHz processor, 512MB RAM, 8GB internal storage, and the integrated USB port allows you to extend storage via external HHD or USB drive, or connect with other devices such as computer mouse, keyboard and more. Apart from that, built-in WiFi connection lets you access to the Internet for your favorite videos, games and more contents.
The Android mini PC is priced at $58 USD. If you’re interested, jump to Brando online store for more details. Additionally, if you need other options, you might like to check Mini X Android TV box and more via “TV adapter” tag.

Grenade Salt and Pepper Shakers


Grenade Salt and Pepper Shakers

Don’t worry, this isn’t a pair of powerful grenades that can lay waste your house. But if you want to add some seasonings to your food, the grenade salt and pepper shakers will help you.
grenade_salt_and_pepper_shakers_1.jpg

This is a pair of interesting salt and pepper shakers. Each shaker measures 62mm in diameter by 100mm in length, and weights approx 115g. As we can see from the images, each of the salt and pepper shakers is shaped as a realistic grenade, and comes with very nice details. Moreover, the both shakers are made from quality porcelain instead of iron for food safe. Of course, in addition to salt and pepper, you can also put any your favorite seasoning in the special grenade, but we don’t recommend gunpowder and iron fillings.
grenade_salt_and_pepper_shakers_2.jpg
grenade_salt_and_pepper_shakers_3.jpg
The pair of grenade salt and pepper shakers is priced at $16.99 USD. If you’re interested, jump to USBGeek for more details.
grenade_salt_and_pepper_shakers_4.jpg

Tiltpod Mobile Keychain Tripod for iPhone 4 and 4S


Tiltpod Mobile Keychain Tripod for iPhone 4 and 4S

No double, you can easily take photos with your iPhone 4 or 4S. But if you want to shoot steadily or take self portraits, the following Tilt Mobile keychain tripod should be able to meet your requirements.
Tiltpod Mobile Keychain Tripod for iPhone 4 and 4S

Tilt Mobile is a practical, ultra portable ball head tripod designed for iPhone 4 and iPhone 4S. As we can see from the images, the tripod features keychain-sized, go-anywhere design, and comes with a grippy base in order to hold tightly on rough or smooth surface, while the iPhone-safe magnetic ball head mount allows you to smoothly adjust the position of your iPhone at just about any angle for perfect group and self-portrait shots, and the portable tripod supports both portrait and landscape modes. Apart from that, the custom opening lets you attach the tripod to your keychain.
Tiltpod Mobile Keychain Tripod for iPhone 4 and 4S Tiltpod Mobile Keychain Tripod for iPhone 4 and 4S
Tilt Mobile keychain tripod is priced at $15 USD. If you’re interested, jump to Photojojo for more details.
Tiltpod Mobile Keychain Tripod for iPhone 4 and 4S Tiltpod Mobile Keychain Tripod for iPhone 4 and 4S
Additionally, if you need other options, you might like to check Gerber tripod multi-tool and more via “tripod” tag.

Powerbag Deluxe Backpack with Backup Battery

Powerbag Deluxe Backpack with Backup Battery
Of course, you can put a backup battery in your bag for charging, but if you want to more conveniently charge your mobile devices on the go, the Powerbag Deluxe backpack with backup battery may be more suitable for you.

Powerbag Deluxe Backpack with Backup Battery

The Powerbag Deluxe is a versatile backpack that measures 4.5 x 13.5 x 23 inches. As we can see from the images, the backpack features simple and stylish design, and is constructed of nylon material for lightweight and durability. The backpack comes with a large laptop compartment that can hold up to 17-inch laptop, while another compartment measures 8.5 x 10 x 5 inches for your iPad or other tablet, and other pockets are enough to carry various travel essentials including iPhone, camera and more.
Powerbag Deluxe Backpack with Backup Battery
Most importantly, the backpack also features a built-in 6000mAh backup battery, using three built-in connectors including 30-pin connector, micro USB and mini USB, you can easily charge your mobile devices on the go. Apart from that, the backup battery also comes with water-resistant AC adapter charging port, fold-flat AC adapter and integrated one-touch indicator for battery status.
Powerbag Deluxe Backpack with Backup Battery
The Powerbag Deluxe backpack with backup battery is priced at $169.99 USD. If you’re interested, jump toThinkGeek for more details.

Recent Posts