Skip to content

Instantly share code, notes, and snippets.

@martinsson
Last active January 3, 2019 15:11
Show Gist options
  • Save martinsson/2cad7ef64132755e254b8daf615cc5ef to your computer and use it in GitHub Desktop.
Save martinsson/2cad7ef64132755e254b8daf615cc5ef to your computer and use it in GitHub Desktop.
The static initialiser has been replace by a lazy initialiser, allowing for loading the class without provoking a query to the database.
public class LazyInitialiserDependency {
private static Map<String, Object> translationMap;
// no more static initaliser, the class is mockable, though we'll have to go further by
// adding a version of getTranslation as an instance method if we want to mock it
// this static method is called by the class you'd like to test
public static String getTranslation(String key, Locale locale) {
Object keys = getTranslationMap().get(locale.toString());
// logic ...
// etc ...
return null;
}
private static void initialiseTranslationMap() {
translationMap = HibernateUtil.executeQuery("Select ...");
}
private static Map<String, Object> getTranslationMap() {
if (translationMap == null) {
initialiseTranslationMap();
}
return translationMap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment