Connect Internet Through Your iPhone 3G

May 18th, 2009

Couple weeks ago, I was waiting in the hospital line and luckily I had my MBP with me. I turned it on and tried Internet connection, but no luck. There was no free wireless access anywhere close :( Then I tried to connect through my iPhone 3G. This time I was lucky, it just worked. Here is how I did:

// 1. Create an Ad-HOC wireless network over Airport
// 2. Connect iPhone to this network
// 3. ssh to iPhone using following snippet

ssh -ND 9999 root@IP_ADDRESS

// 4. set your browsers socks proxy to localhost:9999
// Done.

Unfortunately this only works for a Jailbroken iPhone. Anyways, it saved my boring time in that line. Hope it helps to you too.

Tips

4 Comments

How to Avoid NullPointerExceptions (NPE)?

May 4th, 2009

I’m sure every Java developer has had some hard times with NPEs (NullPointerException) since Java doesn’t really have a nice mechanism to avoid them :) Let’s recall something here: NPE is a run time exception and it occurs in the run time, therefore it means it is a design mistake, bad code quality or careless programming. Anyways, whatever the reason is, we all see NPEs all over our codes :) In this post, I want to cover this issue and give some tips from my experience so far.

Why NPE?

And from Java spec perspective, I don’t know why they never came up with something nice so far. And I hate it, ‘coz Java spec doesn’t contain anything for this. Luckily there are some proposals for Java 7 like @NotNull and @Nullable annotations and ? syntax.

How to Avoid?

Avoiding NPE for a legacy code is very challenging since legacy code doesn’t contain any Unit Tests that covers it. For an on-going development, I’ll try to explain some best practices. If it is applicable for your code-base, just try it. You won’t regret :) A quick side note: all these are my experiences so far and it might not be applicable for all scenarios. However, I’m sure you’ll find a likely approach for your code base.

Here is my agenda for this post:

  1. @NotNull and @Nullable annotations from IntelliJ,
  2. A friend of Java developers: assertions,
  3. Factory Pattern,
  4. Accurate Exception Handling
  5. Common Practices
  6. Unit Testing
  7. Aspect Oriented Programming
  8. Null Object Pattern

@NotNull and @Nullable Annotations

I love IntelliJ. I think, it’s the best Java IDE in the market. It has a little cost, but believe me it is worth it. You can argue about this, but before trying the IntelliJ for yourself, your arguments will be just irrelevant for me :) Anyway, let’s get back to topic :)

@NotNull and @Nullable are life-saver annotations and designed to help you watch contracts throughout method hierarchy. Consequently this will avoid emergence of NPEs. With these tiny annotations, you can save a lot of time. Let’s look at the usage of these annotations:

@Nullable
private String getDefinition() {
   // ...
}

public void doSomething() {
   if (getDefinition().equals("DEFINITION")) {
      // ...
   }

   // ...
}

When you try to invoke a @Nullable method (in this case it’s getDefinition), you’ll receive a warning that says: “getDefinition may product NPE”. Now you know that you have to check for NPE. Isn’t that nice? Now let’s look at the @NotNull annotation’s usage:

private User findUser(@NotNull final String id) {
   // ...
}

public void doSomething() {
   // try invoking with null parameter
   User user = findUser(null);

   // ...
}

If you try to invoke the findUser method with @NotNull, you’ll receive a warning that says: “Passing ‘null’ argument to a method annotated @NotNull”. By using these annotations, it’s almost impossible to receive an NPE from your code base (I ignored the 3rd party tools).

As you see, these are really nice annotations. However, the bad news is that they’re not really friendly if you’re not using IntelliJ. For more information about these annotations, please look at the how-to documentation.

So what are other options to avoid NPEs? Just continue reading.. :)

Java Assertions

Java introduced assert keyword with Java 1.4, but the interesting thing about them is no one is really using it or they don’t even know what it is. I think we’re giving up a very nice feature by not using them. So what is this assertion thing?

An assertion is a statement that enables you to test your assumptions about your code. For example, if you write a method that returns the quantity of products in the system, you might assert that the returning quantity should be greater than or equal to 0. Basic usage of assertions would be:

assert <Expression>; // or another usage is
assert <Expression1> : <Expression2>;

For more information about assertions, please look at the Sun’s assertion guide.

So far it’s okay, but how are we gonna use it to avoid NPEs? Very simple. There are two ways to use assertions in your code base:

First, direct usage. Please check the following code:

public void getUserDetails(final User user) {
   // make sure that user is not null

   assert (user != null) : "User cannot be null";
}

Second way of using assertions is creating an Assert utility class as in Spring. You can put various assertions into this utility class for your project like isEmpty(), isValidCountryCode(), etc.

public void doSomethingWithUser(final User user) {
   // make sure that user is not null

   Assert.notNull(user, "User cannot be null");
   Assert.hasLength(user.getLastName(), "User must have a last name");

   // etc..
}

I want to highlight one thing here. Assertions should be available only in the development process, and not in the production environment. And one more thing, you shouldn’t use any business logic with the assert keyword. Otherwise when assertions are gone after development, your code doesn’t work.

Factory Pattern

Factory Pattern is a design pattern that is used to create concrete objects. The idea is preventing developers to have their own object creation and initialization (I10N) code within various part of the project. By using factory pattern, you would have a centralized object creation and initialization, and you would prevent mis-initialization problems. For more information about the pattern, please check Gang of Four’s official design patterns page.

Now let’s look at how to use this method to avoid NPEs. Please look at the following example:

public void doSomething() {
   // ...

   myPrettyService.save(dummyObject);
}

At first look, it seems like there is no problem in the code. However, careful eyes can catch that myPrettyService might not be initialized at all. This is one common problem of using services/DAOs or any external provider’s instance. Yes it might be null. To prevent this, people tend to create a Singleton of these services. We all know that Singletons are evil in most cases (there are exceptions). To avoid NPE and Singleton together, factory pattern saves us :) Please check the following code:

public void doSomething() {
   // ...

   ServiceFactory.getMyPrettyService().save(dummyObject);
}

I’ll post another article about Singleton and Factory patterns later on. For now, just imagine that ServiceFactory returns only a single instance of our service every time we invoke it (a little singleton hint is by using reflection and making service’s constructor private).

Accurate Exception Handling

One common mistake is not throwing exceptions. I think the reason is that people find try-catch blocks ugly. However, they’re also life-savers, especially pin-pointing the problematic areas in your code-base. Right now, probably you’re thinking what’s the relation between avoiding NPEs and throwing exceptions. Let me tell you why accurate exception handling is important. First, look at the following code snippet:

public User findByGuid(final String guid) {
   // ...

   Result result = executeNamedQuery(FIND_BY_GUID);

   if (!result.isEmpty()) { // EDIT from comments
      return result.get(0);
   }

   return null;
}

As you see, our guy is trying to reach the User by querying the database and returning the result, if there is any, otherwise it returns null. You see this kind of code everywhere, maybe even you’re coding just like this. Maybe you think nothing is wrong with this code. Let me tell what is wrong with this code snippet. Since this method is public, anyone can invoke it. People who use this method might forget to null check for the result, especially if our guy is not a good documenter :S (java developers tend to forget JavaDocs I don’t know why :P). As in following code:

public void doSomething() {
   // ...

   User user = service.findByGuid("XYZ");
   String licenseNumber = user.getLicenseCode().getEncryptedLicenseNumber();

   // ...
}

Unfortunately, this usage seems perfect, but it throws NPE at run-time :( And then you would try to understand what’s wrong with your code. After finding that this user is null, like most developers you tend to place a quick & dirty fix as below:

public void doSomething() {
   // ...

   User user = service.findByGuid("XYZ");
   
   if (user != null) {
      String licenseNumber = user.getLicenseCode().getEncryptedLicenseNumber();
   }

   // ...
}

I guess now we’re on the same page. If this guy would have thrown an exception instead of returning null, you would never end up with an NPE. Instead of throwing an accurate exception, now you’re struggling with an NPE. From this point, I’m leaving it to your considerations:

public User findByGuid(final String guid) throws UserNotFoundException {
   // ...

   Result result = executeNamedQuery(FIND_BY_GUID);

   if (result.isEmpty()) {
      return result.get(0);
   }

   throw UserNotFoundException("No user found with guid: %1$s", guid); // or any ServiceException you like..
}

Common Practices

This part contains some common patterns/practices for your NPE safety. I’ll give some bad code samples and correct them. Please compare each code snippets to have good understanding of why it is a common practice.

1. NPE on String

Don’t compare Strings like below:

public void doSomething() {
   // ...

   if (name.equals("BAD")) {
      // do something
   }

   // ...
}

instead do like this:

public void doSomething() {
   // ...

   if ("BAD".equals(name)) {
      // do something
   }

   // ...
}

2. Empty Collections

Don’t return null from your service methods like below:

public List<User> getUsers() {
   // ...

   Result result = executeNamedQuery(GET_ALL_USERS);

   if (result.isEmpty()) {
      return result;
   }

   return null;
}

instead do like this:

public List<User> getUsers() {
   // ...

   Result result = executeNamedQuery(GET_ALL_USERS);

   if (result.isEmpty()) {
      return result;
   }

   return Collections.EMPTY_LIST; // or EMPTY_SET or EMPTY_MAP, etc. Depending on your return type
}

3. Too Many Dot Syntax

If your object is not a builder object, don’t use too many dot syntax in your code like below:

public void doSomething() {
   // ...

   user.getCountry().findStateByCode("BC").getPopulation();

   // ...
}

instead do like this:

public void doSomething() {
   // ...

   Number population = getStatePopulationFromUser(user);

   // ...
}

private Number getStatePopulationFromUser(final User user) {
   Country country = user.getCountry();
   State state = country.findStateByCode("BC");

   return state.getPopulation();
}

4. Use contains(), containsKey(), containsValue()

Try to use collection’s contains(), containsKey() and containsValue() methods. Don’t do like this:

public void doSomething() {
   // ...

   TaxCode taxCodeForTurkey = taxCodeMap.get("Turkey");

   // ...
}

instead do like this:

public void doSomething() {
   // ...

   if (taxCodeMap.containsKey("Turkey")) {
      TaxCode taxCodeForTurkey = taxCodeMap.get("Turkey");
   }

   // ...
}

Unit Testing

This should be a default action for an agile developer. If you discover an NPE in your code, please update your Unit Tests. And of course before having this problem, make sure that your Unit is already covered for NPEs :P

Aspect Oriented Programming

This is a really big topic. So I’ll cut it short. Try to look at Aspect Oriented Programming. By using AOP, you might have some neat way of handling NPEs (by inserting if (object == null ) { handleNull(); } kinda logic into your bytecode).

Null Object Pattern

Martin Fowler’s Refactoring book covers this topic very nice. However I find it very un-practical. Then again, it’s wise to have a quick look on this pattern. The basic idea of pattern is creating a Null version of your possible error-prone objects.

That’s it folks. I’m sure you guys have your own experiences about NPEs too. Please help me to grow this post by sending your comments.

Java

17 Comments

Tips For Better Tests – Part 2

May 2nd, 2009

In the last post, I tried to roughly touch Unit Tests and what/how many and when to test our Units. For more information about that topic, please go back to first article.

In this article, I want to summarize Agile Testing. I’ll try to cover why we test, why we automate our tests, life-cycle of agile testing process, what kind of tests are available in an agile environment, open sources tools available in the market, etc.

Why We Test

A quick highlight would be; we would like to ensure that the product/project satisfies all the Use Cases and User Stories. On top of that having tests gives you more confidence in your product’s abilities and teaches you about the behavior of your product. This also helps the new developers to learn product faster.

Delivering a quality product/project to your customer is a key for all companies. To reach this target, tests are very important. If you manage to cover your project with tests, your product quality will increase. Who doesn’t want to have quality code :P (I know there are a lot of market guys around). And if you don’t want your code to be a legacy code, you better cover it with tests. Michael C. Feathers has an awesome quote in his book “Working with Legacy Code”:

Legacy code is code without tests!  

Why We Need Automated Tests

Very simple. Because human is error-prone by nature. And also automating your tests will save your time by removing repetitive tasks.

Automated tests consume minimal resources on any hardware. They can be run frequently and highly effective with CI (Continuous Integration) tools.

Life-cycle of Agile Tests

Testing is a continuous action. From the first day of project to the release day, you’re supposed to test your code continuously. If you don’t do testing against your code, you’ll most likely give your customer a crappy software. There are so many examples of this case. Lots of software/IT projects are failing just because of this reason.

We’re OK up to here I believe. So the main question here would be; when and how to test? Well, this part might depend from project to project, but so far below life-cycle worked for me:

  • Unit Testing, you do unit testing while you develop the code. The purpose of the test is to cover your code-base with the maximum possible coverage.
  • Integration Testing, you do integration testing while and after you develop your code. The purpose of the test is to ensure that your system modules can interact with each other without any problems. We don’t write millions of tests in this stage, we only do for fragile and error-prone parts of interactions. However, if you find new fragile parts, you do add it to your integration tests.
  • Functional Testing, you don’t do functional testing if you are not following BDD (Behavior Driven Design) practices. QA (Quality & Assurance) does this after code completion. However, if you follow BDD practices, then you do functional testing while developing the code. The purpose of this test is to ensure that functional behaviors of your system are as they expected. Unit tests and integration tests are for internal system behaviors, and from business perspective, they don’t have any value. They only have values for developers. On contrast, functional tests have business values since they’re external system behaviors. And in any refactoring (refactoring is an internal activity), external behaviors should remain same. So having functional tests are very crucial.
  • Load Testing, you don’t do load testing. QA and/or PG (Performance Group) do this test. The purpose of this test is to find out the system behavior under a big load (concurrent users/concurrent web service clients, etc).
  • Performance Testing, you don’t do performance testing as well. QA and/or PG (Performance Group) do this test. The purpose of this test is to optimize/fix/detect the system performance, memory leaks, etc.
  • Acceptance Testing, neither you nor QA do acceptance testing. Your customer does acceptance testing after QA releases the product (this release is not supposed to be final product, it happens every iteration).

Let’s try to list the characteristic of each test:

Unit Testing

  1. Done by developers
  2. Generally written before code itself. And updated every time you add a new functionality to your unit. Unit tests are also iterative and continuous till you finalize your unit.
  3. For successful unit testing, your code must also be designed for testing. Please refer SOLID Principles by Robert C. Martin.
  4. Code shouldn’t be checked in without unit tests pass
  5. CI (Continuous Integration) tools should run them with every build and before code check-ins.

Integration Testing

  1. Ideally done by both developers and QA group (separately).
  2. Involves at least 2 units or more.
  3. Focus is on interaction of units.
  4. Typically touches on DB, IO, remote services etc.

Functional Testing

  1. Generally done by QA.
  2. If you’re following BDD practices, stories prepared by QA and fixtures coded by developers.
  3. Focus is on system functions.
  4. Contains E2E (End to End) flow of a certain functionality (i.e adding a product to the shopping cart, or searching a keyword in the system)
  5. Generally for each story-card you’ll have at least one functional test.

Load & Performance Testing

  1. Done by QA and/or PG.
  2. Focus on system behavior under big load and detecting performance and memory problems.
  3. Generally done by using 3rd party tools.
  4. Timing and measuring system resources while executing E2E stories is key to find out problematic areas.

Acceptance Testing

  1. Done by customer after each iteration.
  2. A story isn’t complete until all acceptance tests pass.
  3. Focus is on customer/product owner to verify the correctness of acceptance tests.
  4. Automation of these tests is strongly desired.

Open Source Tools

There are many many tools in the open source world. And every new day brings new ones. At this point, selecting/finding the best tools available is very crucial for the development process. I’ll try to list some tools that I find useful from my personal experience:

Unit Tests & Integration Tests

JUnit and TestNG are the market leader in Java world. I personally like TestNG more than JUnit, but JUnit has more community support. Both has support for Java 5+, annotations and framework integrations. Both are supported by many IDEs and build tools. You can pick whichever you like. For database related test, I personally like DbUnit a lot. I find it very useful to populate initial data for each test. For mocking (I’ll try to cover mocking on a separate article) my personal favorite is Mockito, but alternatives; JMock and EasyMock are good too. There are many many others like XMLUnit, HttpUnit, SoapUI, Cactus, etc. These are my favorites. You can use any tool you like as long as you’re comfortable.

Functional Tests

For web-based applications Selenium is my personal favorite. A nice alternative is Canoo WebTest. For Swing/JFC based applications Marathon, Abbot and jfcUnit are worth to look at it.

If you’re following BDD practices, Concordion, easyb and FitNesse are really great tools. I’ve been looking at Concordion for the last couple days and I find it extremely useful since there is no great alternative. It’s JUnit based and learning curve is just 1-2 days. I’ll post another article about it soon.

Load & Performance Tests

TestNG itself has built-in annotations for concurrent requests. For more information please refer it’s official site. From JUnit perspective, JUnitPerf is doing a lot good. And JMeter and The Grinder are really nice tool for server, web service load testing.

Acceptance Tests

Since your customers are going to test this part, I don’t want to give open source tool list here. Generally there are pretty good paid projects that do awesome job. If you want to direct your customer on this point, Concordion, easyb and FitNesse can do some good.

That’s it folks! Till next time have fun..

TDD

No Comments