Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Micro Patterns in Java Code The Unbelievable Simplicity of real Object Oriented Programming Yossi Gil Technion joint work with Itay Maman Research supported in part by IBM HRL June 9 2005 , Netanya Academic College Israeli Conference on Software, Engineering and Management (ICSEM 2005) A Classical Class in C++ … typedef basic_string< char , char_traits<char>, allocator< char> > string; template <class charT,class traits,class Allocator> class basic_string { // 300 dense lines of C++ declarations }; You call this simple?!?!? 2/20 Is Java any Better? Let’s look at a classical example, drawn from: • Sun Development Network – Tutorial and Code Camps • Essentials of the Java programming language – Lesson 8: Object-Oriented Programming » The lead question: How Do These Concepts* Translate into Code? *Object, Message, Class, Inheritance 3/20 Class ClickMe /** * ClickMe.java is used by ClickMeApp.java. ClickMe is a * component that puts a spot wherever you click. It requires * another file: Spot.java. */ import javax.swing.BorderFactory; import javax.swing.JComponent; import java.awt.*; How Do These import java.awt.event.*; Concepts* Translate into Code? public class ClickMe extends JComponent implements MouseListener { Message, *Object, private Spot spot = null; Class, Inheritance private static final int RADIUS = 7; private Color spotColor = new Color(107, 116, 2); //olive /** Creates and initializes the ClickMe component. */ public ClickMe() { addMouseListener(this); public void mouseClicked(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} /** * * */ public void paintComponent(Graphics g) { /** * Copy the graphics context so we can change it. * } //Methods required by the MouseListener interface. public void mousePressed(MouseEvent event) { if (spot == null) { spot = new Spot(); spot.setSize(RADIUS); } spot.x = event.getX(); spot.y = event.getY(); repaint(); } Cast it to Graphics2D so we can use antialiasing. */ Graphics2D g2d = (Graphics2D)g.create(); // Turn on antialiasing, so painting is smooth. g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //Hint at good sizes for this component. // setPreferredSize(new Dimension(RADIUS * 30, RADIUS * 15)); setMinimumSize(new Dimension(RADIUS * 4, RADIUS * 4)); //Request a black line around this component. setBorder(BorderFactory.createLineBorder(Color.BLACK)); Paints the ClickMe component. This method is invoked by the Swing component-painting system. // Paint the background. g2d.setColor(Color.WHITE); g2d.fillRect(0, 0, getWidth() - 1, getHeight() - 1); Paint the spot. if (spot != null) { int radius = spot.getSize(); g2d.setColor(spotColor); g2d.fillOval(spot.x - radius, spot.y - radius, radius * 2, radius * 2); } } } 4/20 import import import import A Bird’s Eye View on ClickMe javax.swing.BorderFactory; javax.swing.JComponent; java.awt.*; java.awt.event.*; public class ClickMe extends JComponent implements MouseListener { private Spot spot = null; private static final int RADIUS = 7; private Color spotColor = new Color(107, 116, 2); public ClickMe() {… } public void paintComponent(Graphics g) {…} public void mousePressed(MouseEvent event) { … }} public void mouseClicked(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} } Still, not simple enough… 5/20 A Really Simple Java Class? class Example { public static void main(String args[]){ System.out.println("Hi, Dad!"); } } public?!? static?!? void?!? 6/20 The Complexity Hypothesis Classes are not simple, because they come in so many different varieties 7/20 The Enormous Design Space of a Single Java Class • • • • • Which interfaces does it implement? Which class, if any, does it extend? Is it final, abstract or neither? Is it inner, local, anonymous or neither of these? For each member, designer must select – Multiplicity: instance or static? – Visibility: private, public, protected, or default? – Kind: field, method, constructor, or initializer? • If it is a field… – Is it final or not? – Is it initialized? • If it is a method… – Sort: Is it final, abstract, or neither? – If it is non-abstract… » Inheritance: Is it overriding, refining, or extending? – Signature? The Patterns Conjecture • Programmers rarely use the many different alternatives offered by the design space of the underlying language. • Example: – There are over 40 different kinds of members (without counting signature information). Thus, there are: • 1600 (=40*40) different kinds of classes with 2 members. • 64000 (=40*40*40) different kinds of classes with 3 members. • ... – Only a small fraction of these are used in practice. Let’s concentrate 90% of the complexity is on the boring 90% in 10% of the code of the code. • Rationale: – People do not have time for deep pondering of all details. – They reuse the same simple ideas that work over and over. – Variety, Creativity, Ingenuity are reserved for the difficult cases. 9/20 Micro Patterns “Formal condition on the type, structure, names, and attributes of a Java class and its components.” 1. 2. 3. 4. 5. Purposeful: fulfill a useful programming practice. Prevalence: occurs reasonably often in real code Limiting: restrict the design space variety. Mechanically recognizable: by an automatic checker. Simple: human understandable Similar to Design Patterns, but (i) automatable, and (ii) at a lower level of abstraction. 10/20 Quick Examples • Immutable: a class whose state never changes These are so obvious! • Record: hasHow the look andIfeel Pascal come didofnot thinkrecords • Sampler: offers to customer a collection of pre-made about these myself? instances • Sink: does not propagate calls You no did! Youinformation have been • Stateless: carries state usingwith these all the time! details • Pure type: a class no implementation It is just interface that you never • Designator: an empty them! • Implementor:bothered gives bodytotoname abstract methods, without introducing new such methods. 11/20 The Micro Patterns Catalog • 27 different μ-patterns • 8 categories • Wide spectrum of common programming practices – – – – – Data management Wrapping Restricted creation Immutability Restrictive use of inheritance • Experiment spanning over 70,000 classes – Coverage: The catalog covers about 75% of the data set – Informative: Contribute about 5 bits of descriptive information to each class. 12/20 Benefits of μ-Patterns • Software Understanding – Only a few Complex Classes: 20-25% defeat categorization • Some are a result of imperfections of our cataloging • Some are truly complex: Concentrate efforts on these • Documentation – Terse Description: The essence of long classes can be captured by a word or two. • Design – Vocabulary for specifying framework structure – Communication between designers – Facilitate better design by providing a definitive guidance regarding “how do many of the classes should look like” • Education: Quick introduction to the tools of the trade. 13/20 Example: Mould Mould: The functionality of all abstract methods is solely by a composition of the concrete methods. package java.lang; import java.io.Serializable; public abstract class Number implements Serializable { public byte byteValue() { return (byte)intValue(); } public short shortValue() { return (short)intValue(); } public public public public abstract abstract abstract abstract double doubleValue(); float floatValue(); int intValue(); long longValue(); } 14/20 The Pattern Groups • Degeneracy: – – – – Degenerate State and Behavior Degenerate State Degenerate Behavior Controlled Creation • Data Management: – Wrappers – Data Managers • Inheritance – Inheritors – Base Classes 15/20 Map μ-Patterns in their Categories more restricted Behavior Base Classes Degenerate State and Behavior more restricted Designator Taxonomy Joiner Pool more general Degenerate State Outline State Machine Pure Type Augmented Type Pseudo Class Mould Stateless Monostate Immutable Box Immutable Inheritors Implementor Overridder Extender State Degenerate Behavior more general Function Pointer Function Object Cobol Like Data Managers Record Data Manager Sink Wrappers Box Compound Box Controlled Creation Restricted Creation Sampler 16/20 Multiplicity of patterns 14000 13039 12415 12000 9947 No. Classes 10000 8000 6000 5377 4000 2000 558 89 18 5 6 0 0 1 2 3 4 No. Patterns 17/20 Six Examples in One This class combines 6 patterns: – – – – – – ImmutableBox Sampler / Restricted Creation Overrider Sink FunctionObject DataManager public class ParameterMode { public static final ParameterMode IN = new ParameterMode("IN"), INOUT = new ParameterMode("INOUT"), OUT = new ParameterMode("OUT"); private String mode; private ParameterMode(String m) { mode = m; } public String toString() { return mode; } { 18/20 Statistical Inference • Pattern prevalence is a distinguishing mark of software – Different collections tend to use different patterns at different levels. – The differences in prevalence are statically significant • Independent implementations of the same specification tend to use the same pattern. • Progressive versions of the same software product tend to patterns at the same prevalence level. 19/20 Conclusions and Further Work • • • • • • There is no such thing as classical classes… Better vocabulary for frameworks, design, understading. Teach the tools of the trade Automatic Detection Tools Automatic Corrections Tools Nano-patterns: same, but on methods – – – – – – Setter Getter Factory Delegator Forwarder Verifier 20/20 Our notion of a typical class • (An excerpt from an advanced course in OOD) • Our research shows that many of the classes in the “real world” are of a very limited scope: – – – – – Pool, Stateless (10.8%) FunctionObject (6.84%) Box, ImmutableBox, CompoundBox (19.8%) Sink (13.3%) Etc. 21/20 Our notion of inter-class relationships The analysis of relationships between classes and within parts of a class is central to the design of a system: §24.3.2 Inheritance relationships §24.3.3 Containment relationships §24.3.5 Use relationships §24.3.6 Use relationships §24.3.7 Relationships within a class (The C++ programming Language) • Again, the popularity of simple implementation patterns, suggests otherwise 22/20