iOS 4.2 out… home runs in all categories…except iPrint

Well, iOS 4.2 is out and got it all installed last night on every device I had. After I was done, even the wife was using Airplay to stream music to the Airport Express with her iPhone and we were both watching This Week in Tech (TWIT) by streaming it from my MacBook to the Apple TV. I know, I could have just cranked up the episode on the Apple TV itself, but this was just a test and it worked flawlessly.

I was thoroughly impressed with all the features that the update had, especially Airplay, but I’ll get right down to what I really was disgusted about. It was no surprise that Airprint was scaled back at the last minute from this release and that being able to print from a shared printer on another computer was not included, but let’s also look at some other limitations.

  • Airprint cannot use a standard printer connected to your Wifi unless it supports Airprint. (HP has the only ones right now)
  • Airprint cannot use a printer attached to Airport Extreme, Airport Express and Time Capsule. Now this makes sense since this is basically an extension of printer sharing, but that doesn’t mean I have to dislike it any less.

It’s seems as if Apple was merely trying to help prop up HP printer sales by releasing Airprint in this fashion. Needless to say, I am not happy about it since my HP printer is only a year old and is wireless on my network and Windows and Mac OS both print to it just fine… iPrint should have been removed from the release until you could support printers attached to Apple hardware at least. Releasing a feature that requires a new printer, well is just a one-off and appears to be a marketing ploy concocted by HP.

Enough with my ranting and I’ll get back to praising the other features. I just can’t say enough about Airplay. This has revolutionized my home experience. Being able to project from one device to another over wifi is just
the pinnacle for me. Before you Windows fanboys and hackers get started, I know that this functionality has been around for a while, but it required me to work too hard. I look at a computer screen all day, I don’t need to go home and stare blindly at another trying to figure these things out. Apple makes this very easy…


Where do we go from here?

Now that the release is out, he is what I want to see happen in the near future.

  • Release iPrint that supports computers attached to other Apple Devices at least and soon.
  • Release a version of Airport Express that has an HDMI output so that I can just hook that up to a TV in another room. (This may not happen as it might limit apple TV sales and of course, for the price of the device, which would probably be $99, you could just buy another $99 Apple TV)
  • I’d like to see a convergence of features in Apple TV, Airport Extreme, Time Capsule, etc. I doubt this will ever happen, but having all the features in a single device would be much better than having multiples plugged in, but there are some factors that would make this difficult, e.g. what would happen to Apple TV viewing when Time Capsule started to run on the same box…it prob couldn’t handle it.

 Overall iOS 4.2 is a spectacular update and other tablet makers are going to struggle even further now. I’ll paraphrase something that Andy Ihnatko said in his blog; this update is going to push the emergence of a competing tablet out six more months. I wonder if Andy knows that Oprah, endorsed iPad as her favorite thing of all time. That could push it out another year or two…

The latest and greatest JUnit features… expand your toolset

Junit has been around for some time and it is still a favorite of mine, well it became my favorite after it moved to annotations instead of having to extend that pesky TestCase class. Modern Junit tests are small concise and extremely handy when it comes to testing your code. Let’s look at some of the latest features that Junit offers and see how they can help you write better code with Test Driven Development paradigm.

Categories

Each test method and test class can be annotated as belonging to a category:

 
public static class SomeUITests {
@Category(UserAvailable.class)
@Test
public void askUserToPressAKey() { }

@Test
public void simulatePressingKey() { }
}

@Category(InternetConnected.class)
public static class InternetTests {
@Test
public void pingServer() { }
}

To run tests in a particular category, you need to set up a test suite. In JUnit 4, a test suite is essentially an empty annotated class. To run only tests in a particular category, you use the @Runwith(Categories.class) annotation, and specify what category you want to run using the @IncludeCategory annotation

 
@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@SuiteClasses( { AccountTest.class, ClientTest.class })
public class LongRunningTestSuite {}

You can also ask JUnit not to run tests in a particular category using the @ExcludeCategory annotation

 
@RunWith(Categories.class)
@ExcludeCategory(SlowTests.class)
@SuiteClasses( { AccountTest.class, ClientTest.class })
public class UnitTestSuite {}

assertThat

Two years ago, Joe Walnes built a new assertion mechanism on top of what was then JMock 1. The method name was assertThat, and the syntax looked like this:

assertThat(x, is(3));
assertThat(x, is(not(4)));
assertThat(responseString, either(containsString("color")).or(containsString("colour")));
assertThat(myList, hasItem("3"));

More generally:

assertThat([value], [matcher statement]);

Advantages of this assertion syntax include:

  • More readable and typeable: this syntax allows you to think in terms of subject, verb, object (assert “x is 3″) rather than assertEquals, which uses verb, object, subject (assert “equals 3 x”)
  • Combinations: any matcher statement s can be negated (not(s)), combined (either(s).or(t)), mapped to a collection (each(s)), or used in custom combinations (afterFiveSeconds(s))
  • Readable failure messages. Compare
    assertTrue(responseString.contains("color") || responseString.contains("colour"));
    // ==> failure message:
    // java.lang.AssertionError:


    assertThat(responseString, anyOf(containsString("color"), containsString("colour")));
    // ==> failure message:
    // java.lang.AssertionError:
    // Expected: (a string containing "color" or a string containing "colour")
    // got: "Please choose a font"
  • Custom Matchers. By implementing the Matcher interface yourself, you can get all of the above benefits for your own custom assertions.
  • For a more thorough description of these points, see Joe Walnes’s original post.

We have decided to include this API directly in JUnit. It’s an extensible and readable syntax, and it enables new features, like assumptions and theories.

Some notes:

  • The old assert methods are never, ever, going away. Developers may continue using the old assertEquals, assertTrue, and so on.
  • The second parameter of an assertThat statement is a Matcher. We include the Matchers we want as static imports, like this:
    import static org.hamcrest.CoreMatchers.is;

    or:

    import static org.hamcrest.CoreMatchers.*;


Assumptions

Ideally, the developer writing a test has control of all of the forces that might cause a test to fail. If this isn’t immediately possible, making dependencies explicit can often improve a design.
For example, if a test fails when run in a different locale than the developer intended, it can be fixed by explicitly passing a locale to the domain code.

However, sometimes this is not desirable or possible.
It’s good to be able to run a test against the code as it is currently written, implicit assumptions and all, or to write a test that exposes a known bug. For these situations, JUnit now includes the ability to express “assumptions”:

import static org.junit.Assume.*

@Test public void filenameIncludesUsername() {
assumeThat(File.separatorChar, is('/'));
assertThat(new User("optimus").configFileName(), is("configfiles/optimus.cfg"));
}

@Test public void correctBehaviorWhenFilenameIsNull() {
assumeTrue(bugFixed("13356")); // bugFixed is not included in JUnit
assertThat(parse(null), is(new NullDocument()));
}


Theories

More flexible and expressive assertions, combined with the ability to state assumptions clearly, lead to a new kind of statement of intent, which is called a “Theory”. A test captures the intended behavior in one particular scenario. A theory captures some aspect of the intended behavior in possibly infinite numbers of potential scenarios. For example:

@RunWith(Theories.class)
public class UserTest {
@DataPoint public static String GOOD_USERNAME = "optimus";
@DataPoint public static String USERNAME_WITH_SLASH = "optimus/prime";

@Theory public void filenameIncludesUsername(String username) {
assumeThat(username, not(containsString("/")));
assertThat(new User(username).configFileName(), containsString(username));
}
}

This makes it clear that the user’s filename should be included in the config file name, only if it doesn’t contain a slash. Another test or theory might define what happens when a username does contain a slash.
UserTest will attempt to run filenameIncludesUsername on every compatible DataPoint defined in the class. If any of the assumptions fail, the data point is silently ignored. If all of the assumptions pass, but an assertion fails, the test fails.

Theories match data points by type, so if you have a theory that take an int as an argument and you have 5 int @Datapoints, your theory will run a total of 5 times. This gets more complicated if you add a second parameter that is a double since you will get every possible permutation ran for the combination of the number of total parameters.

I’d hate to wrap up a discussion about Junit without mentioning TestNG. Both TestNG and Junit are competing testing frameworks but they are not mutually exclusive from one another. I use both in my projects normally since I can take advantage of features one has that the other ones does not. That being said, I usually lean more toward Junit during development since it is the most widely recognized and understood by more people I work with. Both are great testing frameworks so it makes it difficult to pick on over the other so I just don’t.

Telecommuting policy necessary if you want to be competitive

Working from home…it’s a phrase that can be polarizing as any when the discussion comes up in the workplace. For the most part upper management feels like it has been shoved down their throats by a picky, whiny workforce. Middle management and their underlings feel it is a necessary tool that provides an ideal, desirable work environment. I’m going to tell you right out, it is always one of my interview questions and I will refuse to work somewhere that doesn’t allow it.

In the rise of the digital age, when most everyone has high speed internet access at home, telecommuting has become easier than ever to accomplish and be productive. While in the earlier days, it might have been like sucking meatloaf through a straw, the modern experience is real-time and effective.

Working from home or Telecommuting has many advantages for both the employer and the employee. Let’s look at some of them.

For the employer

  • Gives the impression that the employer is progressive and keeping up with the times
  • Retention goes up and turnover does down
  • Makes the employer attractive to other candidates they may not be able to get with salary
  • Promotes a more relaxed employee who is less often to abuse sick days
  • Reduces lost work time due to doctor visits, car repairs and other things that employees take time off to do.
  • It reduces the footprint of the employee around the office. Office supplies, network bandwidth, water, toilet paper, coffee (For the progressive employers that still pay for it) and things that employees consume on a daily basis are being consumed out of the employee’s own pocket
  • A coup for employers who want to claim a green initiative. The savings on the environment due to decreased emissions are staggering just from one day a week of telecommuting alone. Here are some facts from a 2008 article published on Treehugger.com.
    • “In a poll of 1,500 technology workers, 37 percent said they would accept a salary cut [of up to 10%] if they could work from home, according to Dice Holdings.”

      Telecommuting Could Save Billions of Gallons of Gasoline
      According to Telework Exchange, “white-collar employees who feel they could do their jobs from home began to telework twice a week, the United States could conserve 9.7 billion gallons of gasoline and save $38.2 billion a year.” These calculations are based on 50 miles roundtrips in vehicles getting 24 miles per gallon, with gasoline at $3.94/gallon.

  • When you can’t afford to provide a pay raise for employees and you are looking at high turnover, use a telecommuting policy as leverage. You can bet the retention numbers will be higher.
  • Relocation isn’t necessary for a candidate you want to hire badly. You might find the perfect candidate for your IT staff, but they live 5 hours away so you let them Telecommute so you can get them hired.Another one is that some people often work an hour or better from their job so telecommute gives these people back a little over 2 hours a day that they don’t have to sit in traffic. Can anyone say…reduced road rage. You folks in Atlanta or Washington D.C. know what I’m talking about.

For the employee

  • The employee feels like his employer cares and is being progressive.
  • The employee is less stressed e.g. no dress code, noone over their shoulder
  • Often the employee is more productive because there are fewer distractions
  • Employees save money from the cost of fuel and car maintenance
  • Employees can save vacation time because of the reduced stress
  • You can work later in life and make it to those retirement ages

I have meet very few people in my career who oppose telecommuting, but there are some out there. Let’s look at some of the excuses I have heard and I’ll address why they aren’t valid.

From employers

  • Employees goof off at home - Work is and should be a meritocracy. You perform poorly, you get fired. Revoke the privileges of the goof off or fire them. They are just as likely to goof off at work. Telecommuting is a privilege, not a right.
  • If I give it to one, I have to grant it for another – This isn’t true. Telecommuting policies are for eligible folks. Janitors, Security and people whose interactions compel them to be in the office wouldn’t be eligible for telecommuting. Use some common sense people.
  • If you can’t be productive at work, I need to address why and correct it.  – This excuse came from a blithering idiot at Franklin American Mortage in Nashville, TN who promoted a work environment with a shirt and tie Mon-Thurs but you can relax and wear a gold shirt on Fri. They worked strict 8-5 and often worked until 8 – 12 PM on Thursdays and no flex time. Working in this environment would make anyone not want to come to work.

For employees

  • I can’t concentrate at home. I have 3 kids driving me crazy. I just can’t be productive – Telecommuting may not be a good choice for you. Just come into work and stop ruining for the other folks who can be productive.
  • My wife is always wanting me to do something at home - I’ve heard this one a lot. Again Telecommuting may not be a good choice for you.
  • My coworkers don’t do a thing when they work from home - This usually comes from the same person who voiced the first excuse. It’s rarely true and if it was,the manager will pick up on it and clean house eventually.
  • I like to get out of the house – This is why telecommuting isn’t a 5 day a week thing. You need the social interaction.

Telecommuting policies vary, but the most common I have seen over the past few years is a one day a week up to the employee’s choice and it kinda floats. This is great since you may have responsibilities all through the week that require office face time so you can choose a day that you can be isolated to telecommute. Another one is for an employee to pick a day and stick to that day. This doesn’t work out so well as it can conflict with office responsibilities, which is why I lean toward the floating day.

Granted that working from home is efficient and benefits everyone, there are some guidelines that the employee needs to follow.

  • Be accessible – Send an email letting your immediate team member know you are WFH for the day and include your cell number.
  • Use some type of instant messenger and monitor your email more vigilant than you would do in the office. Set your status if you step away.
  • Use Google Voice or a Magic Jack to attend meetings if you are concerned about your phone usage
  • Be available during the core hours that you might be needed. 9-11 and 1-4 and times you want to try to be in front of your computer. Don’t be the idiot who sleeps until 10 and doesn’t log into your computer until 11 or later. Manager’s are reluctant to punish an individual for this behavior. More often they punish the group instead of the offending slacker.
  • Defend the practice and set an example. Don’t be the poster boy for the idiot who says everyone who works at home goofs off.

 The landscape of the world at work is changing. In the past 8 years, every job/contract I have taken instituted a telecommuting policy with great success. At one particular banking company, it saved the IT organization from a large fallout during an acquisition and at another healthcare company it also managed to save them in a lean time where they weren’t able to provide bonuses.

The fact remains that work is a meritocracy; you are rewarded for being productive. It brings to mind the old saying from a Star Trek movie, “Work well…and you will be treated well, work poorly and you will be shot.” Managers have to be competent enough to know and trust in the ability of their people. If a manager can’t trust his people, that says something about the manager. It says that either the manager has made some poor choices in the hiring process or hasn’t culled his herd of the bad sheep. It also says that maybe a manager needs to look at himself/herself to access their skills as a leader.

Stop using XML files with Spring Hibernate already

Hibernate has had annotations available for configuration for several years now and Spring hasn’t been too far behind it. I think the last time I actually used a hibernate mapping or hbm file was back in 2006 or so and as far as Spring goes, I still use the XML but only for classes I don’t control myself or when I need to do something like inject values into something that an annotation wouldn’t support.

Annotations simplify your coding, make it self documenting and they provide compile-time checking. Annotations also add some flexibility over the XML configuration as well. I can’t tell you how many people I see who are just starting to use Hibernate or Spring and they just do everything with XML files and then they complain when they have to refactor and have to edit the XML or they complain because they have all this XML to manage.

Another complaint I hear is that some developers say they don’t want to make their model depend on Hibernate or the Java Validation Framework. The answer to that is that you will only have to depend on having the runtime annotations on the classpath. Annotations cause no problems in code that isn’t looking for them. I have annotated a domain model before with Hibernate and Java Validator Framework and passed it around in the enterprise with no problem. The callers code was only using the classes as a POJO and not using the Hibernate functionality…with no performance impact at all.

Remember:  Annotations are only useful in code that is explicitly looking for them!

Also, if you are that concerned with the non-existent problem, just create interfaces and have your annotated classes extend your interfaces. I have done this before…although it leads to fragmentation of validation code. One developer would implement the concrete classes one way using Hibernate and the other would implement it totally different. Centralized validation was one reason the JSR was created for the Java Validation Framework.

Guidelines for when to use Annotations vs. XML

  • Use Annotations - when you control the code that you are annotating

          e.g. You create a domain model and markup with Hibernate annotations and Java Validation Framework and you create a DOA and Service layer to interact with your model.

  • Use XML - when you don’t have direct control over the code you need to use in Spring or Hibernate or when you need something that the XML version provides that the annotated model does not. (This was true in earlier versions of Hibernate, but this is not the case anymore. Hibernate Annotations are quite robust as of present). You should also use XML if you plan on injecting values that an annotation wouldn’t normally support. Remember that the value of an annotation attribute cannot be modified at runtime so it must be static, so in this case, XML is ideal.

e.g. You need to create an instance of the Hibernate SessionFactory via Spring and inject a configuration

Just embrace the annotations or the rest of us who have and stop whining or we will hunt you down and make you do something like lick a toilet seat…

I won’t even go into the folks who are using Junit, DBUnit, Unitils, etc sans annotations.

Java: It is most certainly pass by value

I am surprised after all these years that this debate still happens between even seasoned Java developers. It isn’t really their fault though. Java made it a little confusing. If you want something more detailed, then you should read the following link.

I’m going to give you a quick overview that is not as detailed. Let’s start with a rule.

Java is pass by value regardless whether you are dealing with an object or a primitive

Everyone who writes java understands that when a method is called and a primitive is passed in, you get a copy of that variable and not the original. It is when passing an object that people get confused. The short of it is that the variable passed in is a cheap referenced copy of the original, but not really a pointer like in other languages like C++.

When you pass in an object, you can manipulate the values of elements of the object, but you cannot reassign the object to a new instance of that object because once you do, the link back to the object is completely broken. So if you call modifyIt(myClass) and in the method, you say myClass.someValue = ‘test’ and directly after the method call, the value of the original will be reflected by your change, but if you attempt to do this and reassign myClass to another object, your reference is lost.

Here is a class that illustrates the examples with some comments to help you along.

public class TestString {

private static void modifyIt(String modified) {

modified = "New String"; //This doesn't have any effect on the original

}

private static void modifyIt(int modified) {

modified = 2; //This doesn't have any effect on the original

}

private static void modifyIt(MyClass clazz) {

clazz.myValue = "new Value"; //This will work
clazz.intValue = 2; //this will work

clazz = new MyClass(); //Things will go south here.

clazz.myValue = "This value"; //you are throwing a toothpick in a volcano
clazz.intValue = 56; //Urinating in the wind

}

public static void main(String[] args) {

String value = "Original Value";
modifyIt(value);
// Prints only original value
System.out.println(value);

MyClass clazz = new MyClass();
modifyIt(clazz); //This method call has problems


System.out.println(clazz.myValue);
System.out.println(clazz.intValue);

int intValue = 1;

modifyIt(intValue);

// Only prints original value
System.out.println(intValue);

}
}

class MyClass {

public String myValue = "Original Value";
public int intValue = 1;

}





My personal preference is to always avoid even the remote possibility that these circumstances can even happen. You can do this by always returning the element in question from the method you are calling.

private static MyClass modifyIt2(MyClass clazz) {

clazz = new MyClass(); //Things will go south here. If Java was
//pass by reference, this would work
//but it is pass by value

clazz.myValue = "This value"; //you are throwing a toothpick in a volcano
clazz.intValue = 56; //Urinating in the wind

return clazz;

}

...

myClazz = modifyIt2(myClazz);

If you make an assignment back to your variables from the return of a method in all cases, this eliminates any question as to what object you have. This is also more object oriented and leans away from the function paradigm to a method paradigm.

The biggest thing I want everyone to take away from reading this is that Java is pass by value and not pass by reference, it is not even a mix.

Yet Another Expression Language… Spring EL

Most of the time when I hear that the term expression language I cringe, after all, we have seen so many…JSTL, JSFEL, etc and some others that will remain nameless. When I heard Spring was adding an expression language to Spring 3, I was a big dissappointed, but really I was sort of already using it and didn’t even know it with Spring Security to define my roles and accessbility rules. So I got over my dread and I took a dive into Spring EL to see how it could help make my code better.

Right off the bat, I can tell you that Spring EL will save you some coding. It gives you the ability to dynamically assign values to elements at runtime so that you aren’t stuck with a constant that you have to replace later and you won’t have to write a custom strategy class to manipulate values upon certain conditions.

Let’s look at an example I pulled straight from the Spring documentation.

...
public class MovieRecommender {

private String defaultLocale;

private CustomerPreferenceDao customerPreferenceDao;

@Autowired
public MovieRecommender(CustomerPreferenceDao customerPreferenceDao,
@Value("#{systemProperties['user.country']}"}

String defaultLocale) {
this.customerPreferenceDao = customerPreferenceDao;
this.defaultLocale = defaultLocale;
}

// ...
}
...

If you know anything about me, it’s that I embraced convention-based configuration and I intend to largely ignore the old XML style of defining beans. In this example, we see that the value of the user’s country is injected into the defaultLocale when the method is called.

...
@PreAuthorize("hasRole('ROLE_USER')")
public void create(Contact contact);
...

This is an example I have used before. Using Spring Security, you can define what permissions a user much have to access certain urls in your application or secure a method. 


You can pretty much use Spring EL anywhere you would have normally put a literal in an XML file, annotation value and you can even evaluate expression directly in code. If you literally want a literal just enclose your value in single ticks like ‘Hello World’.

...
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("put your expression here");
...
If you're not in a context where expressions are directly supported, you need to define your expressions 
using the JSF style #{} to get Spring to understand that you don't want a literal. 

Here is another useful example you might want to emulate. 

The calculation of the random number injected into NumberGuess is done at runtime by the expression. Normally, I would have done this by declaring another Spring Bean that is an instance of a generator and just injected that into the other class and have a method that calls the generation, but this is just much simpler.

One of my favorite points, is that you can use the Elvis operator to shorten the ternary operator syntax and not have to repeat a variable. It saves typing and since it already exists in Groovy, most will be familiar with it.

...

ExpressionParser parser = new SpelExpressionParser();
String name = parser.parseExpression("null?:'Unknown'").getValue(String.class);

...

As with anything resembling scripting or an expression language, I recommend that you use this feature sparingly. Don’t go off and litter your code with it. As a general rule of thumb, use this as a last resort for the specific circumstance where it just seems to be begging for it.

Check out the reference documentation and see how this powerful feature can help you in your coding.