Tuesday, September 14, 2010

Cleaner Code with One Simple Technique


Clean code bookWhat is the simplest technique you can apply to write cleaner code? Clean Code by Robert C. Martin is a very good book that focuses exclusively on writing cleaner code. I read this book several months ago and at a recent code review I was again reminded of the value of this simple technique. The simplest technique to apply for writing cleaner code is to keep functions small!



Advantages of Small Functions

  • Functions perform one specific responsibility (single responsibility principle)
  • Functions become very readable
  • Functions are more likely to descend only one level of abstraction (tip G34 from Bob's book)
  • Small functions promote reusability and help eliminate duplication
  • Your favorite IDE makes extract method so simple
  • Small functions adhere to these valuable coding principles by design


Ideal Function Size

"Continue to extract methods until you can not extract methods anymore. Extract until you drop!" This is Bob's recommendation from his online presentation of Bad Code and Craftsmanship. Personally, I couldn't agree more. For the past three months I have been following this practice and this simple technique has a high return on investment.



Additional Clean Code Tips

Looking for additional clean code tips? Chapter 17 (Smells and Heuristics) in Bob's book is a very quick read and covers sixty-six valuable coding practices. Alternatively, Bob discusses many clean code practices in his online presentation. In fact, he leads off the discussion by focusing on the importance of small functions!

Tuesday, August 31, 2010

Objective-C for Java Developers

objective c book

I actually won Learn Objective-C for Java Developers at the last Twin Cities Java User group meeting. The only stipulation for winning a free book is the expectation that we publish a review of the book online. This is a small task for a free book. Learning Objective-C has been on my todo list for several months anyway. Winning this book simply moved it higher on my priority list.


Review:

4 star rating

Pros:

  • Many of the Objective-C examples were also shown with their Java counterpart. This added value in two regards. First, it clarified what the example was really doing. I could simply reference the Java version and quickly understand the Objective-C code. Secondly, it allowed me to compare and contrast the two languages. In many cases (but not all) the Objective-C examples contained fewer lines of code.

  • In addition to the Java and Objective-C examples, the book also had many table-based comparisons for common features (data types, methods). For example, one page listed the Java data types and their Objective-C alternative including their size and range restrictions. Again this helped simplify the learning curve. The table-based charts were also used for common method declarations too. For example, the common String utility methods were shown side-by-side. One column showing Java's String utility method declarations and the other column showing the Objective-C alternative.

  • Most code examples were a page or less. This helped simplify the learning process by allowing me to focus on more isolated code fragments.

Cons:

  • Many books that teach a new programming language typically include exercises at the end of each chapter that the reader can take away and complete. This book did not have any. This is a minor complaint. I can definitely think of sample programs to write...

  • The index does not always serve as a good reference for finding things quickly. For example, I wanted to find more information about logging and "logging" or "NSLog" were not in the index. Need to find the for loop quickly? You will not find it in the index. It is actually found in the index under "Collections, iterating through". The index could have been structured slightly better for quick search keywords.

  • An Objective-C quick reference guide would have been helpful. This did not bother me too much because about the time I started reading this book DZone released a new Objective-C reference guide. I highly recommend it! In my previous "con" I mentioned that it can be painful to find certain topics (logging, data types, loops) quickly within the index. The DZone refcard provides quick access to those topics and more!

Summary

Overall this book is a very valuable resource for Java developers that want to learn the Objective-C language. The author greatly simplifies the Objective-C learning curve by contrasting many features and examples to its Java equivalent.

Saturday, July 31, 2010

Mobile Web Toolkit



mobile phoneMobile Web development requires a more abundant set of developer tools than its desktop counterpart. XHTML MP, Wireless CSS, and Mobile JavaScript are all more refined subsets compared to their desktop predecessors. In addition, the Mobile Web offers many new challenges. In particular, device fragmentation and browser inconsistencies will always wreak havoc within this ecosystem. Great tools can help overcome these challenges. Here are a few:


Validating Mobile Sites

How valid is your Mobile Web Site? Find out with these awesome validators. These validators will grade and offer best practice solutions to achieve a more compliant Mobile site. These are also valuable tools for a code review!

Mobile Web Best Practices

Both validators above evaluate mobile sites based upon standards and best practices. Their best practice and standards documentation can be found here:

Device Databases

Device databases simplify device detection. This helps facilitate content adaptation for specific device groupings (smartphones, featurephones, screen size, OS, JavaScript/AJAX support, is wireless, is touchscreen, etc.). For example, Bank of America and Amazon tailor content based on several of these groupings.

XHTML Mobile Profile

XHTML MP is the standard markup language for the Mobile Web. Unlike HTML and XHTML, XHTML-MP is featurephone compatible, it is less likely to be transcoded for optimization, and it supports the mobile-optimized Wireless CSS and Mobile JavaScript features. For additional XHTML MP 1.2 features refer to OMA's specification document.


Firefox Add-ons

The following Firefox add-ons are very powerful tools for testing and developing:

Device Testing Solutions

The ideal testing solution is to test on the physical device. Two virtual device testing solutions exist:

JavaScript & AJAX Compatibility

When device testing is not always feasible, the compatibility tables generated by Peter-Paul Koch are a good alternative. If you need assistance identifying JavaScript compatibility across browsers or devices these tables can definitely help:


CSS Compatibility

If you need assistance identifying CSS compatibility across browsers or devices these tables exit too:

Web Widgets

Web Widgets will allow Mobile Web developers to take advantage of native phone features. The subset is limited but it is a start: Device APIs and Policy Working Group


Book Resources

Wednesday, June 30, 2010

Restful Link Integrity

lockHow do you secure sensitive information within your URIs? Many of the RESTful examples I have seen expose sensitive information within their links. Often this sensitive data is the identifying key of the entity that is being managed. RESTful Web Services Cookbook briefly discussed two solutions for securing sensitive information within URI's (refer to chapter 12 for details). I will expand upon these two solutions by demonstrating how we can leverage the Jasypt encryption framework to preserve sensitive information.

Initially, we must validate our URI templates do not expose sensitive data. If they do not, there are no concerns. However, if your URI templates expose sensitive data we must preserve their integrity and confidentiality. An example of an insecure URI template may look like:

http://rest.com/account/{account_id}.

If this URI template exposes a clear text account ID we have a security gap. If a security gap exists, we must implement a solution to preserve the integrity and confidentiality of the insecure URIs. Three solutions exist to secure RESTful links:

Hashing

Hashing is an ideal solution if you need to expose data parameters in clear text and want to preserve data integrity. Integrity is the assertion that the data was not altered by the consumer or a man-in-the-middle. With a hash-based solution the RESTful link may look like:

http://rest.com/account?account_id=123456&digest=83r/grjAxjcqe5FE42xRgD6YF00q4DmsJALlfA==

This solution will preserve integrity but it does not provide confidentiality. If the consumer or malicious user alters the account ID a server-side integrity check against the hash algorithm will fail. The JUnit below demonstrates the creation of the digest (hash) and the assertion to validate the integrity of the clear text and digest have been preserved:

@Test
public void testJasyptsHashAlgorithm() {
/*
* By default the standard digester uses the RandomSaltGenerator and runs the hash
* algorithm 1000 times. These are configurable for greater security.
*/

StandardStringDigester digester = new StandardStringDigester();
digester.setAlgorithm("SHA-1");

final String clearText = "123456";
final String digest = digester.digest(clearText);
Assert.assertTrue("Integrity has been violated!", digester.matches(clearText, digest));
}

Encryption

Encryption is an ideal solution if you want to preserve integrity and confidentiality. For example, an encryption-based RESTful link may look like:

http://rest.com/account/kNddGYRn3KAWK5nYJ/5jrA==

The JUnit below demonstrates the creation of the encrypted text and the assertion to validate the integrity of the encrypted text has been preserved:

@Test
public void testJasyptsEncryptionAlgorithm() {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("password");
encryptor.setAlgorithm("PBEWithMD5AndTripleDES");

final String clearText = "123456";
String encryptedText = encryptor.encrypt(clearText);

String decryptedText = null;
try {
decryptedText = encryptor.decrypt(encryptedText);
} catch (EncryptionOperationNotPossibleException e) {
Assert.fail("Integrity has been violated!");
}
Assert.assertEquals(clearText, decryptedText);
}

Do not expose sensitive data

The ideal solution is to not expose any sensitive information. Alternatively, instead of exposing a sensitive primary key expose an associative key or index that has no identifying relationship to the entity. A common scenario occurs when consumers need to search and maintain records. Consider the following use case:
  1. User performs a search
  2. The server-side executes the search and stores the list of authorized search results within session
  3. The server only exposes the indexes of the entities the consumer is allowed to maintain: http://rest.com/account/{index_id}
This solution preserves integrity by restricting the user to only maintain the records they are authorized to manage and we do not expose a confidential primary key.