1.3k likes | 1.42k Views
JavaBeans Specification, Design, and Test (using Catalysis) Aamod Sane Platinum Technology www.platinum.com. About the Speaker.
E N D
JavaBeansSpecification, Design, and Test(using Catalysis)Aamod SanePlatinum Technology www.platinum.com
About the Speaker Dr. Aamod Sane is principal architect at Platinum Technology. He is involved in developing the Catalysis method , component specification and implementation techniques, including tool support. He has worked with software technology since 1987 and developed object systems since 1989. He has published on design patterns, frameworks, and components at conferences like OOPSLA, ECOOP, and PLOP. Aamod has worked on operating systems, distributed systems, orbs, design-pattern tools, and case tools. He is experienced in software architectures, modeling, analysis, and specification and programming. Aamod’s home page is http://choices.cs.uiuc.edu/sane/home.html
From objects to components Java interface versus class Components with Java Beans Specifying Java Beans Components and connectors Testing against specifications Reuse Outline
A coherent package of software that can be independently developed and delivered as a unit, and that defines interfaces by which it can be composed with other components to provide and use services. A component package can include: Executable, source, design, specification, models, test Must be self-contained to be independently delivered A component implements provided interfaces in terms of required interfaces The implementation must be in terms of interfaces expected from others What is a Component?
IDisplay IDataSource Spreadsheet Display Calc Data source Components and Interfaces • Packages must clearly separate interfaces from implementations • Interfaces must be organized to capture interface dependencies Many implementations of used interfaces Must contain (or reference) interfaces provided and used
Component Essentials 1. Components interact 2. Components compose and grow Warehouse 3. Components may be distributed Supplier That’s what’s interesting about them
IPickup Interface IDelivery How is data stored? Is the data stored here? …or actually stored here? What other interfaces are provided or used? How do Components Interact? Components interact via clearly specified interfaces Warehouse Supplier Focus on behavior; stored data, implemented procedures, other interfaces remain completely hidden
Services Provided: Interface Spec Services Required: Interface Spec Not standard OO!! Events Raised: Notifications of state changes Logical model of component state: Type Model Interface operations and events specified based on this Describing a Component Warehouse IDelivery Supplier Result: Precise model of information exchanged, assumptions, guarantees
slider Button start position pressed <<prop>> limit start <<physical>> value in Thermometer Threshold stop value out toggled in1 out in OR Alarm reactor Switch in in2 out gradient Differentiator in Threshold <<replicate>> Other forms of higher-level “connectors” <<workflow>> Component “connectors” <<prop>> <<event>> <<event>> <<prop>> [OCF 10.8]
Standard “horizontal” infrastructure services request broker, interface and server repository, transaction, security, … OMG, Microsoft rapidly defining many global “standards” Standard “vertical” models of domain concepts What is a “Customer”, “Phone Call”, “Order”, etc. components must talk the same “domain language” OMG defines “Vertical” architectures standards as well Standard “connector” mechanisms between components Synchronous request, asynchronous message, event, workflow, replicate Location transparency: RMI, CORBA, DCOM Mobility of code vs. data, mobile objects: Java, ActiveX, TeleScript synchronous? event? work-flow? What is customer, phone call…? Components must share Architectural Standards infrastructure services
Most components can be described as objects both emphasize encapsulation, interfaces, polymorphic late-bound connections most new components will be built from traditional objects inside So, what did traditional object-oriented development do wrong? undue emphasis on class and implementation inheritance rather than interfaces just one basic form of “connectors” -- explicit message invocations unfortunate language-imposed dependencies on class source code -- .h files boundaries such as host, programming language visible to components infrastructure services ignored -- persistence, transactions, security, discovery… component can be larger than a traditional single “object” or “class” host/language host/language obj-1 obj-3 obj-2 obj-4 class infrastructure services Are Components and Objects Different?
Granularity spans the spectrum UI widgets: combo-box, tree “Application” and component-document elements: spreadsheet Large-grain components: scheduler, inventory manager Good components are often not “business objects”!! Naïve OOA/D will not lead automatically to component design Running component can usually be modeled as an object But it need not correspond to a single OOPL object! Services may be exposed by separate constituents Range of binding times Design-time Run-time Component Granularity and Binding Time
Larger-grain, more static, polymorphic “components” Finer-grain, dynamic, polymorphic “objects” Components + Objects: Best of Both • Plug together components and objects at any level and any binding time
From objects to components Java interface versus class Components with Java Beans Specifying Java Beans Components and connectors Testing against specifications Reuse Outline
“Plug” into new service What Type? What Type? Airline Hotel Type of an Object: Multiple (Inter)Faces • Object or component plays different roles • It offers multiple interfaces, and is seen as different types • Benefits to the airline, hotel: less coupling, more “pluggability” • Benefits to person: easier to adapt to “plug” into a bigger system Guest guarantee check In order room Service pay at check Out Passenger check Baggage board deplane
Guest Hotel Airline object:Both Passenger Full type/class separation possible!! Types: Java, COM, Corba, ... • interface Guest { • guaranteeCheckIn (); • orderRoomService(); • payCheckOut (); • } • interface Passenger { • checkBaggage (); • board (); • deplane (); • } • class Both • implements Guest, Passenger { • // implementation …. • }
Interface vs. Class: Which does a Client Use? • Which of the Tx types here have to be classes, and which can be interfaces? • class C1 implements T extends T0 { • private T1 contents; • public T2foo (T3 b) { • super (); • this (); • contents = b; • T2 d; • d = new T5 (); • return d; • } • } Client never needs to mention “class - except to instantiate - can use “factory” patterns here
From objects to components Java interface versus class Components with Java Beans Specifying Java Beans Components and connectors Testing against specifications Reuse Outline
Java Beans • A “Component” standard for Java • A reusable software component that can be manipulated in a visual builder tool • Describes component by properties, methods, events • Property: an observable state variable • Method: an invocable service • Event: a notification of state change • Builds on underlying technology of reflection, persistence
Events can be “wired” to methods Match event parameters and properties (state variables) to method inputs Properties can be “wired” to other properties Implicit, rather than explicit update protocols Not currently supported by JavaBeans products m (p,q) method E (x) event “Wiring” beans together properties p1 p2 p3
Reflection • JDK 1.1 introduced the reflection API • Run-time representation of class, interface, method, … • Run-time operations on these objects • Enables very-late binding of calls • Determines properties, methods, events from signatures • Can be supplanted by an explicit BeanInfo class
JDK 1.1 Reflection • Reflect on Java definitions at run-time by accessing: • Class: static Class forName(String) getSuperclass, getInterfaces, getFields, getMethods, getConstructors, …newInstance, ... • Field: getDeclaringClass, getName, getModifiers, getType, getBoolean, getInt, … setBoolean, setInt ... • Method: getDeclaringClass, getName, getReturnType, getParameterTypes, getExceptionTypes, invoke ... • Constructor: … newInstance • Uses wrappers for primitives, arrays
Reflection Example • // locate and load the class dynamically • Class c = Class.forName (“UserDefinedClass”); • // instantiate the class • Object o = c.newInstance (); • // get one of the methods on that class • Method m = c.getDeclaredMethod (“userMethod”, { } ); • // invoke that method on the new instance • m.invoke (o);
Beans Properties via Naming + Reflection • Properties derived by reflection using name conventions • Simple properties: “StockSymbol” of type String • String getStockSymbol(); • void setStockSymbol(String newSymbol); • “Multi-valued” properties: “Symbol” of type String [] • public String getSymbol(int index); // throws bounds error public void setSymbol(int index, String newValue); // throws … • Other property types: bound, constrained • Example: • class MyBean { • String getStockSymbol() {…} • void setStockSymbol (String) {…} • }
Balance eventchannel Account Bean Usage eventchannel Event Design Patterns in JavaBeans • Group events into event channels by Listener interfaces • interface BalanceListener extends java.util.EventListener { • void overdrawn (BalanceEvent); • void balanceOK (BalanceEvent); • } • Bean may offer different event channels • Standard protocol pattern for registering event listener: • void addBalanceListener (BalanceListener f); • void removeBalanceListener (BalanceListener f); Balance Listener
Beans persistence via Serialization • Save and restore graphs of Bean objects to/from streams • All JDK 1.1 classes can be serialized • implement java.io.Serializable • Default behavior/formats easily extended or overridden • public class MyBean implements java.io.Serializable • { SomeOtherBean delegate; • transient Object anotherField; • } • Save and restore automatically available • ObjectOutputStream ost = new ObjectOutputStream(a); • out.writeObject(new MyBean()); • ObjectInputStream ist = new ObjectInputStream(b); • MyBean x = (MyBean)ist.readObject();
The interfaces of a JavaBean may be provided by a group of collaborating objects of different classes This will become increasingly common with complex beans They conceptually work as a single object Danger: Java language primitives will not know this! Don’t use a language “cast” to get another interface Don’t use the language == operator to check for identity Beans Glasgow specs provide some interim recommendations JavaBean versus Java Object a b d c
JAR files • A JavaBean is packaged into a JAR file • Set of class files that implement its behaviors • Serialized instance to use for initialization • Help files • Resource files: images, sound, video, … • Manifest file: describes the JAR file contents and dependencies • When modeling, use package structure effectively
Enterprise Java Beans • A standard for simplifying server components by implementing most “middle-tier” services • Distributed transactions • Thread and database connection pooling • Concurrent access • Authentication
From objects to components Java interface versus class Components with Java Beans Specifying Java Beans Type models Methods Exceptions Properties Events Components and connectors Testing against specifications Reuse Outline
Thingami frob (Thing, int) Thing fritz(int) Editor spellCheck() layout() addElement(…) delElement(…) NuclearReactorCore add (ControlRod, int) ControlRod remove(int) The “Black-Box” Component • Signatures are not enough to define widely-used components
To build systems by “plugging” together components Two choices: “plug-n-pray”, or use better specifications that are: abstract: apply to any implementation precise: accurately cover all necessary expectations is one implementation of... ? certify and publish will work with... “Type” spec what is expected of any “plug-in” Components need Precise Interfaces
type-model = vocabulary Editor «type» type specification usually in separate package contents * Element preferredSize position operations specified in terms of the type model “vocabulary” * dictionary Word Composite * every word in contents is correct by the dictionary spellCheck() layout() addElement(…) delELement(…) every element is positioned so that its preferred size can be accommodated Model-Based Type Specification - Example Editor Type Specification [OCF 3.4]
Operation specification can formalized OCL (Object Constraint Language) used after rectifying some shortcomings Checked, used for refinements, testing, change propagation, … Enables checkable/testable design-by-contract Editor:: spellCheck () post// every word in contents contents -> forAll (w: Word | // has a matching entry in the dictionary dictionary -> exists (dw: Word | dw.matches(w))) Formalizing Operation Specs
maximum size resize children Editor E-Core next word replace word spellCheck() layout() addElement(…) delELement(…) Layout Manager Spell Checker spellCheck() layout() Component-Based Design internal design in a separate package from the specification Editor Internal Design dictionary words • Large component is a type for its external clients • Implement it as collaboration of other components • Specify these other components as types • The child component models must map to the original model
Spell-Checker Layout Manager SpellCheckable Layoutable seq * Elem size Word curr descendants * next word replace word maximum Size resize children Each Component implements many Types EditorCore LM SC • Components offer different interfaces to each other • Each interface has a different supporting model • The implementation refines each interface spec
Spell Checkable SpellChecker seq * Word next Word replace Word Acme Spell Bee EditorCore DB Record Type-Based Components are “Pluggable” • Any component that provides the correct interface (operations and apparent type model) can plug-into another component
Component Implementation class EditorCoreClass implements SpellCheckable, Layoutable { // store a tree of all elements — graphics, words, characters, tables, etc. private ElementTree contents; // this iterator traverses all elements in the contents tree in depth-first order private DepthFirstIterator elementIterator = contents.root(); // this iterator only visits Word elements, ignoring others private WordIterator spellPosition = new WordFilter (elementIterator); // return the “next” word in the tree public Word nextWord () { Word w = spellPosition.word(); spellPosition.next(); return w; } // replace the last visited word with the replacement public void replaceWord (Word replacement) { spellPostion.replaceBefore (replacement); }}
Spell Checkable words seq * Word next Word replace Word “abstraction function” or “retrieval” words = contents.asDepthFirstSequence -> select (e | e.isKindOf (Word)) refinement EditorCore <<class>> Class refines Interface • Abstraction function “retrieves” abstract model attributes
1. Higher-level parts … abstract the objects 2. Higher-level late-bound connectors and properties … abstract the protocol, defer binding Order Taker Shipper <<event>> shipordered Buyer Receiver * Order * Shipment takeOrder (info) orderStatus (...) cancel (...) <<output>>ordered ship (shipment, receiver) shippingStatus (order) 4. Precise interfaces for 3rd assembly 3. Separate views for flexible use (can ship to any receiver) Integrated business model Customer Business Components: Modeling Issues • To assemble variety of configurations from a kit of reusable parts • demands abstract parts, abstract connections, multiple views and “plug” precision - must integrate in conceptual models - must integrate data in implementation - shared objects with multiple interfaces - federated data + cross-component links
Business area Presentation “local” connector Local Application “distributed” connector Business Logic Component packaging + reuse at all levels “distributed” connector UI parts Domain Objects Business Data Domain Objects + UI Panels Data Access Logging, events,... Shipper Order Taker Shipper Order Taker Business Components: Tiered Architecture Can zoom in to show architectural tiers, or zoom out to model abstract business components Can package application components as: - vertical slice - interfaces connecting Business Logic
From objects to components Java interface versus class Components with Java Beans Specifying Java Beans Type models Methods Exceptions Properties Events Components and connectors Testing against specifications Reuse Outline
Exception versus Undefined Behavior • Guaranteed exceptions are different from undefined failures • Invoker needs clear indication of exception versus success • Exceptions should not be overspecified: e1 versus e2 • [OCF8.4]
Define normal and exception indicators Editor::spellCheck () exception = throws (Object) // throw <=> exception normal = not throws (Object) // if normal, nothing thrown Write separate post defining different exceptions Editor::spellCheck () post (dictionary@pre = null) or (read_only) implies exception // a definite exception if no dictionary or read_only post throws (DictionaryError) implies (dictionary@pre = null) post exception implies contents unchanged // contents definitely unchanged on any exception Specifying Exceptions
From objects to components Java interface versus class Components with Java Beans Specifying Java Beans Type models Methods Exceptions Properties Events Components and connectors Testing against specifications Reuse Outline
Model only public Type model attribute vs. query method • A type-model attribute does not imply a get/set method • Attributes are just a model of state • Not necessarily externally accessible • The only publicly accessible things are methods • So we must have read-only methods for any public query • which is a recurring pattern for any “exposed” attributes • Shortcut for “property” attributes with Catalysis frameworks
Intent • We don’t want to model with explicit get/set • Loses the main intent • Define a modeling pattern where: • <<property>> can be annotated on any attribute • <<property>> is defined as a framework • get/set is implied (expanded form) of that annotation
property: T get_<property> () : T set_<property> (T) Catalysis Model Framework • A generic template package which is imported with substitutions A package to be imported property X substituting for this generates this [OCF9.8]
X property: T get_<property> () : T set_<property> (T) <<property>> stereotype property • <<property>> stereotype means a read-write accessor • Stereotype implies import with substitution • import property [ X \ EditorCore, property\current, T\Element ] editor EditorCore selection 0,1 Element <<property>> get_selection () : Element set_selection (Element)
<<indexed_property>> property (int): PropertyType <<indexed_property>> (generates) setProperty (int, PropertyType) getProperty (int) : PropertyType setProperty ( Array(PropertyType)) getProperty () : Array(PropertyType) <<bound_property>> implies event protocol for notifying of change in property uses Catalysis framework for output event and change i.e. equality [OCF 9.7] <<constrained_property>> implies vetoable protocol of change in property uses Catalysis framework for output event and change i.e. equality Other “property” variations