SlideShare a Scribd company logo
1 of 63
Download to read offline
Eberhard Wolff



10 Typical Problems in
Enterprise Java Applications
Why this talk?
  I do a lot of reviews
  There are some common problems you
   see over and over again

  So: Here are 10
  •  …not necessarily the most common
  •  ...but certainly with severe effects
#1
public class Service {	
	
      private CustomerDao customerDao;	
      private PlatformTransactionManager transactionManager;	
	
      public void performSomeService() {	
         TransactionStatus transactionStatus = transactionManager	
          .getTransaction(new DefaultTransactionDefinition());	
         customerDao.doSomething();	
         customerDao.doSomethingElse();	
         transactionManager.commit(transactionStatus);	
      }	
	
}	
  
#1 Weak Transaction Handling
public class Service {	
	
      private CustomerDao customerDao;	
      private PlatformTransactionManager transactionManager;	
	
      public void performSomeService() {	
         TransactionStatus transactionStatus = transactionManager	
          .getTransaction(new DefaultTransactionDefinition());	
         customerDao.doSomething();	
         customerDao.doSomethingElse();	
         transactionManager.commit(transactionStatus);	
      }	
	  What happens to the transaction if the DAO
    throws an exception?
}	
  

   We might never learn...
   ...or learn the hard way
Weak Transaction Handling: Impact
  Hard to detect, has effects only if
   exception is thrown
  …but then it can lead to wired behavior
   and data loss etc.

  Protection against failures is why you are
   using transactions in the first place
  This is compromised
Solution
  Declarative transactions
public class Service {	
	
      private CustomerDao customerDao;	
	
      @Transactional	
      public void performSomeService() {	
         customerDao.doSomething();	
         customerDao.doSomethingElse();	
      }	
	
}	
  

 •  Exception is caught, transaction is rolled back (if
    it is a RuntimeException)
 •  Exception handling can be customized
A different solution…
 public void performSomeService() {	
   TransactionTemplate template = new TransactionTemplate(	
    transactionManager);	
   template.execute(new TransactionCallback() {	
 	
     public Object doInTransaction(TransactionStatus status) {	
        customerDao.doSomething();	
        customerDao.doSomethingElse();	
        return null;	
     }	
 	
    });	
 }
  Allows for multiple transactions in one method
  More code – more control
  Rather seldomly really needed
#2 Exception Design
  Get all the details from a system
   exception!
  Each layer must only use its own
   exceptions!
  Exceptions have to be checked – then
   they must be handled and the code is
   more secure.

  Sounds reasonably, doesn't it?
public class OrderDao {	
   public void createOrder(Order order) throws SQLException {	
      // some ugly JDBC code	
      // that I am not going to show	
   }	
}	
                       public class SomeService {	
                          public void performService()	
Get all the details!         throws ServiceException {	
Use checked                  try {	
exceptions!                     orderDao.createOrder(new Order());	
                             } catch (SQLException e) {	
                                throw new ServiceException(e);	
Service must only            }	
throw                     }	
ServiceException!      }	       public class SomeController {	
                                  public void handleWebRequest() {	
                                     try {	
 What am I supposed to do               someService.performService();	
 now?                                } catch (Exception e) {	
 No real logging                        e.printStackTrace();	
                                     }	
 And I don’t care about the       }	
 specific ServiceException    }
Impact
  Lots of useless exception handling code
  Lots of exception types without specific
   handling of that type
  In the end all you get is a log entry
  …and lots of code

  And what should the developer do?
  •  All he knows "Something went wrong"
  •  Does not really care and can not really
     handle it
Why is this commonplace?
  Very few languages have checked exceptions
   (Java - CLU and Modula-3 had similar concepts)
  Checked exception force developers to handle an
   exception – very rigid
  How often can you really handle an exception?
  Checked exceptions seem more secure
  But: Checked exceptions are overused – also in
   Java APIs

  In many cases there are even no wrong
   exception concepts in projects – there are just
   none.
Solution
  Use more unchecked exceptions aka
   RuntimeExceptions
  Remember: A lot of languages offer only
   unchecked exceptions

  Avoid wrap-and-rethrow – it does not add
   value
  Don't write too many exception classes –
   they often don't add value
  An exception classes is only useful if that
   exception should be handled differently
Solution
public class OrderDao {	
   public void createOrder(Order order) {	
      jdbcTemplate.update("INSERT INTO T_ORDER ...");	
   }	
}	



                     public class SomeService {	
Where is the            public void performService() {	
                           orderDao.createOrder(new Order());	
exception               }	
                     }	
handling?
                                public class SomeController {	
                                  public void handleWebRequest() {	
                                     someService.performService();	
                                  }	
                                }
AOP in one Slide
@Aspect	
public class AnAspect {	
	
   // do something before the method hello	
   // is executed	
   @Before("execution(void hello())")	
   public void doSomething() {	
   }	
	
  // in a specific class	
   // that ends in Service in any package or subpackage	
   @Before("execution(* com.springsource.MyService.hello())")	
   public void doSomethingElse2() {	
   }	
	
   // do something before any method in a class	
   // that ends in Service in any package or subpackage	
   @Before("execution(* *..*Service.*(..))")	
   public void doSomethingElse2() {	
   }	
	
}
Aspect for Logging
@Aspect	
public class ExceptionLogging {	
	
   @AfterThrowing(value="execution(* *..*Service.*(..))",	
    throwing="ex")	
   public void logRuntimeException(RuntimeException ex) {	
      System.out.println(ex);	
   }	
	
}	


  Logs every exception – 100%
   guaranteed!
Handle only specific cases
 public class SomeService {	
    public void performService() {	
       try {	
          orderDao.createOrder(new Order());	
       } catch (OptimisticLockingFailureException ex) {	
          orderDao.createOrder(new Order());	
       }	
    }	
 }	

  Everything else will be handled
   somewhere else
  Can handle specific error conditions
   using catch with specific types
  Can be done with AOP
Generic Exception Handling
public class MyHandlerExceptionResolver	
  implements HandlerExceptionResolver {	
	
   public ModelAndView resolveException(	
    HttpServletRequest request,	
    HttpServletResponse response, Object handler, Exception ex) {	
      return new ModelAndView("exceptionView", "exception", ex);	
   }	
	
}

  In the web layer
  Handle all the (Runtime)Exceptions not
   handled elsewhere
#3 Exception Handling

 public void someMethod() {	         Exception is not logged
   try {	
 	                                   just written to stdout
   } catch (Exception ex) {	         operations might not notice
      ex.printStackTrace();	
   }	
   try {	
 	
   } catch (Exception ex) {	
      log.error(ex.getMessage());	
                                     Stack trace will be lost
   }	
   try {	
 	
   } catch (Exception ex) {	         Exception is swallowed
      // should never happen	        comment suggests it would be
   }	
 }                                   serious error
Impact
  Related to #2: Bad Exception design will
   cause more bad exception handling

  In the end you just get a message on the
   console and the application continues.
  All kinds of wired behavior
  i.e. exception is swallowed
  You will have a hard time finding
   problems in the code
  Potentially a huge problem – so worth its
   own explanation
Solution
  At least log exceptions including stack trace
  Rethink: Is it really OK to continue after the
   exception is thrown? Might be better to let a
   generic handler handle it.
  Introduce generic handling at least for
   RuntimeException (AOP, web front end, etc)
  Enforce logging using
   Findbugs, PMD etc.          public void someMethod() {	
                                 try {	
  And: Improve the            	
                                 } catch (Exception ex) {	
   exception design (#2)           log.error(ex);	
                                      }	
                                  }
#4
  Table of
   packages and
   the relations
   between them
  Everything in
   red is part of
   a cycle
  This is actual
   code from an
   Open Source
   project
Dependency Graph
  Overview
Dependency Graph

  Just a small
   part
  Red line show
   circular
   references
What is Architecture?
  Architecture is the decomposition of
   systems in parts

  No large or complex parts
  No cyclic dependencies
Normal Dependencies

  B dependes on A, i.e. it
   uses classe, methods
                              Component A
   etc.
  Changes in A impact B
  Changes in B do not
   impact A
                              Component B
Cyclic Dependency

  B depends on A and A
   on B
                            Component A
  Changes in A impact B
  Changes in B impact A
  A and B can only be
   changed as one unit      Component B
  …even though they
   should be two separate
   units
Bigger cyclic dependencies


     Component A


                    Component B


     Component C
#4: Architecture Mess
  This is
   effectively just
   one big
   unstructured
   pile of mud
  Maintenance
   will be hard
  Concurrent
   development
   will be hard
  Changes will
   have
   unforeseeable
   results
Solution
  Very hard if you have this state
  Therefore: Manage dependencies from the
   start
  Otherwise you are looking at a major
   restructuring of your application
  …which might not be worth it
  Effort for restructuring pays off by lower
   effort for maintenance
  …might take a long time to amortize

  Throwing away + redevelopment means
   that you have to migrate to a new solution -
   > complex and risky
Metrics are not everything
  If everything is in one package there will be
   no cycles
  If packages for technical artifact (DAOs,
   services) might hide cycles in the functional
   decomposition
  If interfaces and implementation are in the
   same package dependencies to the
   implementation might slip in.
  A cycle with one dependency in the "wrong"
   direction is different from one with 40 in
   both directions.
  Think about the structure – don't let metric
   fool you.
#5
public class ServiceAdaptor {	
   public void performService(OrderDTO orderDTO) {	
      logger.trace("Entering performService");	
      try {	
         if (orderDTO == null) {	
            throw new NullPointerException("order must not be null");	
         }	
         if (youAreNotAllowedToDoThis()) {	
            throw new IllegalStateException(	
             "You are not allowed to call this!");	
         }	
         OrderEntity order = new OrderEntity();	
         order.setCustomer(orderDTO.getCustomer()); // ...	
         service.performService(order);	
         commandLog.add(new Command("performService",	
          service,order));	
      } finally {	
         logger.trace("Leaving performanceService");	
      }	
   }	
}
#5: Adaptor Layer
  Adds to a service:
  •    Security
  •    Tracing
  •    Check for null arguments
  •    Log for all commands (auditing, replay…)
  •    Conversion from DTO to internal
       representation
  Lots of boilerplate code for each service
  Changes to tracing etc. hard: lots of
   methods to change
Solution: Tracing with AOP
  …or use Spring's predefined
   TraceInterceptor, DebugInterceptor etc.
  @Aspect	
  public class TraceAspect {	
  	
    @Before("execution(* *..*Service.*(..))")	
    public void traceBegin(JoinPoint joinPoint) {	
      System.out.println("entering method "	
        + joinPoint.getSignature().getName());	
     }	
  	
     @After("execution(* *..*Service.*(..))")	
     public void traceEnd(JoinPoint joinPoint) {	
        System.out.println("leaving method "	
         + joinPoint.getSignature().getName());	
     }	
  }
Solution: Null Checks with AOP
@Aspect	
public class NullChecker {	
	
  @Before("execution(* *..*Service.*(..))")	
  public void checkForNull(JoinPoint joinPoint) {	
     for (Object arg : joinPoint.getArgs()) {	
        if (arg==null) {	
          throw new NullPointerException("Argument was null!");	
        } 	
     }	
  }	
	
}


  Security can be handled with Spring
   Security or AOP
  Command log also possible
What is left…
public class ServiceAdaptor {	
	
  public void performService(OrderDTO orderDTO) {     	
     OrderEntity order = new OrderEntity();	
     order.setCustomer(orderDTO.getCustomer()); // ...	
     service.performService(order);	
  }	
	
}
   You should probably switch to Dozer
   http://dozer.sf.net
   Can externalize mapping rules
   i.e. the layer can be more or less eliminated
   Everything (mapping, security, tracing…) is now
    implemented in one place (DRY)
   Often services just delegate to DAOs –
     same issue
#6: No DAO
public class SomeService {	
	
  @PersistenceContext	
  private EntityManager entityManager;	
	
  public void performSomeService() {	
     List<Order> list = entityManager.	
      createQuery("select o from Order").getResultList();	
     for (Order o : list) {	
        // ...	
        if (o.shouldBeProcessed()) {	
           o.process();	
        }	
     }	
  }	
}

  We don't need to abstract away from
   JPA – it's a standard, right?
#6: Even worse
public class SomeServiceJdbc {	
	
private OrderDao someDoa;	
	
  public void performSomeService() throws SQLException {	
     ResultSet rs = someDoa.getOrders();	
     while (rs.next()) {	
        //...	
     }	
  }	
	
}

  Service depends on JDBC
  …and throws SQLException
  Persistence visible in the service layer
   and beyond
Impact
  Code is impossible to test without a
   database
  …so no unit tests possible

  Service depends on persistence – cannot be
   ported

  How do you add data dependent security?

  No structure
Solution
  Use a DAO (Data Access Object)
  •  Separate persistence layer
  •  Technical motivation


  …or a Repository
  •  Interface to existing objects
  •  Non technical motivation: Domain Driven
     Design, Eric Evans


  Basically the same thing
Solution
public class SomeServiceDAO {	
	
  public void performSomeService() {	
     List<Order> list = orderDao.getAllOrders();	
     for (Order o : list) {	
       // ...	
       if (o.shouldBeProcessed()) {	
          o.process();	
       }	
      }	
  }	
}

  Clear separation
  Tests easy
Solution: Test
public class ServiceTest {	
  @Test	
  public void testService() {	
     SomeService someService = new SomeService();	
     someService.setOrderDao(new OrderDao() {	
	
       public List<Order> getAllOrders() {	
          List<Order> result = new ArrayList<Order>();	
          return result;	
       }	
     });	
     someService.performSomeService();	
     Assert.assertEquals(expected, result);	
  }	
	
}
#7
  No Tests
#7 Or bad tests
  No asserts       public class MyUnitTest {	
                      private Service service = new Service();	
  System.out:      	
   results are        @Test	
   checked            public void testService() {	
   manually             Order order = new Order();	
                        service.performService(order);	
  Tests
   commented out: }	System.out.print(order.isProcessed());	
   They did not run 	
   any more and       // @Test	
   were not fixed     // public void testOrderCreated() {	
  No mocks, so no // Order order = new Order();	
                      // service.createOrder(order);	
   real Unit Tests    // }	
  No negative      	
   cases            }
Impact
  Code is not properly tested
  Probably low quality – testable code is
   usually better designed
  Code is hard to change: How can you
   know the change broke nothing?
  Design might be bad: Testable usually
   mean better quality
  Code might be considered tested – while
   in fact it is not.
Solution
  Write proper Unit Tests!
public class MyProperUnitTest {	
   private Service service = new Service();	
	
   @Test	
   public void testService() {	
      Order order = new Order();	
      service.performService(order);	
      Assert.assertTrue(order.isProcessed());	
   }	
	
   @Test(expected=IllegalArgumentException.class)	
   public void testServiceException() {	
      Order order = new BuggyOrder();	
      service.performService(order);	
   }	
	
}
Wow, that was easy!
The real problem…
  The idea of Unit tests is over 10 years old
  Still not enough programmer actually do
   real unit tests
  Even though it should greatly increased
   trust and confidence in your code
  …and make you much more relaxed and
   therefore improve quality of life…

  Original paper: Gamma, Beck: "Test
   Infected – Programmers Love Writing Tests"
  Yeah, right.
Solution
  Educate
  •    Show   how to write Unit Test
  •    Show   how to build Mocks
  •    Show   aggressive Testing
  •    Show   Test First / Test Driven Development
  Coach / Review
  Integrate in automatic build
  Later on: Add integration testing,
   functional testing, FIT, Fitnesse etc.
  …or even start with these
What does not really work
  Measuring code coverage
  •  Can be sabotaged: No Asserts…
   public class MyProperUnitTest {	
     private Service service = new Service();	
   	
     @Test	
     public void testService() {	
        Order order = new Order();	
        service.performService(order);	
     }	
   }

  Let developers just write tests without
   education
  •  How should they know how to test properly?
  •  Test driven development is not obvious
#8:

 public class OrderDAO {	
 	
   private SimpleJdbcTemplate simpleJdbcTemplate;	
 	
   public List<Order> findOrderByCustomer(String customer) {	
      return simpleJdbcTemplate.query(	
       "SELECT * FROM T_ORDER WHERE name='"	
       + customer + "'", new OrderRowMapper());	
   }	
 	
 }
Impact
  Performance is bad:
  •  Statement is parsed every time
  •  Execution plan is re created etc.
Impact: SQL Injection
  Pass in
   a' or 't'='t'
  Better yet:
   a'; DROP TABLE T_ORDER; SELECT *
   FROM ANOTHER_TABLE
 public class OrderDAO {	
 	
   private SimpleJdbcTemplate simpleJdbcTemplate;	
 	
   public List<Order> findOrderByCustomer(String customer) {	
      return simpleJdbcTemplate.query(	
       "SELECT * FROM T_ORDER WHERE name='"	
       + customer + "'", new OrderRowMapper());	
   }	
 	
 }
Solution
 public class OrderDAO {	
 	
   private SimpleJdbcTemplate simpleJdbcTemplate;	
 	
   public List<Order> findOrderByCustomer(String customer) {	
      return simpleJdbcTemplate.query(	
       "SELECT * FROM T_ORDER WHERE name=?",	
       new OrderRowMapper(), customer);	
   }	
 	
 }

  … and white list the allowed characters
   in name
  to avoid bugs in DB driver etc.
#9
  "What about Performance?"
  "Well, we figured the response time
   should be 2s."
  "How many request do you expect?"
  "…"
  "What kind of requests do you expect?"
  "..."
#9
    Software is in the final functional test
    Then the performance test start
    Performance is too bad to be accepted
    You can hardly do anything:
     •  Changes might introduce functional errors after
        testing
     •  Too late for bigger changes
  The results might be wrong if the
   performance test is on different hardware
   than production.
  You can't test on production hardware: Too
   expensive.
Impact
  You have to get bigger hardware
  •  Prerequisite: The software is scalable
  •  Otherwise: Tough luck


  Worse: You can't go into production
Solution
  Get number of requests, expected types
   of requests, acceptable response times
  Pro active performance management:
  •  Estimate performance before implementation
  •  …by estimating the slow operations (access
     to other systems, to the database etc)
  •  Measure performance of these operation in
     production
  Get data from production
  Practice performance measurements and
   optimizations before performance test
#10
  public class SomeService {	
  	
  private Map cache = new HashMap();	
  private Customer customer;	
  	
    public Order performService(int i) { 	
       if (cache.containsKey(i)) {	
          return cache.get(i);	
       }	
       Order result;	
       customer = null;	
       cache.put(i, result);	
       return result;	
    }	
  	
  }
#10 Multiple threads, memory leaks
public class SomeService {	
	                                          The cache is filled –
  private Map<Integer,Order> cache =	      is it ever emptied?
   new HashMap<Integer, Order>();	
  private Customer customer;	              HashMap is not
	
  public Order performService(int i) { 	
                                           threadsafe
     if (cache.containsKey(i)) {	
        return (Ordercache.get(i);	
                                           customer is an
     }	                                    instance variable –
     Order result;	                        multi threading will
     customer = null;	
     ...	
                                           be a problem
     cache.put(i, result);	
     return result;	
  }	
	
}
Impact
  System working in small tests
  In particular Unit tests work

  But production fails
  …probably hard to analyze / fix
  Almost only by code reviews
  …or extensive debugging using thread
   dumps
Solution
  Use
   WeakHashMap public class SomeServiceSolution {	
                   	
   to avoid          private Map<Integer, Order> cache =	
   memory leaks 	 new WeakHashMap<Integer, Order>();	
  Synchronize       public Order performService(int i) {	
                       synchronized (cache) {	
  Prefer local           if (cache.containsKey(i)) {
                             return cache.get(i);	
   variables              }	
                       }	
  Usually services Order result = null;	
                       Customer customer = null;	
   can store most      synchronized (cache) {	
   things in local     }	
                          cache.put(i, result);	

   variables           return result;	
                           }	
                       }
Solution
  Also consider ConcurrentHashMap
  or http://sourceforge.net/projects/high-
   scale-lib
Sum Up
  #1 Weak Transaction      #8 Creating SQL
   Handling                  queries using String
  #2 Exception Design       concatenation
  #3 Exception             #9 No performance
   Handling                  management
  #4 Architecture Mess     #10 Multiple
                             threads / memory
  #5 Adaptor Layer
                             leaks
  #6 No DAO
  #7 No or bad tests

More Related Content

What's hot

Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxDavid Rodenas
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS ProgrammersDavid Rodenas
 
TDD CrashCourse Part5: Testing Techniques
TDD CrashCourse Part5: Testing TechniquesTDD CrashCourse Part5: Testing Techniques
TDD CrashCourse Part5: Testing TechniquesDavid Rodenas
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeDaniel Wellman
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript TestingKissy Team
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"epamspb
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testingjeresig
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock TutorialSbin m
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special CasesCiklum Ukraine
 
Testing logging in asp dot net core
Testing logging in asp dot net coreTesting logging in asp dot net core
Testing logging in asp dot net coreRajesh Shirsagar
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
TDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving TestingTDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving TestingDavid Rodenas
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksEndranNL
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean codeIBM
 

What's hot (20)

Introduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicoxIntroduction to web programming for java and c# programmers by @drpicox
Introduction to web programming for java and c# programmers by @drpicox
 
Redux for ReactJS Programmers
Redux for ReactJS ProgrammersRedux for ReactJS Programmers
Redux for ReactJS Programmers
 
TDD CrashCourse Part5: Testing Techniques
TDD CrashCourse Part5: Testing TechniquesTDD CrashCourse Part5: Testing Techniques
TDD CrashCourse Part5: Testing Techniques
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
 
How to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy CodeHow to Start Test-Driven Development in Legacy Code
How to Start Test-Driven Development in Legacy Code
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
#ITsubbotnik Spring 2017: Roman Iovlev "Java edge in test automation"
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
JMockit
JMockitJMockit
JMockit
 
Unit Testing: Special Cases
Unit Testing: Special CasesUnit Testing: Special Cases
Unit Testing: Special Cases
 
Server1
Server1Server1
Server1
 
Testing logging in asp dot net core
Testing logging in asp dot net coreTesting logging in asp dot net core
Testing logging in asp dot net core
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
TDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving TestingTDD CrashCourse Part4: Improving Testing
TDD CrashCourse Part4: Improving Testing
 
Checking VirtualDub
Checking VirtualDubChecking VirtualDub
Checking VirtualDub
 
Mockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworksMockito vs JMockit, battle of the mocking frameworks
Mockito vs JMockit, battle of the mocking frameworks
 
Presentacion clean code
Presentacion clean codePresentacion clean code
Presentacion clean code
 

Viewers also liked

Distributed Programming using RMI
Distributed Programming using RMIDistributed Programming using RMI
Distributed Programming using RMIbackdoor
 
Best Practices To Fix 5 Common Web Application Problems: Web Performance Moni...
Best Practices To Fix 5 Common Web Application Problems: Web Performance Moni...Best Practices To Fix 5 Common Web Application Problems: Web Performance Moni...
Best Practices To Fix 5 Common Web Application Problems: Web Performance Moni...Compuware APM
 
Service Oriented Architecture and Business Process Modeling Overview
Service Oriented Architecture and Business Process Modeling OverviewService Oriented Architecture and Business Process Modeling Overview
Service Oriented Architecture and Business Process Modeling OverviewJean Ferguson
 
Top 10 Application Problems
Top 10 Application ProblemsTop 10 Application Problems
Top 10 Application ProblemsAppDynamics
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Peter R. Egli
 
Translating Tester-Speak Into Plain English: Simple Explanations for 8 Testin...
Translating Tester-Speak Into Plain English: Simple Explanations for 8 Testin...Translating Tester-Speak Into Plain English: Simple Explanations for 8 Testin...
Translating Tester-Speak Into Plain English: Simple Explanations for 8 Testin...Neotys
 

Viewers also liked (7)

Distributed Programming using RMI
Distributed Programming using RMIDistributed Programming using RMI
Distributed Programming using RMI
 
Best Practices To Fix 5 Common Web Application Problems: Web Performance Moni...
Best Practices To Fix 5 Common Web Application Problems: Web Performance Moni...Best Practices To Fix 5 Common Web Application Problems: Web Performance Moni...
Best Practices To Fix 5 Common Web Application Problems: Web Performance Moni...
 
Service Oriented Architecture and Business Process Modeling Overview
Service Oriented Architecture and Business Process Modeling OverviewService Oriented Architecture and Business Process Modeling Overview
Service Oriented Architecture and Business Process Modeling Overview
 
Top 10 Application Problems
Top 10 Application ProblemsTop 10 Application Problems
Top 10 Application Problems
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
 
Translating Tester-Speak Into Plain English: Simple Explanations for 8 Testin...
Translating Tester-Speak Into Plain English: Simple Explanations for 8 Testin...Translating Tester-Speak Into Plain English: Simple Explanations for 8 Testin...
Translating Tester-Speak Into Plain English: Simple Explanations for 8 Testin...
 
Project management
Project managementProject management
Project management
 

Similar to 10 Typical Problems in Enterprise Java Applications

10 Typical Java Problems in the Wild
10 Typical Java Problems in the Wild10 Typical Java Problems in the Wild
10 Typical Java Problems in the WildEberhard Wolff
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesRaffi Khatchadourian
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - TransactionsDmitry Buzdin
 
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit TestsJDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit TestsPROIDEA
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC PrinciplesPavlo Hodysh
 
Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Ismar Silveira
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09Guy Korland
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Raffi Khatchadourian
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiRan Mizrahi
 

Similar to 10 Typical Problems in Enterprise Java Applications (20)

10 Typical Java Problems in the Wild
10 Typical Java Problems in the Wild10 Typical Java Problems in the Wild
10 Typical Java Problems in the Wild
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
JDK Power Tools
JDK Power ToolsJDK Power Tools
JDK Power Tools
 
Automatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to InterfacesAutomatic Migration of Legacy Java Method Implementations to Interfaces
Automatic Migration of Legacy Java Method Implementations to Interfaces
 
Ruslan Platonov - Transactions
Ruslan Platonov - TransactionsRuslan Platonov - Transactions
Ruslan Platonov - Transactions
 
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit TestsJDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
JDD 2016 - Sebastian Malaca - You Dont Need Unit Tests
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
SOLID & IoC Principles
SOLID & IoC PrinciplesSOLID & IoC Principles
SOLID & IoC Principles
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 
Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9Paradigmas de linguagens de programacao - aula#9
Paradigmas de linguagens de programacao - aula#9
 
E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9E:\Plp 2009 2\Plp 9
E:\Plp 2009 2\Plp 9
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Deuce STM - CMP'09
Deuce STM - CMP'09Deuce STM - CMP'09
Deuce STM - CMP'09
 
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
Open Problems in Automatically Refactoring Legacy Java Software to use New Fe...
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
How Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran MizrahiHow Testability Inspires AngularJS Design / Ran Mizrahi
How Testability Inspires AngularJS Design / Ran Mizrahi
 
Exception
ExceptionException
Exception
 
Curator intro
Curator introCurator intro
Curator intro
 

More from Eberhard Wolff

Architectures and Alternatives
Architectures and AlternativesArchitectures and Alternatives
Architectures and AlternativesEberhard Wolff
 
The Frontiers of Continuous Delivery
The Frontiers of Continuous DeliveryThe Frontiers of Continuous Delivery
The Frontiers of Continuous DeliveryEberhard Wolff
 
Four Times Microservices - REST, Kubernetes, UI Integration, Async
Four Times Microservices - REST, Kubernetes, UI Integration, AsyncFour Times Microservices - REST, Kubernetes, UI Integration, Async
Four Times Microservices - REST, Kubernetes, UI Integration, AsyncEberhard Wolff
 
Microservices - not just with Java
Microservices - not just with JavaMicroservices - not just with Java
Microservices - not just with JavaEberhard Wolff
 
Deployment - Done Right!
Deployment - Done Right!Deployment - Done Right!
Deployment - Done Right!Eberhard Wolff
 
Data Architecture not Just for Microservices
Data Architecture not Just for MicroservicesData Architecture not Just for Microservices
Data Architecture not Just for MicroservicesEberhard Wolff
 
How to Split Your System into Microservices
How to Split Your System into MicroservicesHow to Split Your System into Microservices
How to Split Your System into MicroservicesEberhard Wolff
 
Microservices and Self-contained System to Scale Agile
Microservices and Self-contained System to Scale AgileMicroservices and Self-contained System to Scale Agile
Microservices and Self-contained System to Scale AgileEberhard Wolff
 
How Small Can Java Microservices Be?
How Small Can Java Microservices Be?How Small Can Java Microservices Be?
How Small Can Java Microservices Be?Eberhard Wolff
 
Data Architecturen Not Just for Microservices
Data Architecturen Not Just for MicroservicesData Architecturen Not Just for Microservices
Data Architecturen Not Just for MicroservicesEberhard Wolff
 
Microservices: Redundancy=Maintainability
Microservices: Redundancy=MaintainabilityMicroservices: Redundancy=Maintainability
Microservices: Redundancy=MaintainabilityEberhard Wolff
 
Self-contained Systems: A Different Approach to Microservices
Self-contained Systems: A Different Approach to MicroservicesSelf-contained Systems: A Different Approach to Microservices
Self-contained Systems: A Different Approach to MicroservicesEberhard Wolff
 
Microservices Technology Stack
Microservices Technology StackMicroservices Technology Stack
Microservices Technology StackEberhard Wolff
 
Software Architecture for Innovation
Software Architecture for InnovationSoftware Architecture for Innovation
Software Architecture for InnovationEberhard Wolff
 
Five (easy?) Steps Towards Continuous Delivery
Five (easy?) Steps Towards Continuous DeliveryFive (easy?) Steps Towards Continuous Delivery
Five (easy?) Steps Towards Continuous DeliveryEberhard Wolff
 
Nanoservices and Microservices with Java
Nanoservices and Microservices with JavaNanoservices and Microservices with Java
Nanoservices and Microservices with JavaEberhard Wolff
 
Microservices: Architecture to Support Agile
Microservices: Architecture to Support AgileMicroservices: Architecture to Support Agile
Microservices: Architecture to Support AgileEberhard Wolff
 
Microservices: Architecture to scale Agile
Microservices: Architecture to scale AgileMicroservices: Architecture to scale Agile
Microservices: Architecture to scale AgileEberhard Wolff
 
Microservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Microservices, DevOps, Continuous Delivery – More Than Three BuzzwordsMicroservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Microservices, DevOps, Continuous Delivery – More Than Three BuzzwordsEberhard Wolff
 

More from Eberhard Wolff (20)

Architectures and Alternatives
Architectures and AlternativesArchitectures and Alternatives
Architectures and Alternatives
 
Beyond Microservices
Beyond MicroservicesBeyond Microservices
Beyond Microservices
 
The Frontiers of Continuous Delivery
The Frontiers of Continuous DeliveryThe Frontiers of Continuous Delivery
The Frontiers of Continuous Delivery
 
Four Times Microservices - REST, Kubernetes, UI Integration, Async
Four Times Microservices - REST, Kubernetes, UI Integration, AsyncFour Times Microservices - REST, Kubernetes, UI Integration, Async
Four Times Microservices - REST, Kubernetes, UI Integration, Async
 
Microservices - not just with Java
Microservices - not just with JavaMicroservices - not just with Java
Microservices - not just with Java
 
Deployment - Done Right!
Deployment - Done Right!Deployment - Done Right!
Deployment - Done Right!
 
Data Architecture not Just for Microservices
Data Architecture not Just for MicroservicesData Architecture not Just for Microservices
Data Architecture not Just for Microservices
 
How to Split Your System into Microservices
How to Split Your System into MicroservicesHow to Split Your System into Microservices
How to Split Your System into Microservices
 
Microservices and Self-contained System to Scale Agile
Microservices and Self-contained System to Scale AgileMicroservices and Self-contained System to Scale Agile
Microservices and Self-contained System to Scale Agile
 
How Small Can Java Microservices Be?
How Small Can Java Microservices Be?How Small Can Java Microservices Be?
How Small Can Java Microservices Be?
 
Data Architecturen Not Just for Microservices
Data Architecturen Not Just for MicroservicesData Architecturen Not Just for Microservices
Data Architecturen Not Just for Microservices
 
Microservices: Redundancy=Maintainability
Microservices: Redundancy=MaintainabilityMicroservices: Redundancy=Maintainability
Microservices: Redundancy=Maintainability
 
Self-contained Systems: A Different Approach to Microservices
Self-contained Systems: A Different Approach to MicroservicesSelf-contained Systems: A Different Approach to Microservices
Self-contained Systems: A Different Approach to Microservices
 
Microservices Technology Stack
Microservices Technology StackMicroservices Technology Stack
Microservices Technology Stack
 
Software Architecture for Innovation
Software Architecture for InnovationSoftware Architecture for Innovation
Software Architecture for Innovation
 
Five (easy?) Steps Towards Continuous Delivery
Five (easy?) Steps Towards Continuous DeliveryFive (easy?) Steps Towards Continuous Delivery
Five (easy?) Steps Towards Continuous Delivery
 
Nanoservices and Microservices with Java
Nanoservices and Microservices with JavaNanoservices and Microservices with Java
Nanoservices and Microservices with Java
 
Microservices: Architecture to Support Agile
Microservices: Architecture to Support AgileMicroservices: Architecture to Support Agile
Microservices: Architecture to Support Agile
 
Microservices: Architecture to scale Agile
Microservices: Architecture to scale AgileMicroservices: Architecture to scale Agile
Microservices: Architecture to scale Agile
 
Microservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Microservices, DevOps, Continuous Delivery – More Than Three BuzzwordsMicroservices, DevOps, Continuous Delivery – More Than Three Buzzwords
Microservices, DevOps, Continuous Delivery – More Than Three Buzzwords
 

Recently uploaded

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Recently uploaded (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

10 Typical Problems in Enterprise Java Applications

  • 1. Eberhard Wolff 10 Typical Problems in Enterprise Java Applications
  • 2. Why this talk?   I do a lot of reviews   There are some common problems you see over and over again   So: Here are 10 •  …not necessarily the most common •  ...but certainly with severe effects
  • 3. #1 public class Service { private CustomerDao customerDao; private PlatformTransactionManager transactionManager; public void performSomeService() { TransactionStatus transactionStatus = transactionManager .getTransaction(new DefaultTransactionDefinition()); customerDao.doSomething(); customerDao.doSomethingElse(); transactionManager.commit(transactionStatus); } }  
  • 4. #1 Weak Transaction Handling public class Service { private CustomerDao customerDao; private PlatformTransactionManager transactionManager; public void performSomeService() { TransactionStatus transactionStatus = transactionManager .getTransaction(new DefaultTransactionDefinition()); customerDao.doSomething(); customerDao.doSomethingElse(); transactionManager.commit(transactionStatus); }   What happens to the transaction if the DAO throws an exception? }     We might never learn...   ...or learn the hard way
  • 5. Weak Transaction Handling: Impact   Hard to detect, has effects only if exception is thrown   …but then it can lead to wired behavior and data loss etc.   Protection against failures is why you are using transactions in the first place   This is compromised
  • 6. Solution   Declarative transactions public class Service { private CustomerDao customerDao; @Transactional public void performSomeService() { customerDao.doSomething(); customerDao.doSomethingElse(); } }   •  Exception is caught, transaction is rolled back (if it is a RuntimeException) •  Exception handling can be customized
  • 7. A different solution… public void performSomeService() { TransactionTemplate template = new TransactionTemplate( transactionManager); template.execute(new TransactionCallback() { public Object doInTransaction(TransactionStatus status) { customerDao.doSomething(); customerDao.doSomethingElse(); return null; } }); }   Allows for multiple transactions in one method   More code – more control   Rather seldomly really needed
  • 8. #2 Exception Design   Get all the details from a system exception!   Each layer must only use its own exceptions!   Exceptions have to be checked – then they must be handled and the code is more secure.   Sounds reasonably, doesn't it?
  • 9. public class OrderDao { public void createOrder(Order order) throws SQLException { // some ugly JDBC code // that I am not going to show } } public class SomeService { public void performService() Get all the details! throws ServiceException { Use checked try { exceptions! orderDao.createOrder(new Order()); } catch (SQLException e) { throw new ServiceException(e); Service must only } throw } ServiceException! } public class SomeController { public void handleWebRequest() { try { What am I supposed to do someService.performService(); now? } catch (Exception e) { No real logging e.printStackTrace(); } And I don’t care about the } specific ServiceException }
  • 10. Impact   Lots of useless exception handling code   Lots of exception types without specific handling of that type   In the end all you get is a log entry   …and lots of code   And what should the developer do? •  All he knows "Something went wrong" •  Does not really care and can not really handle it
  • 11. Why is this commonplace?   Very few languages have checked exceptions (Java - CLU and Modula-3 had similar concepts)   Checked exception force developers to handle an exception – very rigid   How often can you really handle an exception?   Checked exceptions seem more secure   But: Checked exceptions are overused – also in Java APIs   In many cases there are even no wrong exception concepts in projects – there are just none.
  • 12. Solution   Use more unchecked exceptions aka RuntimeExceptions   Remember: A lot of languages offer only unchecked exceptions   Avoid wrap-and-rethrow – it does not add value   Don't write too many exception classes – they often don't add value   An exception classes is only useful if that exception should be handled differently
  • 13. Solution public class OrderDao { public void createOrder(Order order) { jdbcTemplate.update("INSERT INTO T_ORDER ..."); } } public class SomeService { Where is the public void performService() { orderDao.createOrder(new Order()); exception } } handling? public class SomeController { public void handleWebRequest() { someService.performService(); } }
  • 14. AOP in one Slide @Aspect public class AnAspect { // do something before the method hello // is executed @Before("execution(void hello())") public void doSomething() { } // in a specific class // that ends in Service in any package or subpackage @Before("execution(* com.springsource.MyService.hello())") public void doSomethingElse2() { } // do something before any method in a class // that ends in Service in any package or subpackage @Before("execution(* *..*Service.*(..))") public void doSomethingElse2() { } }
  • 15. Aspect for Logging @Aspect public class ExceptionLogging { @AfterThrowing(value="execution(* *..*Service.*(..))", throwing="ex") public void logRuntimeException(RuntimeException ex) { System.out.println(ex); } }   Logs every exception – 100% guaranteed!
  • 16. Handle only specific cases public class SomeService { public void performService() { try { orderDao.createOrder(new Order()); } catch (OptimisticLockingFailureException ex) { orderDao.createOrder(new Order()); } } }   Everything else will be handled somewhere else   Can handle specific error conditions using catch with specific types   Can be done with AOP
  • 17. Generic Exception Handling public class MyHandlerExceptionResolver implements HandlerExceptionResolver { public ModelAndView resolveException( HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { return new ModelAndView("exceptionView", "exception", ex); } }   In the web layer   Handle all the (Runtime)Exceptions not handled elsewhere
  • 18. #3 Exception Handling public void someMethod() { Exception is not logged try { just written to stdout } catch (Exception ex) { operations might not notice ex.printStackTrace(); } try { } catch (Exception ex) { log.error(ex.getMessage()); Stack trace will be lost } try { } catch (Exception ex) { Exception is swallowed // should never happen comment suggests it would be } } serious error
  • 19. Impact   Related to #2: Bad Exception design will cause more bad exception handling   In the end you just get a message on the console and the application continues.   All kinds of wired behavior   i.e. exception is swallowed   You will have a hard time finding problems in the code   Potentially a huge problem – so worth its own explanation
  • 20. Solution   At least log exceptions including stack trace   Rethink: Is it really OK to continue after the exception is thrown? Might be better to let a generic handler handle it.   Introduce generic handling at least for RuntimeException (AOP, web front end, etc)   Enforce logging using Findbugs, PMD etc. public void someMethod() { try {   And: Improve the } catch (Exception ex) { exception design (#2) log.error(ex); } }
  • 21. #4   Table of packages and the relations between them   Everything in red is part of a cycle   This is actual code from an Open Source project
  • 23. Dependency Graph   Just a small part   Red line show circular references
  • 24. What is Architecture?   Architecture is the decomposition of systems in parts   No large or complex parts   No cyclic dependencies
  • 25. Normal Dependencies   B dependes on A, i.e. it uses classe, methods Component A etc.   Changes in A impact B   Changes in B do not impact A Component B
  • 26. Cyclic Dependency   B depends on A and A on B Component A   Changes in A impact B   Changes in B impact A   A and B can only be changed as one unit Component B   …even though they should be two separate units
  • 27. Bigger cyclic dependencies Component A Component B Component C
  • 28. #4: Architecture Mess   This is effectively just one big unstructured pile of mud   Maintenance will be hard   Concurrent development will be hard   Changes will have unforeseeable results
  • 29. Solution   Very hard if you have this state   Therefore: Manage dependencies from the start   Otherwise you are looking at a major restructuring of your application   …which might not be worth it   Effort for restructuring pays off by lower effort for maintenance   …might take a long time to amortize   Throwing away + redevelopment means that you have to migrate to a new solution - > complex and risky
  • 30. Metrics are not everything   If everything is in one package there will be no cycles   If packages for technical artifact (DAOs, services) might hide cycles in the functional decomposition   If interfaces and implementation are in the same package dependencies to the implementation might slip in.   A cycle with one dependency in the "wrong" direction is different from one with 40 in both directions.   Think about the structure – don't let metric fool you.
  • 31. #5 public class ServiceAdaptor { public void performService(OrderDTO orderDTO) { logger.trace("Entering performService"); try { if (orderDTO == null) { throw new NullPointerException("order must not be null"); } if (youAreNotAllowedToDoThis()) { throw new IllegalStateException( "You are not allowed to call this!"); } OrderEntity order = new OrderEntity(); order.setCustomer(orderDTO.getCustomer()); // ... service.performService(order); commandLog.add(new Command("performService", service,order)); } finally { logger.trace("Leaving performanceService"); } } }
  • 32. #5: Adaptor Layer   Adds to a service: •  Security •  Tracing •  Check for null arguments •  Log for all commands (auditing, replay…) •  Conversion from DTO to internal representation   Lots of boilerplate code for each service   Changes to tracing etc. hard: lots of methods to change
  • 33. Solution: Tracing with AOP   …or use Spring's predefined TraceInterceptor, DebugInterceptor etc. @Aspect public class TraceAspect { @Before("execution(* *..*Service.*(..))") public void traceBegin(JoinPoint joinPoint) { System.out.println("entering method " + joinPoint.getSignature().getName()); } @After("execution(* *..*Service.*(..))") public void traceEnd(JoinPoint joinPoint) { System.out.println("leaving method " + joinPoint.getSignature().getName()); } }
  • 34. Solution: Null Checks with AOP @Aspect public class NullChecker { @Before("execution(* *..*Service.*(..))") public void checkForNull(JoinPoint joinPoint) { for (Object arg : joinPoint.getArgs()) { if (arg==null) { throw new NullPointerException("Argument was null!"); } } } }   Security can be handled with Spring Security or AOP   Command log also possible
  • 35. What is left… public class ServiceAdaptor { public void performService(OrderDTO orderDTO) { OrderEntity order = new OrderEntity(); order.setCustomer(orderDTO.getCustomer()); // ... service.performService(order); } }   You should probably switch to Dozer   http://dozer.sf.net   Can externalize mapping rules   i.e. the layer can be more or less eliminated   Everything (mapping, security, tracing…) is now implemented in one place (DRY)   Often services just delegate to DAOs – same issue
  • 36. #6: No DAO public class SomeService { @PersistenceContext private EntityManager entityManager; public void performSomeService() { List<Order> list = entityManager. createQuery("select o from Order").getResultList(); for (Order o : list) { // ... if (o.shouldBeProcessed()) { o.process(); } } } }   We don't need to abstract away from JPA – it's a standard, right?
  • 37. #6: Even worse public class SomeServiceJdbc { private OrderDao someDoa; public void performSomeService() throws SQLException { ResultSet rs = someDoa.getOrders(); while (rs.next()) { //... } } }   Service depends on JDBC   …and throws SQLException   Persistence visible in the service layer and beyond
  • 38. Impact   Code is impossible to test without a database   …so no unit tests possible   Service depends on persistence – cannot be ported   How do you add data dependent security?   No structure
  • 39. Solution   Use a DAO (Data Access Object) •  Separate persistence layer •  Technical motivation   …or a Repository •  Interface to existing objects •  Non technical motivation: Domain Driven Design, Eric Evans   Basically the same thing
  • 40. Solution public class SomeServiceDAO { public void performSomeService() { List<Order> list = orderDao.getAllOrders(); for (Order o : list) { // ... if (o.shouldBeProcessed()) { o.process(); } } } }   Clear separation   Tests easy
  • 41. Solution: Test public class ServiceTest { @Test public void testService() { SomeService someService = new SomeService(); someService.setOrderDao(new OrderDao() { public List<Order> getAllOrders() { List<Order> result = new ArrayList<Order>(); return result; } }); someService.performSomeService(); Assert.assertEquals(expected, result); } }
  • 43. #7 Or bad tests   No asserts public class MyUnitTest { private Service service = new Service();   System.out: results are @Test checked public void testService() { manually Order order = new Order(); service.performService(order);   Tests commented out: } System.out.print(order.isProcessed()); They did not run any more and // @Test were not fixed // public void testOrderCreated() {   No mocks, so no // Order order = new Order(); // service.createOrder(order); real Unit Tests // }   No negative cases }
  • 44. Impact   Code is not properly tested   Probably low quality – testable code is usually better designed   Code is hard to change: How can you know the change broke nothing?   Design might be bad: Testable usually mean better quality   Code might be considered tested – while in fact it is not.
  • 45. Solution   Write proper Unit Tests! public class MyProperUnitTest { private Service service = new Service(); @Test public void testService() { Order order = new Order(); service.performService(order); Assert.assertTrue(order.isProcessed()); } @Test(expected=IllegalArgumentException.class) public void testServiceException() { Order order = new BuggyOrder(); service.performService(order); } }
  • 46. Wow, that was easy!
  • 47. The real problem…   The idea of Unit tests is over 10 years old   Still not enough programmer actually do real unit tests   Even though it should greatly increased trust and confidence in your code   …and make you much more relaxed and therefore improve quality of life…   Original paper: Gamma, Beck: "Test Infected – Programmers Love Writing Tests"   Yeah, right.
  • 48. Solution   Educate •  Show how to write Unit Test •  Show how to build Mocks •  Show aggressive Testing •  Show Test First / Test Driven Development   Coach / Review   Integrate in automatic build   Later on: Add integration testing, functional testing, FIT, Fitnesse etc.   …or even start with these
  • 49. What does not really work   Measuring code coverage •  Can be sabotaged: No Asserts… public class MyProperUnitTest { private Service service = new Service(); @Test public void testService() { Order order = new Order(); service.performService(order); } }   Let developers just write tests without education •  How should they know how to test properly? •  Test driven development is not obvious
  • 50. #8: public class OrderDAO { private SimpleJdbcTemplate simpleJdbcTemplate; public List<Order> findOrderByCustomer(String customer) { return simpleJdbcTemplate.query( "SELECT * FROM T_ORDER WHERE name='" + customer + "'", new OrderRowMapper()); } }
  • 51. Impact   Performance is bad: •  Statement is parsed every time •  Execution plan is re created etc.
  • 52. Impact: SQL Injection   Pass in a' or 't'='t'   Better yet: a'; DROP TABLE T_ORDER; SELECT * FROM ANOTHER_TABLE public class OrderDAO { private SimpleJdbcTemplate simpleJdbcTemplate; public List<Order> findOrderByCustomer(String customer) { return simpleJdbcTemplate.query( "SELECT * FROM T_ORDER WHERE name='" + customer + "'", new OrderRowMapper()); } }
  • 53. Solution public class OrderDAO { private SimpleJdbcTemplate simpleJdbcTemplate; public List<Order> findOrderByCustomer(String customer) { return simpleJdbcTemplate.query( "SELECT * FROM T_ORDER WHERE name=?", new OrderRowMapper(), customer); } }   … and white list the allowed characters in name   to avoid bugs in DB driver etc.
  • 54. #9   "What about Performance?"   "Well, we figured the response time should be 2s."   "How many request do you expect?"   "…"   "What kind of requests do you expect?"   "..."
  • 55. #9   Software is in the final functional test   Then the performance test start   Performance is too bad to be accepted   You can hardly do anything: •  Changes might introduce functional errors after testing •  Too late for bigger changes   The results might be wrong if the performance test is on different hardware than production.   You can't test on production hardware: Too expensive.
  • 56. Impact   You have to get bigger hardware •  Prerequisite: The software is scalable •  Otherwise: Tough luck   Worse: You can't go into production
  • 57. Solution   Get number of requests, expected types of requests, acceptable response times   Pro active performance management: •  Estimate performance before implementation •  …by estimating the slow operations (access to other systems, to the database etc) •  Measure performance of these operation in production   Get data from production   Practice performance measurements and optimizations before performance test
  • 58. #10 public class SomeService { private Map cache = new HashMap(); private Customer customer; public Order performService(int i) { if (cache.containsKey(i)) { return cache.get(i); } Order result; customer = null; cache.put(i, result); return result; } }
  • 59. #10 Multiple threads, memory leaks public class SomeService { The cache is filled – private Map<Integer,Order> cache = is it ever emptied? new HashMap<Integer, Order>(); private Customer customer; HashMap is not public Order performService(int i) { threadsafe if (cache.containsKey(i)) { return (Ordercache.get(i); customer is an } instance variable – Order result; multi threading will customer = null; ... be a problem cache.put(i, result); return result; } }
  • 60. Impact   System working in small tests   In particular Unit tests work   But production fails   …probably hard to analyze / fix   Almost only by code reviews   …or extensive debugging using thread dumps
  • 61. Solution   Use WeakHashMap public class SomeServiceSolution { to avoid private Map<Integer, Order> cache = memory leaks new WeakHashMap<Integer, Order>();   Synchronize public Order performService(int i) { synchronized (cache) {   Prefer local if (cache.containsKey(i)) { return cache.get(i); variables } }   Usually services Order result = null; Customer customer = null; can store most synchronized (cache) { things in local } cache.put(i, result); variables return result; } }
  • 62. Solution   Also consider ConcurrentHashMap   or http://sourceforge.net/projects/high- scale-lib
  • 63. Sum Up   #1 Weak Transaction   #8 Creating SQL Handling queries using String   #2 Exception Design concatenation   #3 Exception   #9 No performance Handling management   #4 Architecture Mess   #10 Multiple threads / memory   #5 Adaptor Layer leaks   #6 No DAO   #7 No or bad tests