Spring/Testing Training Jay Sissom. Topics Java Interfaces Service Oriented Architecture Spring Testing with junit.

Slides:



Advertisements
Similar presentations
Apache Struts Technology
Advertisements

Spring, Hibernate and Web Services 13 th September 2014.
Copyright © 2006 Korson-Consulting 1/219 Unit 4 Test First Development.
Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
© 2005, Cornell University. Rapid Application Development using the Kuali Architecture (Struts, Spring and OJB) A Case Study Bryan Hutchinson
Pragmatic Application Building: Step by Step Jay Sissom Principal Systems Analyst Indiana University
Software Testing. “Software and Cathedrals are much the same: First we build them, then we pray!!!” -Sam Redwine, Jr.
ASP.NET Programming with C# and SQL Server First Edition
Apache Struts Technology A MVC Framework for Java Web Applications.
Unit Testing Tips and Tricks: Database Interaction Louis Thomas.
Test Driven Development Derived from Dr. Fawcett’s notes Phil Pratt-Szeliga Fall 2009.
The Spring Framework: A brief introduction to Inversion of Control James Brundege
Intro to Spring CJUG - January What is Spring? “The Spring framework provides central transaction control of various objects.” This means that any.
Programmer Testing Testing all things Java using JUnit and extensions.
Struts 2.0 an Overview ( )
UNIT-V The MVC architecture and Struts Framework.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Chapter 10 EJB Concepts of EJB Three Components in Creating an EJB Starting/Stopping J2EE Server and Deployment Tool Installation and Configuration of.
Chapter 7 Designing Classes. Class Design When we are developing a piece of software, we want to design the software We don’t want to just sit down and.
NetArchive Suite Workshop 2011 Technical Track - Code refactoring with the Spring Framework.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Spring Overview, Application demo -Midhila Paineni 09/23/2011 Spring Overview, Application demo9/8/20151.
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
JUnit in Action SECOND EDITION PETAR TAHCHIEV FELIPE LEME VINCENT MASSOL GARY GREGORY ©2011 by Manning Publications Co. All rights reserved. Slides Prepared.
Design Patterns Phil Smith 28 th November Design Patterns There are many ways to produce content via Servlets and JSPs Understanding the good, the.
Data File Access API : Under the Hood Simon Horwith CTO Etrilogy Ltd.
LiveCycle Data Services Introduction Part 2. Part 2? This is the second in our series on LiveCycle Data Services. If you missed our first presentation,
Spring Framework. Spring Overview Spring is an open source layered Java/J2EE application framework Created by Rod Johnson Based on book “Expert one-on-one.
Introduction to Spring Matt Wheeler. Notes This is a training NOT a presentation Please ask questions Prerequisites – Introduction to Java Stack – Basic.
Software Engineering 1 Object-oriented Analysis and Design Chap 21 Test-Driven Development and Refactoring.
Effective Test Driven Database Development Gojko Adzic
JBoss at Work Databases and JBoss Chapter 4 Jeff Schmitt October 26, 2006.
(1) Unit Testing and Test Planning CS2110: SW Development Methods These slides design for use in lab. They supplement more complete slides used in lecture.
TEST-1 6. Testing & Refactoring. TEST-2 How we create classes? We think about what a class must do We focus on its implementation We write fields We write.
Unit Testing with JUnit and Clover Based on material from: Daniel Amyot JUnit Web site.
1 Legacy Code From Feathers, Ch 2 Steve Chenoweth, RHIT Right – Your basic Legacy, from Subaru, starting at $ 20,295, 24 city, 32 highway.
1 CSC/ECE 517 Fall 2010 Lec. 3 Overview of Eclipse Lectures Lecture 2 “Lecture 0” Lecture 3 1.Overview 2.Installing and Running 3.Building and Running.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
JUnit Don Braffitt Updated: 10-Jun-2011.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
Scalatest. 2 Test-Driven Development (TDD) TDD is a technique in which you write the tests before you write the code you want to test This seems backward,
Spring and DWR Frameworks for Rich Web Enterprise Application Thomas Wiradikusuma Presentation to the 20 th.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing.
S Ramakrishnan1 Systems V & V, Quality and Standards Dr Sita Ramakrishnan School CSSE Monash University.
(1) Test Driven Development Philip Johnson Collaborative Software Development Laboratory Information and Computer Sciences University of Hawaii Honolulu.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
Kansas City Java User’s Group Jason W. Bedell July 12, 2006
Test a Little, Code a Little Colin Sharples IBM Global Services New Zealand Colin Sharples IBM Global Services New Zealand.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Automated Testing in Sakai Testing applications and services in isolation and in context Josh Holtzman, UC Berkeley David Haines, University of Michigan.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Unit Testing with FlexUnit
Apache Struts Technology A MVC Framework for Java Web Applications.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2016 ©
Software Engineering 1 Object-oriented Analysis and Design Applying UML and Patterns An Introduction to Object-oriented Analysis and Design and Iterative.
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
Mapping Designs to Code. It specify how to map the design into object oriented language The UML artifacts created during the design work, the interaction.
Best 3 Software Development Languages. Hibernate Training Hibernate is a high-performance object-relational mapping tool and query service. Hibernate.
Unit Testing.
Module Road Map Refactoring Why Refactoring? Examples
Distribution and components
Intro to Spring CJUG - January 2013.
History, Characteristics and Frameworks
Testing a persistence layer
CSE 303 Concepts and Tools for Software Development
CS 240 – Advanced Programming Concepts
Developing and testing enterprise Java applications
Designing For Testability
Object-Oriented PHP (1)
Presentation transcript:

Spring/Testing Training Jay Sissom

Topics Java Interfaces Service Oriented Architecture Spring Testing with junit

Exercise 1 Check out FPS/TRAINING/INTERFACE1 Open edu.iu.uis.Main.java Create instances for each pet Put them all in a collection Iterate through the collection and print each pet’s name and make it speak (Don’t modify Cat & Dog classes) Hint: instanceof

Java Interface An Interface is a special Java class that defines behavior but doesn’t implement the behavior It defines what another object will do, not how it does it It is used to declare methods that an object must implement Use of interfaces allows objects to be dependant on behavior, but not specific object instances

Java Interface By using Interfaces, you don’t hard code which object must provide a service for you The object providing the service can be any object that implements the required interface

Java Interface An example is Collection. A Collection must allow you to:  Add items  Clear all items  Remove items  Get the size  Get an iterator to all members  (among other things)

Java Interface Many objects implement the Collection interface  ArrayList  Vector  LinkedList  And the list goes on….

Java Interface You can create your own Java interface: public interface Worker { public Collection getData(); public void doWork(); }

Java Interface Any number of classes can implement your interface: public class MyWork implements Worker { public Collection getData() { return new ArrayList(); } public void doWork() { // Pretend I’m working }

Java Interface Your interface can be used in place of an object name: public Worker getMyWorker() … public void doStuff(Worker w) … When doing this, your code isn’t dependent on a single implementation of Worker. Any implementation will do.

Exercise 2 Use interface1 project (or check out FPS/TRAINING/INTERFACE1ANSWER if you didn’t finish Exercise 1) Create a Pet interface that defines the common functionality in Cat & Dog Change Cat & Dog to implement this interface Change Main to use the interface instead of specific instances Extra Credit: Add a Parrot object and use it

Inheritance Inheritance is a parent child relationship between classes Children inherit a parent’s functionality Animal public String speak(); public String getName(); Dog

Inheritance Inheritence implies that all children will have the functionality defined in the parent You have to be very careful when designing inheritance Animal public String speak(); public String getName(); AntDonGrinstead

Solution with Interfaces Using interfaces in this case would be more accurate Named > public String getName(); AntDonGrinstead Speaker > public String speak();

Inheritance/Interfaces IssueInterfaceInheritance How Many per classAny numberOne parent per child Inherit method signatures Yes Inherit functionalityNoYes

Interface Conclusion A Java Interface defines what implementing objects do, not how they do it Using interfaces will decouple your code from dependant objects. This will make it easier to maintain the code in the future

Exercise 3 Check out FPS/TRAINING/INTERFACE3 Create an implementation of OrderCalculator that calculates sales tax as 6% if from Indiana, 0 if from another state Shipping is $20 if another state, $15 if Indiana Change Main to use this interface Modify the interface to add this method: public double getOrderTotal(Order o); that returns the total of the order with tax & shipping Modify Main to use this method Make sure you modify both implementations to implement this interface

Interfaces Pt 2 We still had to put the name of the implementation class in our last example If we used that throughout our application, we’d need to change it everywhere This is still a problem

Interfaces Pt 2 A solution is to create a new class that has a method to return the implementation we want public OrderCalculator getInstance(); This allows us to specify our implementation once for the whole app This is called the Factory pattern

Exercise 4 Use interface3 project Create OrderCalculatorFactory class that has one method public OrderCalculator getInstance(); This method should return an instance of your order calculator class Change Main to use the factory

Interfaces Pt 3 Now we specified the implementation class in one place in our app This is better, but it would be best if the implementation class name wasn’t in Java code We can put this class name in a properties file. The factory can read the properties file to determine the class name Now the class name isn’t in compiled Java code. See FPS/TRAINING/INTERFACE4ANSWER2 for an example

Interfaces Pt 3 Now we need a Factory, Interface and properties file for each class This is too much work! We could build a Factory framework so we need one factory and properties file for our app Or we could use an open source framework called Spring

Spring Spring Mission Statement  J2EE should be easier to use  It's best to program to interfaces, rather than classes. Spring reduces the complexity cost of using interfaces to zero.  JavaBeans offer a great way of configuring applications.  OO design is more important than any implementation technology, such as J2EE.  Checked exceptions are overused in Java. A framework shouldn't force you to catch exceptions you're unlikely to be able to recover from.  Testability is essential, and a framework such as Spring should help make your code easier to test.

Spring Spring can replace our factory classes and properties file All classes can be defined to spring and we don’t need to write custom factories See FPS/TRAINING/SPRING1ANSWER

Spring Objects are defined as “beans” in a spring xml file: The object is accessed via the beanFactory: OrderCalculator oc = (OrderCalculator)factory.getBean("OrderCalculator");

Execise 5 Check out FPS/TRAINING/SPRING2 Refactor NewOrderCalculator to use MemorySalesTax object Use Spring as the factory to find the object (the beanFactory is provided for you)

Dependencies OrderCalculator depends on the SalesTax object to do its work Main depends on OrderCalculator When an object needs another to do its work, that is a Dependency Spring helps satisfy dependencies Using Interfaces makes it flexible

Dependencies To satisfy dependencies in our code we can:  Create the dependent objects using new  Use a Factory to get them  Have something external to the object create them for us The last option is called Dependency Injection or Inversion of Control

Inversion of Control There are three types of IoC  Constructor Based  Setter Based  Getter Based

Constructor Based IoC All dependent objects are passed on the constructor All dependancies are satisfied when the object is created If you have lots of dependancies, you have a huge constructor

Setter Based IoC All dependent objects have a setXXX method The factory will call these for each dependent object Good when there are lots of dependencies This documents the dependencies better than Constructor based IoC

Getter Based IoC Each object needs access to a container The object calls get methods on the container to get dependencies This is the way we have been using Spring Our code now has a dependency on Spring which may be a problem

Spring IoC Spring supports all three IoC types  Getter - using BeanFactory  Setter - using bean.xml  Constructor - using bean.xml The most popular is Setter based IoC This is the recommended way to handle dependencies

Spring Setter IoC Dependencies are mapped in the bean xml file  Update the xml to show the dependency  Create a setter method in the bean  The setter method saves the dependency to use it in the future

Spring Setter IoC Update the xml to show the dependency

Spring Setter IoC Create a setter method in the bean & save the dependency to use when necessary private SalesTax salesTax; public void setSalesTax(SalesTax st) { salesTax = st; }

Exercise 6 Modify the spring2 project to use setter injection in OrderCalculator Hint: You can remove the BeanFactory code in NewOrderCalculator because it isn’t necessary anymore FPS/TRAINING/SPRING2ANSWER2

Spring with Struts There are a few steps required to get Spring working with Struts  Starting up Spring  Location of bean xml  Spring/Struts integration

Starting up Spring Spring starts up with a servlet listener This code needs to be in web.xml org.springframework.web.context.ContextLoaderListener

Location of bean xml Spring looks for beans in /WEB-INF/applicationContext.xml This can be changed by adding the following in web.xml contextConfigLocation /WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml

Spring/Struts integration Spring can handle IoC in Struts Actions Define dependencies in xml file Spring calls setter methods in Struts Actions

Spring/Struts integration Define Struts plugin in struts-config.xml Spring looks in /WEB-INF/action-servlet.xml for Struts action bean definitions Note: action is the name of the Struts Servlet in web.xml

Spring/Struts integration The type of each action in struts-config.xml should be org.springframework.web.struts.DelegatingActionProxy The dependencies and actual type should be defined in action-servlet.xml Note: /path needs to match path in in struts-config.xml

Spring/Struts integration Struts Actions are defined in action- servlet.xml Other beans are defined in applicationContext.xml Struts actions can access beans defined in applicationContext.xml applicationContext.xml beans can’t access Struts actions

Exercise 7 Check out FPS/TRAINING/STRUTS1 Setup Spring for the application  Put beans in applicationContext.xml & action- servlet.xml  Put setter methods in beans  Update struts-config.xml for Spring  Update web.xml for Spring

Application Testing Unit Testing – Test each object as it is written Functional Testing – Test each use case to make sure it works properly Usability Testing – Test the app to make sure users understand it Load Testing – Make sure the application will perform properly under a load

jUnit Unit Tests are a series of tests that verify each component of your application jUnit is a framework to help standardize these tests jUnit can help automate tests so it is easy to see if a component works Open Source Framework Integrated into Eclipse and ant

Why Unit Test? Find bugs soon after code is written Save other team members’ time Prove that finished code works Make future maintenance easier Example of how to use code

Unit testing goals Each class has tests for all public methods Tests not only test successes, but also test failures Tests are organized so they are easy to run Tests are run often Each test is completely independent of other tests Each time a bug is found, write an additional test to check for that bug, then fix the bug

jUnit Concepts TestCase – a series of related tests  All the tests for an object  All the tests for a method TestSuite – a series of related test cases  All tests for a package  All tests for a use case  All tests for an application

jUnit Concepts TestRunner – jUnit code that runs tests  Command line  Swing  Eclipse

jUnit Addons Dbunit – code to initialize a database to a known state before testing Struts test case – Test Struts specific code using mock objects Cactus – Test HTTP applications using mock objects HttpUnit – Test HTTP applications based on an embedded servlet container

Writing jUnit tests Subclass junit.framework.TestCase Create a constructor with a single String parameter. Call super(string) in this constructor Write tests in methods that return void and start with test as their name Call fail, assertX in tests as necessary

Writing jUnit tests protected void setUp() is called before each test method protected void tearDown() is called after each test method These can be used to setup and cleanup the environment required for each test

Test success/failure assertX methods test for the correct values. Examples:  assertTrue/assertFalse  assertNull/assertNotNull  assertEquals Fail() method stops the test and marks it as a failure Throwing an uncaught exception marks the test as a failure

Test success/failure The assertEquals method takes the following arguments  String = a message that is printed if the assertion fails  Expected value = the value expected  Test value = the value to test Double & Float comparisons take a 4th argument - a precision range

Example test /** * Test searching for someone that doesn't exist **/ public void testGetPerson1() throws Exception{ BusinessLogic bl = (BusinessLogic)beanFactory.getBean(“BusinessLogic”); Person p = bli.getPerson("Unknown"); assertNull("Unknown person should be null",p); }

Exercise 8 Check out FPS/TRAINING/JUNIT1 Create a series of junit tests for the UsaTax2004Calculator object See for the official tax rates There is at least one bug in the object

Best Practices Make each test method only test one feature Test for success and failure Build a test suite that runs all your tests When a bug is found, write a test to find the bug, then fix the bug Write tests that don’t depend on external systems (database or GDS)

Best Practices Tests shouldn’t be dependent on other tests Don’t test things that can’t break Put tests in their own package Read the jUnit FAQ

jUnit Summary jUnit helps you create higher quality software Time spent by writing tests will be recovered many times over during future maintenance

Test Driven Development TDD is a standard for Kuali development and may be a future standard for UIS This completely changes the way you develop code Tests are developed before production code

Test Driven Development When using TDD, here is how to build functionality:  Write a single test  Compile it. It shouldn't compile, because you haven't written the implementation code it calls  Implement just enough code to get the test to compile  Run the test and see it fail  Implement just enough code to get the test to pass  Run the test and see it pass  Refactor for clarity and "once and only once"  Repeat

Test Driven Development Test Driven Development (a.k.a. Test-first design ) is one of the core programming practices of XP. Many of us have learned over the years the value of writing automated tests for our code. Many of us have also learned the difficulty of writing tests after code is already in place. Test-first design takes a different, extreme approach to ensure that we test all code, all the time. The practice of test-first design begets a changed mindset: we write tests not as an afterthought to ensure our code works, but instead as just part of the everyday, every-minute way of building software. Instead of writing our detailed design specifications on paper, we write them in code. Instead of first striving to perfectly design a system on paper, we use tests to guide our design. Instead of coding for hours at a stretch, only to find our planning went awry, we use test-first design to pace ourselves, always assuring that we are moving forward correctly with each passing minute.

The steps Write a test that specifies a tiny bit of functionality Ensure the test fails (you haven't built the functionality yet!) Write only the code necessary to make the test pass Refactor the code, ensuring that it has the simplest design possible for the functionality built to date

The rules Test everything that can possibly break Tests come first All tests run at 100% all the time

The benefits Code is written so that modules are testable in isolation. Code written without tests in mind is often highly coupled, a big hint that you have a poor object-oriented design. If you have to write tests first, you'll devise ways of minimizing dependencies in your system in order to write your tests. The tests act as system-level documentation. They are the first client of your classes; they show how the developer intended for the class to be used.

The benefits The system has automated tests by definition. As your system grows, running full regression tests manually will ultimately take outrageous amounts of time. Development is paced. We specify tiny bits of functionality in our tests, then write a small amount of code to fulfill that specification. Rinse, repeat. Tiny means seconds to a few minutes. The code base progresses forward at a relatively constant rate in terms of the functionality supported.

Example Roman Number converter

Quick Review Using Java interfaces makes our code more flexible Spring is a Factory that lets us change implementations of objects without recompiling jUnit is a framework to help developers test objects TDD is really great and we’re all going to love it  We WILL use it on the next exercise!

Exercise 8 Create a Bowling Score Calculator Use Test Driven Development

Data Access With Spring Spring provides services to make writing database code easier  Automatic connection handling  Simplified data access code using templates  Declarative transaction management

Auto Connection Handling Spring can manage your database connection for you It is NOT a connection pool, it uses the container’s connection pool It will retrieve connections when you need them and close them when you are done This means less code for you to write

Template Spring provides templates for Hibernate, iBatis, JDBC, OJB and JDO A template provides  Connection management  Exception translation

Template DAO objects can use this template by extending a DaoSupport class For OJB, it is PersistenceBrokerDaoSupport Call getPersistenceBrokerTemplate() in code to access the template

Template Methods available  store() - store a persistent object  delete() - delete a persistent object  getCollectionByQuery() - get a collection  getObjectByQuery() - get an object  There are others Usually updating the database requires a one line method: public store(Object o) { getPersistenceBrokerTemplate().store(o); }

Example Sales Tax Application FPS/TRAINING/DAO1

Exercise 9 Check out FPS/TRAINING/DAO2 Write an OJB DAO according to the interface StateDao Make sure to update the applicationContext file Run the web app to see if it worked

Testing with Mock Objects A Mock object is like an acting double We use Java interfaces so we can swap out functionality This allows us to swap out dependent objects with Mock objects for testing With mock objects, we can test the business logic tier without talking to other systems

Why Mock Objects The real object has nondeterministic behavior The real object is difficult to set up The real object has behavior that is hard to trigger The real object is slow Others… Pragmatic Unit Testing

Mock Objects There are Mock object frameworks  jMock  EasyMock  MockCreator  Probably others OR You can create your own Mock objects

Mock Object A Mock object can be a simple Java object that implements the correct interface A DAO Mock Object can implement the correct interface, then each method is implemented as simply as possible You can implement the methods as needed by your test cases

Mock Objects Insert some really cool exercise here…

Declarative Transactions Spring can coordinate transactions for you in one of two ways  Programatic - in Java code  Declarative - in the applicationContext xml Using declarative transaction means less code to maintain

Declarative Transactions <bean id="pdpReferenceService” class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> PROPAGATION_REQUIRED Example from applicationContext.xml

Declarative Transactions <bean id="pdpReferenceService” class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> PROPAGATION_REQUIRED Example from applicationContext.xml Class we write

Declarative Transactions <bean id="pdpReferenceService” class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> PROPAGATION_REQUIRED Example from applicationContext.xml It calls DAOs for data access

Declarative Transactions <bean id=" pdpReferenceService ” class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> PROPAGATION_REQUIRED Example from applicationContext.xml Other beans access our code via this id

Declarative Transactions <bean id="pdpReferenceService” class=" org.springframework.transaction.interceptor.TransactionProxyFactoryBean" > PROPAGATION_REQUIRED Example from applicationContext.xml Spring provides a proxy class that handles transactions

Declarative Transactions <bean id="pdpReferenceService” class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> PROPAGATION_REQUIRED Example from applicationContext.xml Spring’s proxy class calls our real class

Declarative Transactions <bean id="pdpReferenceService” class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> PROPAGATION_REQUIRED Example from applicationContext.xml We control the type of transaction

Transaction Properties PROPAGATION_MANDATORY Support a current transaction, throw an exception if none exists. PROPAGATION_NEVER Execute non-transactionally, throw an exception if a transaction exists. PROPAGATION_NOT_SUPPORTED Execute non-transactionally, suspending the current transaction if one exists. PROPAGATION_REQUIRED Support a current transaction, create a new one if none exists. PROPAGATION_REQUIRES_NEW Create a new transaction, suspending the current transaction if one exists. PROPAGATION_SUPPORTS Support a current transaction, execute non-transactionally if none exists. * Not all are supported by every transaction manager.

Transaction Properties Properties can be applied to methods based on wildcards PROPAGATION_REQUIRED PROPAGATION_MANDATORY PROPAGATION_REQUIRED,readOnly

Transactions If necessary, a transaction will  Begin before the method is called  Commit after the method is finished  Rollback if the method throws a Runtime exception (not a checked exception) Rollback behavior can be controlled in the applicationContext file

Transactions You can control rollback & commit on specific transactions by listing them in transaction attributes PROPAGATION_REQUIRED, -MyCheckedException PROPAGATION_REQUIRED, +NullPointerException - means rollback, + means commit

Exercise 10 Check out FPS/TRAINING/SERVICE1 Write an implementation of OrderService Apply these business rules for a save  Use the correct part price based on quantity  If the total for a single part is > $100 give a 5% discount  If the total for a single part is > $1000 give a 6% discount  Remember TDD? Use Mock Objects for DAO’s when testing the service

Architecture Our systems should be designed with the following in mind:  Readability  Flexibility  Maintainability  Testable

Architecture The 3 tier architecture helps us meet those some of these goals Data AccessBusiness LogicUser Interface

Architecture Readability - All code of a specific type (data access, business logic, user interface) is in it’s own location Flexibility - ? Maintainability - See Readability Testable - ? We can do better

Architecture OJB or JDBC DAO OJB or JDBC DAO Service (business logic) Service (business logic) Struts Forms Struts Forms Struts Actions Struts Actions Business Objects Service InterfaceDAO Interface

Architecture Readability - Same as before Flexibility - Each tier talks to an interface for the other tier. The implementation can change all it wants Maintainability - See Readability Testable - We can test each tier independently by using Mock objects because they communicate via interfaces

DAO - Data Access Object DAO’s talk to datasources to create, retrieve, update and delete data No business logic allowed All JDBC, SQL and/or OJB features should be in these object types and no other object types Generally one DAO per table

DAO Interface Java interfaces for DAO objects Services should only be aware of interface, not actual DAO implementation The interface allows the use of Mock objects when testing

Service Used for business logic Call DAO’s and other Services to access data Should not contain SQL, JDBC or web specific information Each method will be a single database transaction

Service Interface Java interfaces for Service objects The interface allows the use of Mock objects when testing

Struts Actions Web user interface logic No business logic Call Services for business logic Generally should only call a single method in a service object

Struts Forms Only used when a user posts a form to the server All user edited fields are String properties Validation should just validate that fields have the proper format Validation in the Struts Action should call business logic Form objects can contain Business Objects

Business Object A Business object is a Javabean (POJO) There should be a business object for each entity in the application Business objects can be used in any tier of the application In most cases, Business objects will be OJB data objects

Isolation Each tier should be isolated from other tiers A tier shouldn’t have knowledge of how a different tier is implemented A tier should only communicate to another tier through a Java interface The Spring framework can handle dependencies so each tier is truly isolated

Dependency Injection Spring will call set methods on managed objects so other objects don’t need to know details about how a dependant object works The dependencies are built into Spring’s context.xml file

Declarative Transactions Spring will manage transactions if they are defined in the context.xml No code is required to begin, rollback or commit a transaction No code is required to open and close database connections Spring handles this automatically No code means you can’t forget it!

Declarative Transactions Each method call into a service object is a transaction Spring automatically begins the transaction before the method call and ends it after If the method throws a runtime exception, Spring rolls back the transaction

Exceptions Runtime Exceptions  Use when situation is non-recoverable Checked Exceptions  Use when situation is recoverable Best Practice - fail as soon as possible  The closer the failure to the problem, the easier it is to find the problem Best Practice - fail big  Hidden failures make it more difficult to fix the problem