Best Practices Notes ==================== On the Extreme Programming wiki, Kent Beck says: "Software is too damned hard to spend time on things that don't matter. So, starting over from scratch, what are we absolutely certain matters? ... Listening. Testing. Coding. Refactoring. That's all there is to software. Anyone who tells you different is selling something." Possible new pattern: Executable Documentation (courtesy of Marnix Klooster, on the Wiki web). One page principle: A specification that will not fit on one page of 8.5 x 11 inch paper cannot be understood. --Mark Ardis (via fortune) "Carefully selected and well-written memos can easily substitute for traditional comprehensive design documentation. The latter rarely shines except in isolated spots. Elevate those spots...and forget about the rest." Ward Cunningham Key Questions to ask in Responsibility Based Modelling (RBM) (Alistair Cockburn): * Is it really the responsibility of this object to handle this request? * Is it the responsibility of this object to keep track of all that information? Five Activities of RBM: * Preparation * Invention * Evaluation * Consolidation * Documentation New interpretation of CRC cards: Component (was Class) Responsibility Collaborator. Collaborator has also been changed, but I forget what it was changed to. It's interesting to note that most Java utilities do double duty as both a utility program and a class library or API. Also, an application can be both a GUI or CLI program. And, of course, a GUI can be both an applet and an application (and a component!). Four Pillars of Rapid Development: * Avoid Classic Mistakes * Development Fundamentals * Risk Management * Schedule-Oriented Practices Four Dimensions of Development Speed: * People * Process * Product * Technology Staff Selection for team projects: * Use fewer and better people * Fit tasks to skills and motivations to people available * Help to self-actualize (career progression) * Team balance: select people who complement each other * Misfit elimination: replace problem members quickly Application Framework Notes: An application framework could create interfaces and/or abstract classes for many of the "best practices". Templates can be simulated by making classes which write Java code with the object specified. Or, better still, writing an XSL stylesheet. the problem with using XML/BML for creating beans is that you'll still have to write Java code, so you still end up using two syntaxes (syntacies?) and you'll have to bracket out your Java code with , which is inconvenient. Unless BML is extended to subsume Java syntax... By documenting best practices, especially variations, it is possible to accumulate data on what is really needed to describe a bean. When the time comes to put together an application framework, use the Metrowerks PowerPland book as a guide. 3 Keys to Design Patterns: Factor what changes from what stays the same. Define what changes with an interface to allow it to be implemented in replaceable modules. There is no problem which cannot be solved by adding enough layers of abstraction. Third one is in my notes from Doug Schmidt's class... GOF Principles of Object-Oriented Design: Program to an interface, not to an implementation Favor object composition over class inheritance From Thinking in Java, chapter 7: Use inheritance to express differences in behavior, and member variables to express variations in state. "Prefer object composition over inheritance and strategy objects over template methods." Aspect-oriented programming basically makes the variable parts of an object pluggable. Levels of Patterns: Object Property Pattern Idiom Framework Aspect Component Library Distributed Component Guideline Style Guideline Self-Documentation (What do you call a pattern which ties other patterns together) Pattern Language Multi-Threading Rule: Never fire events from within synchronized blocks. Why not? Where the hell did I read this. This is so screwy if true. Gabriel's Guidelines for programming: Compression - the meaning of a part is larger than the part (Rich Context) Habitability - the ability to understand and change source code comfortably and confidently Piecemeal growth - design and imlementation through embellishment, modification, enlargement, reduction, and improvement (Repair rather than replacement) Alexander, the Software Pattern movement, Zen & the Art of Motorcycle Maintenance, Deepak Chopra, and M. Rushworth Kidder are all seeking to resolve the rift caused by Decartes, discussed in Mindwalk. "What is revolutionary about Alexander is that he is resuming the quest for an understanding of objective quality that science and philosophy abandoned in the modern era. In the seventeenth and eighteenth centuries, a tension developed in which mind and matter were separated by science and philosophy. From this came the separation of fact and value. After the separation, a fact had no value associated with it, a fact could not be good or bad, it just was. Science, then, tried to find theories that explained things as they were and no longer sought what was good or beautiful about things. That is, we no longer sought the objective characterics of beauty, which is where Alexander started his quest." --Richard Gabriel Group pattern thumbnails by level of abstraction (class, framework, application?) and include in the sketch which patterns are related (derived from, similar to, works-well-with, uses). Try to form pattern languages... ======= GRAND I ========== Fundamental Design Patterns Delegation Interface Proxy Immutable Marker Interface Creational Patterns Abstract Factory Builder Factory Method Prototype Singleton Object Pool Partitioning Patterns Layered Initialization Filter Composite Structural Patterns Adapter Iterator Bridge Facade Flyweight Dynamic Linkage Virtual Proxy Decorator Cache Management Behavioral Patterns Chain of Responsibility Command Little Language/Interpreter Mediator Snapshot Observer State Null Object Strategy Template Method Visitor Concurrency Patterns Single Threaded Execution Guarded Suspension Balking Scheduler Read/Write Lock Producer/Consumer Two-Phase Termination ======= GRAND II ========== GRASP (General Responsibility Assignment Software Patterns) Creator Expert Law of Demeter (Don't Talk to Strangers) Low Coupling/High Cohesion Polymorphism Pure Fabrication GUI Design Patterns Conversational Text Direct Manipulation Ephemeral Feedback Explorable Interface Form Disabled Irrelevant Things Interaction Style Limited Selection Size Selection Step-by-Step Instructions Supplementary Window Window Per Task Organizational Coding Patterns Accessor Method Name Anonymous Adapter Checked vs. Unchecked Exceptions Conditional Compilation Composed Method Convert Exceptions Define Constants in Interfaces Extend Super External Resource Intention Revealing Method ServerSocket Socket Switch Symbolic Constant Name Optimization Coding Patterns Double Checked Locking Hashed Adapter Objects Lazy Initialization Lookup Table Loop Unrolling Robustness Coding Patterns Assertion Testing Copy Mutable Parameters Guaranteed Cleanup Maximize Privacy Return New Objects from Accessor Testing Patterns Acceptance Testing Black Box Testing Integration Testing Regression Testing System Testing Unit Testing White Box Testing ======= GRAND III ========== Transaction Patterns ACID Transaction (Atomicity, Consistency, Isolation, Durability) Business Transactions and Accounts Composite Transaction Adjustment Transactions Audit Trail Seperate Transaction Processing from Archival Two Phase Commit Distributed Computing Patterns Object Identifier Object Marshalling Access Proxy Replication Publish-Subscribe Mailbox Registry Broker Object Broker Database Broker Microkernel Naming Service Lightweight/Heavyweight Object Translator Remote Proxy Evictor Connection Multiplexing Environment Worker Distributed Concurrency Patterns Data Lock Optimistic Concurrency Client-Dispatcher-Server Master-Slave Thread Pool Write Consistency Read Consistency Temporal Patterns 13 Temporal Relationships Time Server Versioned Object Effective Dates Business Patterns Data Prototype Trader Exception Report Business Rule Server Database Patterns Represent Relational Database Tables as Objects Represent Objects as Relational Database Tables GUI Implementation Patterns Delegated Validation Externalize Resources Model-View-Controller (Model-Interactor) View Handler ======= SCHMIDT ========== Concurrency Patterns Thread-per-Request Thread Pool Thread-per-Session Active Object Half-Sync/Half-Asynch Double-Checked Locking Thread-Specific Storage Sorceror's Apprentice Problem: Lots of threads being created with no way to shut them down. Event Patterns Asynchronous Completion Token Reactor Proactor Initialization Patterns Acceptor Connector Service Configurator Miscellaneous Patterns Router External Polymorphism Wrapper Facade ======== BECK =============== Best Practices Once & only once - nothing said twice Lots of little pieces - small objects, small methods Replaceable objects Moveable objects Isolated rates of change ======== ChiMu Guidelines ============= GENERAL OO GUIDELINES Types Name Types Well Only Expose Responsibilities Operations Choose Intention Revealing Operation Names Have Uniquely Named Signatures Standardize Naming Patterns Categorize Your Operations Classes Methods Compose Your Methods Make Executable Structure Obvious JAVA-ORIENTED GUIDELINES Types, Interfaces, and Classes: Design Interface with Interfaces Create Different Interfaces for Different Types of Clients Use Interfaces over Abstract Classes Rarely declare a class abstract Consider writing template files Operation and Method Design Weave Parameter Positions into the Operation Name Define return types as void Avoid overloading methods on return type Write Methods that only do "one thing" Packages and Modularity Have a "Pack" class for all packages Use Factories for creating objects Minimize * forms of import When sensible, consider writing a main for the principle class The class with main should be seperate from those containing normal classes Method Implementation Declare a local variable where you know its initial value Use a new local variable Assign null to any reference variable that is no longer being used Avoid assignments ("") inside if and while conditions Ensure that there is ultimately a catch for all unchecked exceptions Embed casts in conditionals Documentation Make code self-documenting before commenting it Provide comments that augment, not repeat, program code Use Interfaces for public documentation Specify a standard keyword order Augment javadoc keywords Class Implementation Never declare instance variables as public Minimize statics Prefer protected to private Minimize reliance on implicit initializers Prefer abstract methods to those with default no-op implementation Avoid giving a variable the same name as one in a superclass Use final and/or comment conventions for instance variables Avoid unnecessary instance variable access and update methods Minimize direct internal access to instance variables inside methods Ensure that non-private statics have sensible values Consider whether any class should implement Cloneable and/or Serializable Whenever reasonable, define a default (no-argument) constructor Overriding If you override Object.equals(), also override Object.hashCode() Override readObject and writeObject if a Serializable class relies on process state Explicitly define clone() Miscellaneous Generally prefer long to int and double to float Use method equals instead of operator == when comparing objects Prefer declaring arrays as Type[] arrayName rather than Type arrayName[] Concurrent Programming Declare all public methods as synchronized Prefer synchronized methods to synchronized blocks Always embed wait statements in while loops that re-wait Use notifyAll instead of notify or resume Always document the fact that a method invokes wait() Methodology, Notation, and CASE Guidelines Use UML Go beyond UML Use a smart drawing tool Link your design diagram to javadoc Don't draw models for everything Use a CASE tool Avoid taking liberties with a CASE tool Recognize the limits of CASE tools Drive CASE tools from the appropriate direction Final Guidelines Try it out Prove performance Take out the trash Do not require 100% conformance to the rules of thumb! Kent Beck/Ward Cunningham: A very small pattern language for designing windows: * Window Per Task * Few Panes Per Window * Standard Panes * Short Menus * Nouns and Verbs Java Idioms (from the Wiki Web: http://c2.com/cgi/wiki?JavaIdioms) Architectural Idioms * Parameter Classes * Abstract Static Variables * Applets are Applications Too Memory Management and Reference/Value Semantics * Resource Releases Resource, which came from Releasing Resources in Java * Return new Objects from Accessor Methods * Value Objects Should be Immutable * Return Immutables from Accessor Methods * Copy Mutable Parameters * Immutable Collection * Immutable Interface Object Creation and Initialisation * Test Whether in Construction Phase * Encapsulate Multi-Stage Construction * Use Factories to Build Objects * Helper Method for Initialization * Parameter File Not Html Params * ParameterClasses * Complex Interfaces Need Cloneable * Always Declare Serial Version Uid Enumeration and collection idioms * Return Enumerations not Collections * Use Enumerations not For loops * Use Closures Not Enumerations * Immutable Collection * Duplicate Collections for Type Safety * Duplicate Collections for Modifications Safety Exception Idioms * Always Type Your Exceptions * Convert Exceptions * Throw Don't Catch Type-Safety Idioms * Enumerated Types in Java * Avoid Final Strings for Unique Types General Workarounds, Idioms * Beans Not Observer/Observable * Conditional Compilation in Java * Efficient Contracts in Java * Return Boolean Evaluations * Use Objects to Return Multiple Values * Observers and RMI * RMI Patterns * Closures that work around Final limitation? * Limit Constructor Arguments * Get Defaults to Types? * Inner Classes are Secondary Abstractions?