Bring the FUN back to Java development Set of tools, making development easier Illarion Kovalchuk © 2011
<?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <web-app id=&quot;WebApp_9&quot; version=&quot;2.4&quot; xmlns=&quot;http://java.sun.com/xml/ns/j2ee&quot;  xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;  xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;> <display-name>Servlet 2.4 application</display-name> <filter> <filter-name>ServletMappedDoFilter_Filter</filter-name> <filter-class>tests.Filter.DoFilter_Filter</filter-class> <init-param> <param-name>attribute</param-name> <param-value>tests.Filter.DoFilter_Filter.SERVLET_MAPPED</param-value> </init-param> </filter> <filter-mapping> <filter-name>ServletMappedDoFilter_Filter</filter-name> <url-pattern>/DoFilterTest</url-pattern> <dispatcher>REQUEST</dispatcher> </filter-mapping> <filter-mapping> <filter-name>ServletMappedDoFilter_Filter</filter-name> <url-pattern>/IncludedServlet</url-pattern> <dispatcher>INCLUDE</dispatcher> </filter-mapping> ... Problem Enterprise Java development can be boring
Problem I have no solution. If you're bored of Java, you are. Enterprise Java development can be boring But Java still rocks ;)
Approach Use the right tools! Keep It Simple Write less code, write clean code Always consider the context
Overview – the stuff I'd like  to talk about
Useful Libraries Mockito
Guice
Guava
Useful Libraries http://code.google.com/p/mockito/ Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with clean & simple API. Mockito doesn't give you  hangover  because the tests are very readable and they produce clean verification errors.
Useful Libraries - Mockito
Useful Libraries - Mockito
Useful Libraries - Mockito
Useful Libraries - Mockito SLIDE FOR THOSE, WHO CAN READ SO MUCH CODE
Useful Libraries Put simply, Guice alleviates the need for factories and the use of new in your Java code. Think of Guice's  @Inject  as the new new http://code.google.com/p/google-guice/ google-guice
Useful Libraries – google-guice public class   BillingModule   extends   AbstractModule  { @Override   protected void  configure ()  { bind( TransactionLog .class).to( Database TransactionLog .class); bind( CreditCardProcessor .class).to( Paypal CreditCardProcessor .class); bind( BillingService .class).to( Real BillingService .class); } } Setup
Useful Libraries – google-guice public class   BillingModule   extends   AbstractModule  { @Override   protected void  configure ()  { bind( TransactionLog .class).to( Database TransactionLog .class); bind( CreditCardProcessor .class).to( Paypal CreditCardProcessor .class); bind( BillingService .class).to( Real BillingService .class); } } Setup @Inject public   RealBillingService ( CreditCardProcessor  processor,  TransactionLog  log ) { this .processor = processor; this .log = log; } Inject
Useful Libraries – google-guice public class   BillingModule   extends   AbstractModule  { @Override   protected void  configure ()  { bind( TransactionLog .class).to( Database TransactionLog .class); bind( CreditCardProcessor .class).to( Paypal CreditCardProcessor .class); bind( BillingService .class).to( Real BillingService .class); } } Setup @Inject public   RealBillingService ( CreditCardProcessor  processor,  TransactionLog  log ) { this .processor = processor; this .log = log; } Inject public static void  main( String [] args) { Injector  injector =  Guice .createInjector(new  BillingModule ()); BillingService  billingService = injector.getInstance( BillingService .class); ... } Launch!
Useful Libraries The Guava project contains several of Google's core libraries that we rely on in our Java-based projects: collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, and so forth. guava-libraries http://code.google.com/p/guava-libraries/
Useful Libraries - guava-libraries Example 1: Objects public class   Person  { final  String  name, nickname; final  Movie  favMovie; @Override   public  boolean equals(Object object) { if (object instanceof Person) { Person  that = ( Person ) object; return  Objects .equal(this.name, that.name) &&  Objects .equal(this.nickname, that.nickname) &&  Objects .equal(this.favMovie, that.favMovie); } return false; } @Override public  int hashCode() { return  Objects .hashCode(name, nickname, favMovie); }
Useful Libraries - guava-libraries Example 2: Other useful things Preconditions .checkState(state ==  State .PLAYABLE,  &quot;Can't play movie; state is %s&quot; , state); //will throw ISE with message … this.rating  = Preconditio ns.checkNotNull(rating); //will throw  NPE … //CharMatcher matcher = CharMatcher.is('x'); //CharMatcher matcher = CharMatcher.isNot('_'); //CharMatcher matcher = CharMatcher.oneOf(&quot;aeiou&quot;).negate(); CharMatcher  matcher =  CharMatcher .inRange('a', 'z').or(inRange('A', 'Z')); matcher.matchesAllOf(“some string”); matcher.matchesAnyOf(“other string”);  … String s = Joiner.on(&quot;, &quot;).join(episodesOnDisc); … StringBuilder  sb = ...; Joiner .on(&quot;|&quot;).skipNulls().appendTo(sb, episodesOnDisc);
Useful Libraries - guava-libraries Example 3: Collections2 List < Integer > integers = ... Collection < String > results; results =  Collections2 . transform (integers, new  Function < Integer ,  String >() { public  String apply(Integer input) { return  Integer.toString(input*2); } }); Collection < Integer > evens; evens =  Collections2 . filter (integers, new  Predicate < Integer >() { public  boolean apply( Integer  input) { return  0 == input % 2; } });
Useful Tools MoreUnit
ecl Emma
XMind
Useful Tools - moreUnit Decorates classes having a test.
Marks methods under test.
Jump to a test via the menu or Ctrl+J
Run a test from the class via the menu or Ctrl-R
Rename classes/methods.
Move classes and MoreUnit will move the corresponding test cases.
Generate a test class/method. http://moreunit.sourceforge.net/
Useful Tools - eclEmma Launches from eclipse like JUnit.

Bring the fun back to java

  • 1.
    Bring the FUNback to Java development Set of tools, making development easier Illarion Kovalchuk © 2011
  • 2.
    <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?><web-app id=&quot;WebApp_9&quot; version=&quot;2.4&quot; xmlns=&quot;http://java.sun.com/xml/ns/j2ee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;> <display-name>Servlet 2.4 application</display-name> <filter> <filter-name>ServletMappedDoFilter_Filter</filter-name> <filter-class>tests.Filter.DoFilter_Filter</filter-class> <init-param> <param-name>attribute</param-name> <param-value>tests.Filter.DoFilter_Filter.SERVLET_MAPPED</param-value> </init-param> </filter> <filter-mapping> <filter-name>ServletMappedDoFilter_Filter</filter-name> <url-pattern>/DoFilterTest</url-pattern> <dispatcher>REQUEST</dispatcher> </filter-mapping> <filter-mapping> <filter-name>ServletMappedDoFilter_Filter</filter-name> <url-pattern>/IncludedServlet</url-pattern> <dispatcher>INCLUDE</dispatcher> </filter-mapping> ... Problem Enterprise Java development can be boring
  • 3.
    Problem I haveno solution. If you're bored of Java, you are. Enterprise Java development can be boring But Java still rocks ;)
  • 4.
    Approach Use theright tools! Keep It Simple Write less code, write clean code Always consider the context
  • 5.
    Overview – thestuff I'd like to talk about
  • 6.
  • 7.
  • 8.
  • 9.
    Useful Libraries http://code.google.com/p/mockito/Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with clean & simple API. Mockito doesn't give you hangover because the tests are very readable and they produce clean verification errors.
  • 10.
  • 11.
  • 12.
  • 13.
    Useful Libraries -Mockito SLIDE FOR THOSE, WHO CAN READ SO MUCH CODE
  • 14.
    Useful Libraries Putsimply, Guice alleviates the need for factories and the use of new in your Java code. Think of Guice's  @Inject  as the new new http://code.google.com/p/google-guice/ google-guice
  • 15.
    Useful Libraries –google-guice public class BillingModule extends AbstractModule { @Override protected void configure () { bind( TransactionLog .class).to( Database TransactionLog .class); bind( CreditCardProcessor .class).to( Paypal CreditCardProcessor .class); bind( BillingService .class).to( Real BillingService .class); } } Setup
  • 16.
    Useful Libraries –google-guice public class BillingModule extends AbstractModule { @Override protected void configure () { bind( TransactionLog .class).to( Database TransactionLog .class); bind( CreditCardProcessor .class).to( Paypal CreditCardProcessor .class); bind( BillingService .class).to( Real BillingService .class); } } Setup @Inject public RealBillingService ( CreditCardProcessor processor, TransactionLog log ) { this .processor = processor; this .log = log; } Inject
  • 17.
    Useful Libraries –google-guice public class BillingModule extends AbstractModule { @Override protected void configure () { bind( TransactionLog .class).to( Database TransactionLog .class); bind( CreditCardProcessor .class).to( Paypal CreditCardProcessor .class); bind( BillingService .class).to( Real BillingService .class); } } Setup @Inject public RealBillingService ( CreditCardProcessor processor, TransactionLog log ) { this .processor = processor; this .log = log; } Inject public static void main( String [] args) { Injector injector = Guice .createInjector(new BillingModule ()); BillingService billingService = injector.getInstance( BillingService .class); ... } Launch!
  • 18.
    Useful Libraries TheGuava project contains several of Google's core libraries that we rely on in our Java-based projects: collections, caching, primitives support, concurrency libraries, common annotations, string processing, I/O, and so forth. guava-libraries http://code.google.com/p/guava-libraries/
  • 19.
    Useful Libraries -guava-libraries Example 1: Objects public class Person { final String name, nickname; final Movie favMovie; @Override public boolean equals(Object object) { if (object instanceof Person) { Person that = ( Person ) object; return Objects .equal(this.name, that.name) && Objects .equal(this.nickname, that.nickname) && Objects .equal(this.favMovie, that.favMovie); } return false; } @Override public int hashCode() { return Objects .hashCode(name, nickname, favMovie); }
  • 20.
    Useful Libraries -guava-libraries Example 2: Other useful things Preconditions .checkState(state == State .PLAYABLE, &quot;Can't play movie; state is %s&quot; , state); //will throw ISE with message … this.rating = Preconditio ns.checkNotNull(rating); //will throw NPE … //CharMatcher matcher = CharMatcher.is('x'); //CharMatcher matcher = CharMatcher.isNot('_'); //CharMatcher matcher = CharMatcher.oneOf(&quot;aeiou&quot;).negate(); CharMatcher matcher = CharMatcher .inRange('a', 'z').or(inRange('A', 'Z')); matcher.matchesAllOf(“some string”); matcher.matchesAnyOf(“other string”); … String s = Joiner.on(&quot;, &quot;).join(episodesOnDisc); … StringBuilder sb = ...; Joiner .on(&quot;|&quot;).skipNulls().appendTo(sb, episodesOnDisc);
  • 21.
    Useful Libraries -guava-libraries Example 3: Collections2 List < Integer > integers = ... Collection < String > results; results = Collections2 . transform (integers, new Function < Integer , String >() { public String apply(Integer input) { return Integer.toString(input*2); } }); Collection < Integer > evens; evens = Collections2 . filter (integers, new Predicate < Integer >() { public boolean apply( Integer input) { return 0 == input % 2; } });
  • 22.
  • 23.
  • 24.
  • 25.
    Useful Tools -moreUnit Decorates classes having a test.
  • 26.
  • 27.
    Jump to atest via the menu or Ctrl+J
  • 28.
    Run a testfrom the class via the menu or Ctrl-R
  • 29.
  • 30.
    Move classes andMoreUnit will move the corresponding test cases.
  • 31.
    Generate a testclass/method. http://moreunit.sourceforge.net/
  • 32.
    Useful Tools -eclEmma Launches from eclipse like JUnit.
  • 33.
    Coverage results areimmediately summarized and highlighted.
  • 34.
    Does not requiremodifying projects or performing any other setup. EclEmma is a free Java code coverage tool for  Eclipse http://www.eclemma.org/index.html http://emma.sourceforge.net/
  • 35.
    Useful Tools -XMind Based on Eclipse engine
  • 36.
    Powerful tool toorganize your thoughts XMind is your friend! http://www.xmind.net/
  • 37.
    Coding techniques Usebuilder pattern as a mini-DSL to describe something
  • 38.
  • 39.
    Do not writeso many unit tests, as they tell you!
  • 40.
  • 41.
    Coding techniques Usebuilder pattern as a mini-DSL to describe something complex Car car = new Car(Engine.NORMAL, Fuel.A95, 5, null, “NoName”, … ); Hard to supply all of the parameters, if some of them are not significant.
  • 42.
    Hard to read– what is that null parameter for, or what's 5?
  • 43.
    Naive replacement withsetters doesn't work – you can forget to call some. or even worse – some other code can access them later and change engine of your car or add some doors!
  • 44.
    Coding techniques Usebuilder pattern as a mini-DSL to describe something complex Car car = new Car(Engine.NORMAL, Fuel.A95, 5, null, “NoName”, … ); Car car = Car. builder() . withEngine(Engine.NORMAL) .withFuel(Fuel.A95) .withDoors(5) .withName(“NoName) .build(); If some parameter is default – just don't set it
  • 45.
  • 46.
    Can have checksin build(), to ensure the result correctness.
  • 47.
    Result can haveno setters or modifiers – safe to work with.
  • 48.
    Coding techniques Verboseunit tests @Test public void testProcess(){ … } @Test public void testRegister(){ … } …
  • 49.
    Coding techniques Verboseunit tests @Test public void process Should FailOnNull(){…} @Test public void process Should WorkOnEmptyString(){…} @Test public void process Should CheckSemicolons(){…} … @Test public void register Should FailOnNull(){…} @Test public void register Should CallProcess (){…} … Friend of you the “ SHOULD ” is @Test public void testProcess(){ … } @Test public void testRegister(){ … } …
  • 50.
    Coding techniques Donot write so many unit tests as they tell you “ Cargo cult programming is a style of  computer programming  that is characterized by the ritual inclusion of code or program structures that serve no real purpose. ” Wikipedia Wikipedia 100% code coverage
  • 51.
    Coding techniques Donot write so many unit tests as they tell you 100% code coverage != 100% code quality
  • 52.
    Tests quantity !=tests quality
  • 53.
    The fact thatthe line of code was called is just a “smoke test”
  • 54.
    Unit tests cannotreplace other tests
  • 55.
    Coding techniques AvoidString-typing public class User { … public User(String login, String password, String home, String shell) { … } … } String login = … String password = … String home = … String shell = … User user = new User(login, password, home, shell); User user = new User(password, home, login, “ “);
  • 56.
    Coding techniques AvoidString-typing public class User { … public User(Login login, Password password, Home home, Shell shell) { … } … } Login login = … Password password = … Home home = … Shell shell = … User user = new User(login, password, home, shell); User user = new User(password, home, login, “ “); // – will not compile Or use a builder pattern, keeping String as type of all these parameters