Refactoring and NPE fixed in sample code