Patterns and Refactoring in Android Presenter: Mihai Fonoage Class: Android Mobile Component Development Date: February 5, 2010 Outline • Patterns – Model-View Controller (MVC) • Android Example – Factory Method • Java Example – Builder • Java Example – Strategy • Java Example + Android Example • Refactoring 2 Patterns • Pattern = a way of solving a particular class of problems in the most general and flexible way • Principles: – A design is finished when you cannot take anything away from it [1] – Occam’s razor: the simplest solution is the best [2] – Avoid duplication of logic and structure [1] • i.e. both pieces of code do the same thing 3 Patterns (cont.) • Types of Patterns: – Architectural Patterns • Expresses a structural organization of the software system • The pattern is followed by the entire system • Example: Model-View-Controller (MVC) – Design Patterns • Express the design of modules/components and their connections • Example: Factory, Builder, Strategy 4 Patterns (cont.) • Why Use Patterns? [3] – They have been proven • Have been used, tested, and proven – They are reusable • Can be adapted to different problems – They are expressive • Effectively express solutions 5 Outline • Patterns – Model-View Controller (MVC) • Android Example – Factory Method • Java Example – Builder • Java Example – Strategy • Java Example + Android Example • Refactoring 6 Patterns Model-View-Controller • Separates the business logic from the user interface • Model - represents the data and the business logic of the application – Android: plain Java class, or a Content Provider (objects used for managing persistent data) • View – graphical representation of the data (of the model) – Android: layout files describing the views • Controller – receives user actions, dispatches them to the model, and updates the view – Android: Activities 7 Patterns (cont.) Model-View-Controller User 1. user action Controller 2. notify model 5. render/update 4. notify of the update View Model 3. update 8 Patterns (cont.) Model-View-Controller • Features [4]: – Views can change independently from controllers and models – Model hides internal details of the data from the view and controller – The model can be reused in other areas (desktop, Java ME, enterprise, etc) 9 Patterns (cont.) Model-View-Controller • Principles [4]: – Model, View, Controller is based on: • Separation of concerns • Loose coupling – Increases cohesion in individual components • Components have focused, strongly-related responsibilities – Minimizes the impact of changes in other layers of the application • i.e. changing the view will not impact the model – Increases the overall complexity • MVC adds many new components 10 Outline • Patterns – Model-View Controller (MVC) • Android Example – Factory Method • Java Example – Builder • Java Example – Strategy • Java Example + Android Example • Refactoring 11 Outline • Patterns – Model-View Controller (MVC) • Android Example – Factory Method • Java Example – Builder • Java Example – Strategy • Java Example + Android Example • Refactoring 12 Patterns Factory Method • It’s a creational pattern [5], dealing with creating objects in a suitable way • Create objects without specifying the exact class of object that will be created – Define a separate (factory) method for creating objects – Subclasses override the method to provide the derived type of object to be created • When adding a new type, you modify only the factory 13 Patterns (cont.) Factory Method MainClass shape = ShapeFactory.createShape(type); Circle «interface» Shape ShapeFactory +createShape(in type) : Shape Rectangle 14 Patterns (cont.) Factory Method • Benefits: – Allow subclasses to chose which type of object to create – Factory methods can have descriptive names • Constructors must have the same name – Factory methods encapsulate the creation of objects • Separate the user of those objects form creating them 15 Outline • Patterns – Model-View Controller (MVC) • Android Example – Factory Method • Java Example – Builder • Java Example – Strategy • Java Example + Android Example • Refactoring 16 Outline • Patterns – Model-View Controller (MVC) • Android Example – Factory Method • Java Example – Builder • Java Example – Strategy • Java Example + Android Example • Refactoring 17 Patterns Builder • It’s a creational pattern [5], dealing with creating objects in a suitable way • Separate the complex construction from the “representation”, allowing multiple different representations – The construction process stays the same – Resulting object has different possible representations • Creates an object in multiple steps as opposed to the Factory – More control over the final object 18 Patterns (cont.) Builder ManageCreation +create() Builder +buildPart() ConcreteBuilder Product +buildPart() 19 Outline • Patterns – Model-View Controller (MVC) • Android Example – Factory Method • Java Example – Builder • Java Example – Strategy • Java Example + Android Example • Refactoring 20 Outline • Patterns – Model-View Controller (MVC) • Android Example – Factory Method • Java Example – Builder • Java Example – Strategy • Java Example + Android Example • Refactoring 21 Patterns Strategy • It’s a behavioral pattern [6] used for identifying common communications patterns between objects • Algorithms can be selected at run-time – Algorithms are encapsulated in objects – Each algorithm is called a strategy • Use when: – You need different variants of an algorithm – To avoid multiple conditional statements 22 Patterns (cont.) Strategy Context -strategy «interface» Strategy +algorithm() ConcreteStrategy1 ConcreteStrategy2 +algorithm() +algorithm() 23 Outline • Patterns – Model-View Controller (MVC) • Android Example – Factory Method • Java Example – Builder • Java Example – Strategy • Java Example + Android Example • Refactoring 24 Outline • Patterns – Model-View Controller (MVC) • Android Example – Factory Method • Java Example – Builder • Java Example – Strategy • Java Example + Android Example • Refactoring 25 Refactoring • Refactoring = a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior [7] • Cleaning up code in a more efficient and controlled manner 26 Refactoring (cont.) • Reasons for Refactoring: – Improving the design of the software • When changing code, the code looses its structure => it becomes harder to see the design – Makes software easier to understand • How long it takes for the next developer (can still be you) to make a change to an existing code is important – Refactoring will make your code more readable – You code will better communicate its purpose 27 Refactoring (cont.) • Reasons for Refactoring (continued): – Helps you find bugs • Refactoring code implies getting to know the code really well => helps spotting the bugs – Helps you develop code faster • Good design goes hand-in-hand with rapid development – Refactoring stops the design of a system from decaying 28 Refactoring (cont.) • When should you refactor: – When you add a function • Take the example of the Calculator: adding a new operation => refactor first using the Strategy pattern => adding the operation is now easier => everything goes more quickly and smoothly – When you need to fix a bug • If you got a bug, it means that you need to refactor because your code was not clear enough for you to see there was a bug 29 Refactoring (cont.) • Duplicated Code: – Same code structure in more than one place • i.e. same expression in two methods of the same class – Solution: Extract Method – see Java example • Long Method – Harder to understand – Find parts of the method that go nicely together and make a new method (Extract Method) 30 Refactoring (cont.) • Large Class – Class is trying to do too much => too many instance variables => low cohesion – Solution: Extract Class – see Java example • Long Parameter List – Used to pass in as parameters everything needed by a routine • Hard to understand – With objects, this changes => pass enough to a method so that it can get to everything it needs • A method’s host class usually has everything needed – if not, other objects can get it for you – Solution: Replace Parameter with Method, or Send the whole object – see Java example 31 References • • • • [1] Bruce Eckel, Thinking in Patterns [2] http://en.wikipedia.org/wiki/Occam's_razor [3] http://java.sun.com/blueprints/patterns/ [4] Bryan Basham, Kathy Sierra, Bert Bates, Head First Servlets & JSP • [5] http://en.wikipedia.org/wiki/Creational_pattern • [6] http://en.wikipedia.org/wiki/Behavioral_pattern • [7] Martin Fowler, Kent Beck, John Brant, William Opdyke, Don Roberts, Refactoring: Improving the Design of Existing Code 32