Efektivní vývoj v Java EE a využití návrhových vzorů (JEEDP) Petr Adámek [email protected] Content

• Introduction • Java EE platform • Component Design • JavaBeans • Enterprise Applications Design • Persistence Layer • Business Layer • Presentation Layer • Application Development and Maintenance Introduction: Lector

• Ing. Petr Adámek • Commercial programming since 1994 • Java / Java EE developer since 2001 • Java / Java EE lector at FI MU since 2002 • Java Program Coordinator & Java Development Technical Lead at EmbedIT since 2012 Introduction: You

• Your name • Your experience • Your expectations Resources

Effective Java (2nd Edition) Joshua Bloch http://amazon.com/dp/0321356683/ Resources

Clean Code: A Handbook of Agile Software Craftsmanship Robert C. Martin http://amazon.com/dp/0132350882/ Resources

Refactoring: Improving the Design of Existing Code Martin Fowler, , John Brant, William Opdyke, Don Roberts http://amazon.com/dp/0201485672/ Resources

Design Patterns: Elements of Reusable Object-Oriented Software Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides http://amazon.com/dp/0201633612/ Resources

Design Patterns: Explained Simply Alexander Shvets https://sourcemaking.com/design-patterns-ebook Resources

Patterns of Enterprise Application Architecture Martin Fowler http://amazon.com/dp/0321127420/ Resources

Core J2EE Patterns: Best Practices and Design Strategies (2nd Edition) Dan Malks, John Crupi, Deepak Alur http://amazon.com/dp/B000OZ0N4E/ Resources

• https://github.com/petradamek/PV168/tree/master/GraveManager- Backend • https://sourcemaking.com/ – design patterns, anti-patterns, refactoring The Most Important Rule Basic rules for writing maintainable code

• Read Effective Java  • Focus on simple and clear code, avoid preliminary optimization • Follow code conventions (identifiers, indentation, etc.) • Use comprehensible identifiers • Write the code such way that comments are not needed • Avoid duplicate code • Use existing libraries and Java Core API, don’t reinvent the wheel • Don’t overuse inheritance, use it only for generalization/specialization • Use exceptions only for handling errors or non-standard situations • Be defensive, always check if method contract is fullfiled Java EE Platform What is Java EE

• Platform for modern enterprise system development • Industry standard (JCP) • Current version is Java EE 7 (JSR 342), Java EE 8 (JSR 366) will be released at the end of 2017 Characteristics of modern IS

• Complex and large systems • Integrated with other systems inside and outside the organization • Adaptability to different requirements of various customers • Multiple platforms support • Support for big amount of users (especially in case of web applications) • Security • Quality and reliability Development process requirements

• Fast development • Easy maintenance • Easy extensibility and adaptability • Easy integration with other systems • Support for agile development • Support for team and multi-team development • Portability and compatibility (various HW, OS, DB, tools, application servers, etc.) • Scalability • Security • Easy to test Basic Concepts

• Infrastructure • Modularity • Independence and low invasiveness • Declarative approach • Convention over configuration Infrastructure

• Developer should be focused on problem domain, he should not be spending time and effort with general problems which are not specific for given application • Architecture, authentication, authorization, transaction management, data persistence, communication and integration, remote access, presentation layer architecture, localization, etc. • Java EE platform and frameworks are providing such infrastructure • Never implement your own framework! Modularity

• Application should be assembled from cooperating components • Components should be • Loosely coupled • Reusable • Coherent • Well tested • Well documented (contract described with JavaDoc) • With well designed components, we can easily change and adjust application behavior • By changing the component • By changing the component configuration • By changing connection between components Independance and low invasivness

• Components should be as less dependent as possible not only between each other, but also on specific technologies and frameworks (at least at interface level) • Such components are • Easy to test • Well maintainable • Better reusable • POJO (plain old java object) concept Declarative approach

• Some aspects of program behavior are not defined with traditional imperative code (i.e. by describing steps how to do it), but by required behavior specification (i.e. what we want to achieve) • The code is more clear and better understandable • Suitable for transaction management, authorization, automatic conversions and/or mappings, etc. • Declaration could be defined • By annotation (since Java 5) • By deployment descriptor Imperative TX management

public void someMethod() { UserTransaction transaction = context.getUserTransaction(); try { transaction.begin(); doSomething(); transaction.commit(); } catch (Exception ex){ try { transaction.rollback(); } catch (SystemException syex){ throw new EJBException ("Rollback failed: " + syex.getMessage()); } throw new EJBException("Transaction failed: " + ex.getMessage()); } } Declarative TX management

@TransactionAttribute(TransactionAttributeType.RequiresNew) public void someMethod() { doSomething(); } Convention over configuration

• Each configurable parameter has some suitable default value, developer only needs to specify unconventional aspects of the application • The amount of decisions which developer has to make is decreased. • Increased efficiency • Less steep learning curve (developer don’t need to know all details to start with simple application) • Developers are motivated to follow conventions • Propagated by Ruby on Rails Convention over configuration: Examples

• Directory structure in Maven • Table name corresponds to entity class name in JPA • Column name corresponds to attribute name in JPA Old versions of Java EE platform

• First versions (prior Java EE 5) were focused especially on infrastructure and technologies • Development easiness was underestimated • Complex technologies with complicated use • Steep learning curve • Need to use complex tools • This lead to frustration of developers and to inventing alternative approaches and technologies (Hibernate, Spring) • Changed in Java EE 5 • Inspired with Spring, Hibernate, etc. • Annotations • POJO components Java EE Architecture

Client Tier computer

Client PresentationTier Desktop Mobile Web application application Browser

Web tier

Servlets Application server WS JSF JSP

Business Business Tier Logic

EJB Spring

Data JDBC ORM Persistance

EIS Tear server DB/IS

Database Other IS Container

• Provides runtime environment for components • Controls component lifecycle, provides services • Example • Servlet container • Portlet container • EJB container • CDI container • Spring IoC container Application Server

• Provides runtime environment for the application • Usually consists of • Servlet Container • EJB Container • Supports (or could support) • Resource management (e.g. database connections) • Transaction Management • Authentication and Authorization • Clustering (load balancing, high availability) Application Server Vendors

• Open Source – fully compliant • JBoss • Glassfish • TomEE (Web profile only) • Open Source – only servlet container • Tomcat • Jetty • Proprietary • WebSphere (IBM) • WebLogic (Oracle, former BEA) Component Design SOLID principles

• Single Responsibility • Open-Closed • Liskov Substitution • Interface Segregation • Dependency Inversion Well designed component

• Single Responsibility (single component = single task) • Loosely Coupled (minimum dependencies) • Well Defined Contract (well documented) • Well Tested (unit tests) Single Responsibility

• Single component should have just single responsibility (single task) • Such component is easy to maintain, easy to test, more flexible and less dependent on other components • When making components loosely coupled, start with making them simple (more responsibility means more dependencies). • Component following single responsibility principle is high coherent Example

• A is transitively dependant on Printer and File even it needs just to write to screen. Loosely coupled components

• Amount of dependencies between components is minimized • Components don't depend on specific implementations, but on general interfaces • Transitive dependencies (can be reduced by separating interface and implementation) • Big problem are especially circular dependencies • Too many dependencies indicates bad design Simple example

// Tight Coupled public interface ProductService { void addProducts(ArrayList products); LinkedList getAllProducts(); }

// Loosely Coupled public interface ProductService { void addProducts(List products); List getAllProducts(); } More Complex Examples

• Component quiz • PropertiesService External Dependencies

• Try to make component independent on specific technologies, frameworks or libraries (at least at the API level). • Use general types, exceptions and annotations instead of the proprietary ones (e.g. use @Inject instead of @Autowired). • Avoid always dependencies of API on another layer technology (e.g. using classes from frontend frameworks in business API) Bad Examples

public interface ClientEventService { void saveLoginEvent(String userName, HttpServletRequest request); } public interface ReportService { List getDailyReportData(); } public void ContractService { void create(Contract contract) throws SQLException; } Well Defined Contract

• What should be defined • Component behavior in all possible situations (especially in non-standard and erroneous ones) • Entry conditions • Thread safety • Described with javadoc Exceptions

• Use general exceptions for contract violation • IllegalArgumentException • IllegalStateException • UnsupportedOperationException • Consider to use checked/unchecked exception • Unchecked exception for contract violation or programmer mistake (could occur anywhere) • Checked exception for situations which should be caller aware of Well defined contract example

package net.homecredit.biometrics.fingerprints.properties; * static PropertyValue.

* /** * @throws IllegalPropertyValueException when string representation of property * This interface represents some property value. PropertyValue can be static or * value is invalid and it can't be converted to appropriate type or when * dynamic, according to the implementation. Static value is implemented as * the value is {@code null} although {@code null} values are not allowed * immutable class and its {@link #get()} method is always returning the same * for given property. * value. Dynamic value can be backed by some properties store and * @throws PropertyNotFoundException when the property is not available anymore. * {@link #get()} method is always returning the actual value in the properties * @return current value of the property * store. */ * T get() throws IllegalPropertyValueException, PropertyNotFoundException; * @author [email protected] * @param property value type */ /** public interface PropertyValue { * Methods is returning current property value as string. * Calling this method is equivalent of {@code String.valueOf(this.get())}. /** * Result can be different than the string representation of property * Returns current value of associated property. Value can be {@code null} if * value used for storing into underlying properties repository! * appropriate {@link PropertyDefinition} allows that. * * * @return current property value as string *

If the PropertyValue is dynamic, current value is loaded as string from */ * underlying properties store and converted to property value type with @Override * appropriate {@link PropertyConvertor}. If the conversion fails String toString(); * due illegal string representation of property value, * {@link IllegalPropertyValueException} is thrown. If the value is {@code null} /** * although {@code null} values are not allowed, * Returns true if this PropertyValue is dynamic. * {@link IllegalPropertyValueException} is thrown as well. If the property * * is not available anymore (e.g. because it has been deleted from underlying * @return true if this PropertyValue is dynamic, false otherwise. * properties store), {@link PropertyNotFoundException} is thrown.

*/ * boolean isDynamic(); *

{@link IllegalPropertyValueException} and * {@link PropertyNotFoundException} should be never thrown for } Reusability

• Avoid duplicate code, prefer to reuse components • If the code is not exactly the same, but just similar, make the component more general and reusable (Design Patterns, Effective java) • But be careful with if-statements – Replace Conditional with Polymorphism (https://sourcemaking.com/refactoring/replace- conditional-with-polymorphism) • On other hand, avoid making universal components with functionality which is not currently needed Refactoring

• Changing code structure without changing functionality • Two hats principle (don't change the structure and functionality at the same time) • Do not refactor a part of the code until it's well covered by all relevant kinds of testing. • Catalog of Refactorings is useful also for writing new code. Immutable classes

• Class which does not change its state • All fields all final • No methods for changing state • Final class (non compatible with class proxy based AOP) • Nobody can change the state (intentionally or by accident) • No defensive copies are needed • Thread safe by design • Example – String class • See item 15 in Effective Java Best Practices

• Make components as simple as possible, follow single responsibility principle • Separate interfaces from implementation, minimize dependencies • Try to make component independent on specific technology (at least at API level). • Define and document well the contract • Don't hesitate to refactor component • Consider making the component immutable • Read Effective Java and Refactoring: Improving the Design of Existing Code. Component Lifecycle and Dependency Management

• Component is not responsible for required resources, it expects that all resources will be provided by user of the component • Hollywood principle – Don't call us, we call you • Helps to reduce dependencies Example

public class ContractServiceImpl implements ContractService {

private final ContractDao contractDao;

public ContractServiceImpl() { this.contractDao = new ContractDaoImpl(); } } public class ContractServiceImpl implements ContractService {

private final ContractDao contractDao;

public ContractServiceImpl(ContractDao contractDao) { this.contractDao = contractDao; } }

• Implementation of IoC principle • Resources can be injected with • Field • Property • Constructor (preferred; allows to design components to be immutable and fully initialized since the instance is created) • JSR 330: Dependency Injection for Java (@Inject, etc.) • Qualifiers Example

public class ContractServiceImpl implements ContractService {

// Field injection @Inject private ContractDao contractDaoA;

// Constructor injection private final ContractDao contractDaoB;

@Inject public ContractServiceImpl(ContractDao contractDao) { this.contractDaoB = contractDao; }

// Property injection private ContractDao contractDaoC;

@Inject public void setContractDao(ContractDao contractDao) { this.contractDaoC = contractDao; } } Java Naming and Directory API

• JNDI is standard way how to retrieve resources • Allows to separate application from system configuration (database, external services, JMS, etc.) JNDI Resources

public class ContractDaoImpl implements ContractDao {

private final DataSource dataSource;

public ContractServiceImpl() { Context context = new InitialContext().lookup("java:/comp/env"); this.dataSource = (DataSource) context.lookup("jdbc/contractDb"); } } public class ContractDaoImpl implements ContractDao {

@Resource("jdbc/contractDb") private final DataSource dataSource; } Lifecycle Management

• Lifecycle management (creating and destroying components) is usually handled by some container, which is also providing Dependency Injection and Resource management. • EJB container, Servlet container, CDI container, Spring container, etc. • Configured with annotations, xml files, JavaConfig, etc. JavaBeans components JavaBean Component

• Concept of components introduced by Sun Microsystems • Support for handling by tools (e.g. User Interface designer) • Any class following these rules: • Zero-argument constructor • Properties accessible with get/set methods • Serializable • Events Properties

• Accessible with get/set method • read/write (both get and set methods) • read-only (only get method) • write-only (only set method) • Get method for property with Boolean type has is prefix • isEmpty() • Property can be logical (no such field exist in the class) • isEmpty() on Collection Serialization

• Mechanism for converting object into sequence of bytes and vice versa • Serializable interface • Version defined as long serialVersionUUID • Default serialized form (fields not marked as transient) • Custom serialized form • readObject(ObjectInputStream) • writeObject(ObjectOutputStream) • See items 74 – 78 in Effective Java Events

• Event Object • object representing an event • e.g. PropertyChangeEvent • Event Listener • Interface which is implemented by class which will receive the notification • Usually implemented as anonymous local class , lambda expression (Java 8) or method reference (Java 8) • e.g. PropertyChangeListener • Example Enterprise Application Design Application architecture example

Presentation Layer

Adapter Layer

Façade Layer

Service Layer

Persistance Layer (DAO)

Database Persistence Tier Where to store data

Data can be stored on different places • Relational Database (RDBMS) • Object Database • XML Database • DMS (Document Management System) • CMS (Content Management System) • Post-relational database (Caché) • Temporary • Hierarchical • Spatial • Key/Value (No-SQL) Database • Another Information System (CRM, ERP, etc.) Relational Databases

• The most frequent data storage for enterprise applications • Relational data model is simple but very powerful • Suitable and sufficient for most of common applications • Good theoretical model (Relational Algebra, Relational Calculus) • Simplicity => High Performance (eg. due simple optimizations) • Proven and well established technology (40 years of development, tools, standards, reliability, high penetration, lots of experts, etc.) • Data are separated from application and can be easily shared between different applications • Independent on concrete platform or Persistence Technologies

• With Relational Model • JDBC (low-level API, cumbersome for direct use) • Commons DB Utils • Spring JDBC • iBatis/MyBatis • Embedded SQL • With Object Model (ORM or other model conversion) • Legacy EJB 2.x • Hibernate • JPA • JDO What is ORM

Object-relational mapping (ORM) • Technique for automatic conversion between object model and relational data model • You work with objects, but they are stored in a traditional relational database.

INSERT INTO people (id, name) VALUES (1, "Pepa");

Person p = new Person(1, "Pepa"); em.persist(p); em.getTransaction().commit();

UPDATE people SET name = "Honza" WHERE id = 2;

Person p = em.find(Person.class,2); p.setName("Honza"); em.getTransaction().commit(); Why ORM

• As we already discussed, the most frequent storage is RDBMS • But we usually want to work with Object Model • Why Object Model? • It is natural for object oriented programming language • Working with Object Data Model is straightforward, friendly and easy • See example Why ORM: JDBC example public String getPersonName(long personId) throws SQLException { PreparedStatement st = null; try { st = connection.prepareStatement( "SELECT name FROM people WHERE id = ?"); st.setLong(1, personId); ResultSet rs = st.executeQuery(); if (rs.next()) { String result = rs.getString("name"); assert !rs.next(); return result; } else { return null; } } finally { if (st != null) { st.close(); } } } Why ORM: JPA Example public String getPersonName(long personId) { Person p = em.find(Person.class,personId); return p.getName(); } ORM: What We Get and Lost

• ORM Benefits • Possibility to work with natural object model • Portability between different RDBMS with different SQL Dialect • Type checking at compile phase • No runtime error in SQL statements • Simplifies testing • Simpler and clearer code • More effective development (auto complete, access to JavaDoc, etc.)

• ORM drawbacks • Less control over SQL statements sent to database • Less performance in some cases (ORM has some overhead). • No access to advantages of relational model and features of RDBMS (e.g. storage procedures) Standards and Approaches

• Entity EJB (EJB 2.1/JSR 153; J2EE 1.4) • Application server with EJB container required. • Entity is heavyweight component, instances are located in EJB container and accessed through remote calls • Problem with latencies (reason for introducing DTO and DAO patterns). • CMP or BMP • JPA is preferred since EJB 3.0 • JDO (JDO 3.0/JSR 243) • General and universal standard for data persistence in Java. • Not limited to RDBMS, arbitrary storage can be used for storing objects • JPA (JPA 2.1/JSR 338; Java EE 7) • Java EE standard for ORM (inspired with Hibernate) • Entity is lightweight POJO which can be freely passed between components, locally or remotely. EJB 2.x CMP Entity public abstract class PersonBean implements EntityBean { private EntityContext context; public abstract Long getId(); public abstract void setId(Long id); public abstract String getName(); public abstract void setName(String name); public Long ejbCreate (Long id, String name) throws CreateException { setId(id); setName(name); return id; } public void ejbPostCreate (Long id, String name) throws CreateException {} public void setEntityContext(EntityContext ctx) { context = ctx; } public void unsetEntityContext() { context = null; } public void ejbRemove() {} public void ejbLoad() {} public void ejbStore() {} public void ejbPassivate() {} public void ejbActivate() {} public PersonDTO getPersonDTO() { return new PersonDTO(getId(),getName()); } } POJO Entity public class Person { private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean equals(Object o) { if (this == o) { return true; } if (getId() == null) { return false; } if (o instanceof Person) { return getId().equals(((Person) o).getId()); } else { return false; } } public int hashCode() { return id==null?0:id.hashCode(); } } Mapping Definition

• With annotations • Object model definition and its mapping are on the same place. • Clear and straightforward • Easier development and maintenance

• With external file (usually XML) • Entities are independent on particular ORM technology • Mapping could be changed without modification of code

• With special JavaDoc comments • For Java 1.4 and older (without annotations support) • See XDoclet. JPA Introduction

• Java Persistence API • POJO Entities, inspired by ORM tool Hibernate • API implemented by various ORM tools from different vendors. • Just basic functionality, implementations could provide other features and functions through its proprietary API • Versions and specifications • JPA 1.0 – part of Java EE 5; created as part of EJB 3.0 (JSR 220), but independent. • JPA 2.0 – part of Java EE 6; JSR 317 • JPA 2.1 – part of Java EE 7; JSR 338 • ORM tools implementing JPA • Hibernate, Open JPA • TopLink, TopLink Essentials, Eclipse Link Entity in JPA

• Entity • Represent domain object • Simple POJO class • Attributes represents domain object properties • Attributes accessible with set/get methods • Mandatory zero argument constructor • It is useful (but not mandatory) to implement Serializable • Mapping definition • With annotations or xml file • Convention-over-configuration principle. JPA Entity

@Entity public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean equals(Object o) { if (this == o) { return true; } if (getId() == null) { return false; } if (o instanceof Person) { return getId().equals(((Person) o).getId()); } else { return false; } } public int hashCode() { return id==null?0:id.hashCode(); } } JPA Architecture Instance of Class of entityInstance A entityTřída A entityInstance B entityTřída B entity C entity C Entity instances Configuration, management mapping definition 0..1 1 0..n 1 Transaction PersistenceContext PersistenceUnit

1 Configures 1 Manages 1..n 1

0..n 1 EntityManager EntityManagerFactory

Allows manipulation Reads PU Configuration with entities Creates EntityManager Entity Lifecycle

. em.detach(e) Does not . em.clear() exist . Serialization and deserialization . Persistence Context Expiration Entity e = new Entity(); (eg. due em.close() operation) . Clone or copy New

em.persist(e);

Leaving Persistence Context em.remove(e) Detached Managed Deleted

em.merge(e) em.persist(e);

All changes are automatically stored into em.refresh(e); DB when current transaction is commited (DAO) Design Pattern

• Separation persistence and data access from business logic • Allows to modify persistence implementation or replace persistence technology at all without affecting application logic. • Testing of business logic is easier • Independent component for each entity • See Example Repository

• Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects. • General collection style interface for all entity types • Useful e.g. when we need to work with complex and/or dynamic queries • http://martinfowler.com/eaaCatalog/repository.html • See Patterns of Enterprise Application Architecture for more details Transaction management

• Transaction are not controlled on DAO level • Why? • Single transaction can contain more operations provided by different DAO components • Transaction management should be independent on persistent technology • Transaction management is usually controlled • At Façade level (if possible) • At various levels (if we need to handle transactions with various scopes) Transaction Management

TransactionAttributeType Transaction already in progress No transaction in progress MANDATORY Current transaction is used. Exception is thrown. NEVER Exception is thrown. No transaction is used. NOT_SUPPORTED Current transaction is suspended No transaction is used. REQUIRED Current transaction is used. New transaction is created. REQUIRES_NEW Current transaction is suspended, new New transaction is created. transaction is created. SUPPORTS Current transaction is used. No transaction is used. Data Transfer Object (DTO) Design Pattern

• Encapsulates data about some entity or entities for transport between layers • Use cases • Remove dependency on entities (e.g. in Business logic API) • Data model can be changed without affecting Business logic API and/or presentation tier • DTO granularity is independent on entity size (single DTO could contain only subset of entity attributes or could aggregate information from multiple entities) • Can be created at any Layer • Sometimes called as Value Object (VO) Proxy

• Proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes • Proxy can just delegate the call to the real object or it can provide some additional logic Proxy

• A virtual proxy – for object which are expensive to create. The real object is created on demand (when first attempt to access the object is made) • A remote proxy – for accessing object from remote system or different address space (e.g. using RPC or CORBA) • A protective proxy – controls access to a sensitive master object • A smart proxy – interposes additional actions when an object is accessed. • Counting the number of references to the real object so that it can be freed automatically when there are no more references (aka smart pointer) • Loading a persistent object into memory when it's first referenced • Checking that the real object is locked before it is accessed to ensure that no other object can change it Business Tier Service Façade

• Encapsulates complex business logic and expose it to the client as simple coarse-grained API • Service orchestration

Create order

Order Façade

Create Create Send Customer Order Notification

Customer Order Notification Service Service Service Observer

• Notifications and events • Example • Observer interface (obsolete) • Event handling in Java Beans Adapter

• Adapts some interface to another one. • Can be used • To make some component compatible with another interface • To convert method parameters types (e.g. Entities to DTO and vice versa) • To make two component completely independent on each other (they are not event sharing the common interface) Flyweight

• Minimizes memory usage by sharing data with other similar objects • Shared data should be represented by immutable classes • Examples • Glyph object in text processor (original example from GoF) • String intern in Java • Addresses code list Iterator

• Allows to traverse collection without knowing details about the implementation • Example – Iterator in Java • See also • Enumeration (obsolete since Java 1.2) • Iterator (Java 1.2) • Iterable (Java 5) • Stream (Java 8) Builder

• Pattern for creating objects • Solves the telescoping constructor anti pattern • Example • GraveBuilder Strategy

• Define a family of algorithms, encapsulate each one, and make them interchangeable. • Example: • Custom Validator • Billing Strategy • Change algorithm according to input type Template Method

• Define the skeleton of an algorithm in an operation, deferring some steps to client subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. • Examples • Report generator • Commons db-utils • Spring JdbcTemplate Visitor

• Represent an operation to be performed on elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. • Example • FileVisitor Bridge

• decouple an abstraction from its implementation so that the two can vary independently • Example • Thread scheduler for multiple platforms • Shapes and Drawing • Export data Presentation Tier Model View Controller

• Not traditional Design pattern but Architectonical Pattern • Implementation could be different in various cases • Presentation is split to • Model – represents data and business logic • View – displays data • Controller – controls data flow Mediator

• Encapsulates how a set of objects interact. • Promotes loose coupling by keeping objects from referring to each other explicitly • Examples • Change state of user interface • Fly control • ESB Chain of Responsibility

• Request is passed through chain of possible processing objects until it is processed • Example • PurchasePower • JavaServlet filters • Aspects in AOP Composite

• Describes that a group of objects is to be treated in the same way as a single instance of an object. • Client does not need to know that component could consist of other objects • Tree structure • Examples • GUI components (SWING, JSF) • Arithmetic expression Decorator

• Allows to attach additional responsibility to object dynamically • More flexible than inheritance • Aggregation + Delegation • Examples • Window decorator • InputStream/OutputStream and Writer/Reader in Java State

• Object can change its behavior when the state is changes • Examples: • State diagram • Order State • Handling exchange price Component Testing Unit Tests

• Test of isolated component • Deterministic (always the same initial conditions, no random data or current time) • Isolated (no interference with other tests) • Border values and non-standard situations should be tested • Test should be easy-to-understand Mock Objects

• Tested component is isolated from the environment, behaviour of other objects is simulated with Mock objects • Easy when interfaces are separated from implementation • Various libraries • Mockito (http://mockito.org) • JMock • EasyMock Demo

• Exception handling • AssertJ • Mockito • Junit Integration • Verify • When • Argument matcher • Argument capture Gold Rule

• When the component is well designed (single responsibility, loosely coupled), it is easy to write unit tests. • If it is hard to write unit test, the component has the most probably bad design.