Your SlideShare is downloading. ×
Advanced android
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Advanced android


Published on

Published in: Technology, Education
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. Android Application Top Down Design with Patterns Boris Farber 5/31/2013
  • 2. Instructor • Senior Software Engineer at Varonis • Before worked for Samsung, Redbend and few start ups • M.Sc. Computer Science and MBA in Marketing • Android Related Stuff – Author of Profiterole Big Data on Android – Key Member in Docomo Lock leading Android lock security application – P2P and Java compilations Android open projects participation (JXTA and ANTLR ) – Analytics and Security for Redbend and Data Governance for Varonis
  • 3. Teaching  • Basic Android • Advanced Java • Big Data/Map Reduce • Design Patterns • API Design and Android Seminars
  • 4. This Seminar • Understanding application architecture, its advantages and limitations is really important for developing good applications. • Existing descriptions of Android application architecture I have seen so far are not very helpful. • Android site provides a lot of how instead of what and why • Stack Overflow/Blogs – content mining, digging checking • Android sources – the best, but no time and capacity to understand completely
  • 5. This seminar • We are going to review Android Application Patterns and Practices Top Down approach • These practices I used/collected over the years reviewing various Android projects usually via my or other mistakes I have seen • We concentrate “on what and why” should be expected on each level • In your work as Senior Developer/Architect will have a “check list” of what to expect • No copy paste of APIs from Google
  • 6. This Seminar contd’ • We are going to touch various aspects at very high level – Lack of time – I can’t cover everything • We have to run on subjects • Your participation/share is welcome !
  • 7. When I get the APK • I would like to check if the intellectual property could be leaked • It is very easy to disassemble APK as we see in next slides
  • 8. 2 directions to disassemble • Access to source code (we cover now) – Intellectual property – Trade secrets • Post Compile Injection (out of scope) – Modify functionality – Alter access and rights
  • 9. Post Compile Injection (out of scope) • Apktool • • Is a tool for reverse engineering 3rd party, closed, binary Android apps. It can decode resources to nearly original form and rebuild them after making some modifications; it makes possible to debug smali code step by step. • Smali – assember and disassembler tools for Android’s dex format
  • 10. Dex 2 Jar • Convert dex format to jar • Written by Chinese student • • We use it for source disasemple
  • 11. Dex2Jar
  • 12. JD Decompiler • Cool from previous step we have jar file • JD decomplier is tool to convert jar/class files to java sources ! •
  • 13. JD Decompiler
  • 14. Obfuscation • Obfuscation is the deliberate act of creating obfuscated code, i.e. source or machine code that is difficult for humans to understand. • Programs known as obfuscators transform readable code into obfuscated code using various techniques.
  • 15. Why • Mainly to defend against Software Reverse Engineering • We can only make it more difficult for reverse engineers • Available obfuscating tools work in the same way as compiler optimizers • Reduce required space and time for compilation
  • 16. Layout Obfuscation • Changing variables • Removing comments • Both methods: – Free of cost – One way functions
  • 17. Data Obfuscation • Encoding for(int i = 0; i < 100; i++ ){} f(i) = 2*i+5 for(int i = 5; i < 205; i =i+2){} • Split array • Change ordering – Variable declaration spread out
  • 18. • Hide information flow – Dead code – note that compiler removes dead code, however obfuscators run after compilation complete on class files. – Parallelize Code Control Obfuscation
  • 19. Proguard • Android comes with obfuscation proguard tool, which is good • However never ship out the APK before disassembling it by yourself
  • 20. Check Commercial Tools • DashO o • I worked with, strongly recommended
  • 21. Use NDK • For exceptional situations (which are rare !) consider using NDK and write your algorithms in native code • For example you have a really fast number crunching, such as matrix inverse algorithm; and you don't want it to be known, you can write in C and ship • ARM disassembly is not good • NDK usually used for legacy code, such as cross platform mobile library for OMA DM protocol written in C • NDK is in Appendix 1, for interested
  • 22. References • Consider the following
  • 23. Android is getting better • Application verification — Users can choose to enable “Verify Apps" and have applications screened by an application verifier, prior to installation. App verification can alert the user if they try to install an app that might be harmful; if an application is especially bad, it can block installation. • From Jelly Bean the application will be downloaded encrypted via AES symmetric key between Play and Device • jelly-bean.html • Way to break build custom ROM.
  • 24. Plan • Application Integration Layer – MVVM – Key Classes – Communication Mechanisms • Analysis “Android SDK and API are for writing user applications and not core libraries”
  • 25. Android application usually consists of: • Java classes that are subclasses of main Android SDK classes: – Views – Activities/Fragments – Content Providers – Services – Intents • Manifest • Resources like strings, images etc • Files
  • 26. MVVM • Android application architecture follows very modern Model-View-ViewModel(MVVM) architectural pattern in how it handles relationships between GUI and a logic supporting the GUI. • What are corresponding Android components ?
  • 27. MVVM • MVVM architecture was created in attempt to solve a disparity of skills which occurs when e.g. a Java developer tries to build GUI in Swing or a Visual C++ developer tries to build GUI in MFC. • Developers are smart folks and have many skills, but building GUIs requires quite different talents than those the developers usually have. • It is work more suitable for GUI designers. Good GUI designers are more artists and a user experience professionals than experts in designing and writing code • Clearly, it would be better if a GUI designer was designing a GUI and a developer was writing a code which implements a logic behind the GUI, but such technologies as Swing or MFC simply do not allow this.
  • 28. MVVM – separate responsibility • GUI development is done by a GUI designer in technology more or less natural for this task (XML) • Logic behind the GUI is implemented by a developer as ViewModel (which actually means Model of View) component • Functional relationships between GUI and ViewModel are implemented through bindings that essentially define rules like “if a button A is clicked, method onButtonAClick() should be called on ViewModel”. Bindings can be written in the code or defined in a declarative way in XML.
  • 29. MVVM • MVVM architecture is used in one way or another by all modern GUI technologies like Microsoft WPF (XAML) and Silverlight, HTML5
  • 30. Context • Android Context class – mighty player behind the scene • The class is rarely mentioned in various manuals and articles; at the same time it is arguably the most important class in the whole set of Android SDK.
  • 31. Context • It is ancestor (although not a direct parent) of such classes Activity, Application, Service classes • Context also implements the biggest portion of functionality of those classes. • To summarize Context class provides access to various infrastructure functionalities provided by Android • Do you think Context is a good name ?
  • 32. Context Getting Access to Managers • AssetManager • AccessebilityManager • AccountManager • ActivityManager • AlarmManager • AudioManager • …
  • 33. Access to • API for working with database files (not DB functionality!) • API for working with files and directories • API for working with permissions • API for binding to services and starting/stopping them • …
  • 34. Activity • Is class and its subclasses are the ones that provide logic behind the GUI. Actually it corresponds to ViewModel in architecture pattern (MVVM). Relationship between subclasses of Activity and GUI layout is 1-to-1; normally each subclass of Activity has one GUI layout associated with it and vice-versa. Activity has a lifecycle. • During the lifecycle Activity can be in one of three states: – Active and running when its GUI is in the foreground (technically speaking – on top of activity stack) – Paused if its GUI lost focus but it is still visible. No code is executed in this state – Stopped if its GUI is not visible. No code is executed in this state
  • 35. Activity Life Cycle User implemented callbacks (template methods) that are called upon the relevant events In case you override callback please pay attention to all edges (onResume preceded onPause)
  • 36. Activity • Here is an example. Let’s assume our application has GUI screen A and GUI screen B. A user accesses screen A first and then screen B; at this point screen A is not visible anymore. • This means screen A and all logic that supports it may or may not be kept in memory.
  • 37. No Sharing Between Activities • Since there is no guarantee that objects associated with screen A exist in memory while screen B is shown, the developer writing screen B logic must not expect that a certain object instantiated for screen A is still in memory. • A side result of this is that Android architecture enforces shared nothing architectural style for Android applications. • This means that different parts of Android application can invoke each other and communicate between them only in an explicit way; there is no shared state between them in-memory, except application object
  • 38. Java Memory Model • In a “regular” Java an object is kept in memory until it is garbage collected. The garbage collection occurs only if an object does not have any reference to it from other “live” objects
  • 39. Android Memory Model • If a certain GUI gets hidden (it is not visible on the screen), there is no guarantee that it will be kept in memory even if the application intends to use it later. • It might be kept in memory alright if Android OS has enough free memory, but it can be garbage collected as well at any moment when the OS finds that it needs more free memory. • If an application process does not show any GUI to the user at the moment, it can be legitimately terminated by Android OS (there is one exception to this rule related to Android Services).
  • 40. Activity • Activity code runs only when the Activity GUI is visible and has focus. Also there is no guarantee that Activity object and its associated objects are in memory while the Activity is paused or stopped • Design carefully code in activity. One of key anti patterns is code in activity that has to be in service • Design your activities thin
  • 41. Fragments • Honeycomb introduced Fragments to support reusing portions of UI and logic across multiple activities in an app • The larger screen sizes found on most tablets added an extra layer of complexity to Android development—a layout designed for the small screen does not necessarily work as well for larger screens, and vice-versa • Fragments can be thought of as user interface modules. They let the developer divide up the user interface into isolated, reusable parts that can be run in separate Activities. At run time, the Activities themselves will decide which Fragments to use
  • 42. Example
  • 43. Activity Fragments • Activity uses APIs of FragmentManager to load relevant fragments (add, remove, replace …) • Activity serves as an intermediary between fragments. – Fragments don’t have intent filters; an Intent can’t directly trigger a fragment. – Let the activity respond to intents and fragment callbacks. – The activity will know if it can “route” a event to a fragment it contains, or if it needs to start another activity to handle the event • For backward compatibility on pre-Honeycomb devices use v4 support library • Problem – increases application size and processing
  • 44. View • View class is a base class for all GUI widgets. Android application GUI is a tree of instances of its subclasses i.e. GUI widgets. • One can build the tree programmatically, but this is not how you should do this. A lot of companies provide “same layout” for iPhone/Android based on programmatically based UIs this is always wrong • GUI is defined by an XML GUI definition (layout file) and inflated automatically into a tree of corresponding objects at runtime. • View follows Composite pattern
  • 45. Content Provider • Is a class and its subclasses correspond to Model in MVVM architecture. In most practical cases it is a wrapper around SQLite database with rather fancy URI-based way to query the database. • Given that query()method of ContentProvider returns Cursor object which is quite similar to JDBC ResultSet interface and the way how the query is made, • Seems real purpose of ContentProviders is to encapsulate a database.
  • 46. Service • How do you define it ? • Why it is there is first place ?
  • 47. Why Service ? • Activity is active and running only when its GUI is on foreground. As soon as another Activity GUI comes in front of the current one, the current one stops running even if it was doing something. • What if you need to perform certain operation even when the process which tries to perform it is not on foreground? You can’t do this with Activity. • Can’t do this with ContentProvider as well since it does not have its own lifecycle and it can run only while Activity which uses it is active.
  • 48. Service • Here Service comes to the rescue. It can be executed even when the process it runs within is not on a foreground. • So if you develop Activity which must perform a long running operation which should be completed even while running in background, you should create Service implementing that operation and invoke it from Activity.
  • 49. Manifest(all global data) • It names the Java package for the application. The package name serves as a unique identifier for the application. • It describes the components of the application — the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each of the components and publishes their capabilities (for example, which Intent messages they can handle). These declarations let the Android system know what the components are and under what conditions they can be launched. • It determines which processes will host application components. • It declares which permissions the application must have in order to access protected parts of the API and interact with other applications. • …
  • 50. Resources • Pictures • GUI layouts (XML files) • Menu definitions (XML files) • Textual strings • – programmatic/type safe access to all resources • Hack – applying reflection to R class thus can do programmatic manipulation of layouts in run time.
  • 51. Communication Patterns • Message Passing • Publisher Subscriber • Content Provider • Service – Local – Remote
  • 52. Message Passing public void do() { Intent explicitIntent = new Intent(this,InvokedActivity.class); explicitIntent.putExtra(“Key”, “Value”); startActivity(explicitIntent); } Connect between components Pass values Start !
  • 53. Message Passing • Simplest communication mechanism. It is used to start an Activity or a Service. It is implemented via three methods on Context and one method on Activity class: – startActivity – startActivityForResult – startService • In both cases Intent class plays a role of a message passed (and only zero or one component gets it)
  • 54. Message Passing • How does Android know which Activity or Service should receive the message? • Intent may specify a name of the target component explicitly. Such Intents are called “explicitIntents” and they specify a target component via setComponent or setClass methods of Intent class. • Implicit Intents – only the action (based on intent resolution) – late binding
  • 55. Publisher Subscriber GMail Contacts Home Blogger Chat Client component makes a request for a specific action “Pick photo” Picasa System picks best component for that action New components can use existing functionality Blogger Photo Gallery
  • 56. Publisher Subscriber • Publish/subscribe communication mechanism involves the same Intent class as a message and the same intent filters as a resolution mechanism defining target components, but it works quite differently. • Intents used for publish/subscribe communication are called “broadcast Intents”. Those broadcast Intents can be delivered to BroadcastReceivers only. SinceBroadcastReceiver is a class and Activity and Service are classes as well, neither Activity not Service can receive the broadcast Intent (Java prohibits multiple inheritance). • Also, unlike Intent used for message passing, a single broadcast Intent can be delivered to many target components.
  • 57. 2 Mechanisms • Normal broadcast which is implemented by sendBroadcast() and sendStickyBroadcast() methods of Contex t class • Ordered broadcast which is implemented by sendOrderedBroadcast() and sendOrderedStickyBroadcast()
  • 58. Publisher Subscriber • Normal broadcast mechanism delivers the Intent to all eligible BrodcastReceivers asynchronously and they act on it independently • One BrodcastReceiver can’t affect either how another BrodcastReceiver is reacting on the Intent or whether the Intent is delivered to another BroadcastReceiver. It is a regular pub/sub pattern.
  • 59. Ordered Broadcast Receivers • Ordered broadcast mechanism delivers the Intent to eligible BrodcastReceives in a sequential manner, i.e.toone at a time. Due to this each BrodcastReceiver can potentially: • Use results produced by previous BroadcastReceivers that worked on the sameIntent • If needed, abort further processing of the Intent • By executing ordered broadcast, a component which initiated it gets opportunity to receive the result of processing the Intent by all BroadcastReceivers in the chain. • Ordered broadcast actually is an implementation of chain of responsibility pattern. • Haven’t used them yet  Your experience ?
  • 60. Sticky • Sticky broadcasts are versions of the corresponding regular broadcasts. • The difference is the Intent is available until it is explicitly removed by removeStickyBroadcast method of Contextclass. Please note, this type of broadcast should be used with great caution since not removing the sticky Intents will result in a memory leak. • One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action.
  • 61. Late binding of ContentProvider • ContentProvider class is essentially a wrapper around SQLite database • There are many ways how Android code can use ContentProviders. – Proxy - ContentProviderClient, which implements proxy design pattern – Cursor - Some of them return an instance of Cursor class which allows iterating through data set returned byContentProvider.
  • 62. Late binding and Inter-process Procedure Communication (IPC) of Service • Apart of ContentProvider class there is Service class which architecturally plays the same role of Model in MVVM architecture pattern. • There are two types of Service and each requires a separate communication mechanism: – Local Service which runs within the same process where it is invoked. – Remote Service which runs within another process from where it is invoked. • It is worth mentioning that the same Service may be used as both Local and Remote; the difference is in where the component which invokes the Service is located (within the same process or in another process).
  • 63. Local Service • Services which can be bound only from the same process. • Implement the service's interface extending the android.os.Binder class • Return an instance of the implemented interface from the service's onBind()callback • The client(Activity) will use the achieved object to execute methods remotely on the bound service • The implementation could allow even calls on Service's methods!
  • 64. Remote Service • Such type of service is accessed through a sort of IPC call implemented using either Messenger or AIDL (Android Interface Definition Language) • If you need to implement a bound Service which have to be reached from outside your application but don't want to deal with AIDL use the android.os.Messenger class! • This class implements a message passing channel handling transparently the IPC mechanism • Messengers are associated to a custom Handler implementation which will handle the incoming messages.
  • 65. Your Classes • Of course, Android application developer is not limited to just extending Android SDK classes. She can write her own classes as she wants. But all they will be just “helper classes” of sorts for those main classes derived from Android SDK classes. • Make sure you add them in right place
  • 66. UI Structure Widget Unique Detail Search Common Action 1 Common Action 2 Action Bar App Home Search Common Action 1 Common Action 2 Activities App Dashboard Activities
  • 67. Google’s Recommendation • Your application most of the time sleeping, but has to respond fast
  • 68. Architectural Analysis • Great Architectural Decisions – Linux kernel – free, stable, robust – VM based applications – cross device platform (ARM, x86 …) – MVVM –most modern UI model
  • 69. Architectural Analysis • Questionable Implementation Issues – Why both Service and Activity inherit from Context, violation of Solid principle. Better to pass context as parameter similar to servlets API – Service and Content have a lot of common functionality both are model in MVVM, why need both ? Or at least provider a common ancestor – Intent plays too many roles … why not to have separated classes – MVVM connection mechanisms – last thing to say they are easy
  • 70. References • deep analysis took many ideas (with permission) • Android Developer’s site • Various blogs • Stackoverflow • Android sources
  • 71. Code Bloat in Application • Code bloat is bad • Usually the code bloat is in with our business logic, because the other parts are Android framework components that we extend • In this part we explore relevant design patterns to cope with code bloat in our applications
  • 72. Gang Of Four
  • 73. Gang of 4 Intro • The book's authors are Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides with a foreword by Grady Booch. They are often referred to as the Gang of Four, or GoF • The book is divided into two parts, with the first two chapters exploring the capabilities and pitfalls of object- oriented programming, and the remaining chapters describing 23 classic software design patterns
  • 74. GoF Pattern Structure • Pattern Name and Classification: A descriptive and unique name that helps in identifying and referring to the pattern. • Intent: A description of the goal behind the pattern and the reason for using it. • Also Known As: Other names for the pattern. • Motivation (Forces): A scenario consisting of a problem and a context in which this pattern can be used. • Applicability: Situations in which this pattern is usable; the context for the pattern. • Structure: A graphical representation of the pattern. Class diagrams and Interaction diagrams may be used for this purpose. • Participants: A listing of the classes and objects used in the pattern and their roles in the design. • Collaboration: A description of how classes and objects used in the pattern interact with each other. • Consequences: A description of the results, side effects, and trade offs caused by using the pattern. • Implementation: A description of an implementation of the pattern; the solution part of the pattern. • Sample Code: An illustration of how the pattern can be used in a programming language • Known Uses: Examples of real usages of the pattern. • Related Patterns: Other patterns that have some relationship with the pattern; discussion of the differences between the pattern and similar patterns.
  • 75. Cont • Structural – Composite – Decorator – Adapter – Flyweight – Bridge • Behavioral – Observer – Command – State
  • 76. Cont • Behavioral – Iterator – Interpreter – Mediator – Memento – Visitor – Template Method – Strategy Chain of Responsibility
  • 77. Pattern Definition 8 2 • A particular recurring design problem that arises in specific design contexts, and presents a well-proven generic scheme for its solution. • The solution scheme is specified by describing its constituent components, their responsibilities and relationships, and the ways in which they collaborate • Context(Problem) + Structure(UML and implementation)
  • 78. A pattern must: • Solve a problem- it must be useful! • Have a context - it must describe where the solution can be used • Recur - it must be relevant in other situations • Teach - It must provide sufficient understanding to tailor the solution • Have a name - it must be referred to consistently
  • 79. Design Patters – Format & Structure • Christopher Alexander and "A Timeless Way of Building“ • A pattern is a careful description of a perennial solution to a recurring problem within a building context, describing one of the configurations which brings life to a building. • Each pattern describes a problem which occurs over and over again in our environment, and then describes the core solution to that problem, in such a way that you can use the solution a million times over, without ever doing it the same way twice." • A pattern language is a network of patterns that call upon one another. Patterns help us remember insights and knowledge about design and can be used in combination to create solutions.
  • 80. Design Patterns are not ! • Patterns fetish – Try to incorporate as much patterns as possible • Wrong/incomplete understanding of the context
  • 81. Design Patterns are not ! • Abuse  “My module incorporates 17 of 23 GoF patterns !”  Don’t confuse design patterns with always- do rules • Don’t to start using design patterns. All of them. At once. Think ! Evaluate !
  • 82. Benefits • Design patterns enable large-scale reuse of software architectures. They also help document systems to enhance understanding • Patterns explicitly capture expert knowledge and design tradeoffs, and make this expertise more widely available • Patterns help improve developer communication. Pattern names form a vocabulary • Patterns help ease the transition to object- oriented technology (refactoring …)
  • 83. Bloat Code If(metaDataElement.getState() == State.Update && metaDataElement.getState != State.Requested ) { doA() return; } else If(metaDataElement.getState() == State.Process || metaDataElement.getState != State.META ) …
  • 84. State
  • 85. State Functional Requirement • An object’s behavior is a function of its state, and it must change its behavior at run-time depending on that state. • An application is characterized by large and numerous case statements that control the application behavior (Why is it bad ?)
  • 86. State
  • 87. Solution • Identify an existing class, or create a new class, that will serve as the “state machine” from the client’s perspective. That class is the “wrapper” class. • Create a State base class that replicates the methods of the state machine interface. Each method takes one additional parameter: an instance of the wrapper class. The State base class specifies any useful “default” behavior. • Create a State derived class for each domain state. These derived classes only override the methods they need to override. • The wrapper class maintains a “current” State object. • All client requests to the wrapper class are simply delegated to the current State object, and the wrapper object’s this pointer is passed. • The State methods change the “current” state in the wrapper object as appropriate.
  • 88. Analysis • State objects are often Singletons. • Flyweight explains when and how State objects can be shared. • The implementation of the State pattern builds on the Strategy pattern. The difference between State and Strategy is in the intent. With Strategy, the choice of algorithm is fairly stable. With State, a change in the state of the “context” object causes it to select from its “palette” of Strategy objects.
  • 89. Solution • Class MetaDataElement holds State current object • Classes (from State interface) – StateApproved – StateSynced – …. • Each State object holds the relevant transitions related to it • Easy to add new states
  • 90. Code Bloat • A lot of code that is not clear what is doing and why is needed • Classes like actions/commands etc’ • Parsing logic in all places • Switch cases and ifs
  • 91. Interpreter
  • 92. Interpreter Functional Requirement • A class of problems occurs repeatedly in a well-defined and well-understood domain. If the domain were characterized with a “language”, then problems could be easily solved with an interpretation “engine”.
  • 93. Interpreter
  • 94. Problem • Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language. • Map a domain to a language, the language to a grammar, and the grammar to a hierarchical object-oriented design.
  • 95. Solution • Decide if a “little language” offers a justifiable return on investment. • Define a grammar for the language. • Map each production in the grammar to a class. • Organize the suite of classes into the structure of the Composite pattern. • Define an interpret(Context) method in the Composite hierarchy. • The Context object encapsulates the current state of the input and output as the former is parsed and the latter is accumulated. It is manipulated by each grammar class as the “interpreting” process transforms the input into the output.
  • 96. Analysis • Considered in its most general form (i.e. an operation distributed over a class hierarchy based on the Composite pattern), nearly every use of the Composite pattern will also contain the Interpreter pattern. But the Interpreter pattern should be reserved for those cases in which you want to think of this class hierarchy as defining a language. • Interpreter can use State to define parsing contexts. • The abstract syntax tree of Interpreter is a Composite (therefore Iterator and Visitor are also applicable). • Terminal symbols within Interpreter’s abstract syntax tree can be shared with Flyweight. • The pattern doesn’t address parsing. When the grammar is very complex, other techniques (such as a parser) are more appropriate.
  • 97. Solution • Take ideas from other languages to implement mini interpreter
  • 98. Code Bloat • If(isCollision) if(Collision == Take their) Action.doTakeThier else (Collision == TakeLocal) Action.doTakeLocal … What is more actions needed and more collision types be available (such as merge or notify them)
  • 99. Strategy
  • 100. Strategy Functional Requirements • We want to define a family of algorithms and make them interchangeable. • We want let the algorithms vary independently from clients that use them
  • 101. Route to Airport via various means
  • 102. Strategy
  • 103. Solution • Identify an algorithm (i.e. a behavior) that the client would prefer to access through a “flex point”. • Specify the signature for that algorithm in an interface. • Bury the alternative implementation details in derived classes. • Clients of the algorithm couple themselves to the interface.
  • 104. Analysis • Strategy is like Template Method except in its granularity. • State is like Strategy except in its Problem. • Strategy lets you change the guts of an object. Decorator lets you change the skin. • State, Strategy, Bridge (and to some degree Adapter) have similar solution structures. They all share elements of the ‘handle/body’ idiom. They differ in Problem - that is, they solve different problems. • Strategy objects often make good Flyweights.
  • 105. Solution CollisionAction HandleCollision(CollisionStrategy s, File f) { return s.appplyStaregy(f) }
  • 106. • In this part we are going to explore the Effective/right usage of the Java i.e. linqa franca of Android • Cover the important topics relevant for Android • Mastering effective language usage will leverage you code and applications in terms of: – Reusability – Security
  • 107. Based on Effective Java Book
  • 108. Utility Classes • Class that is just grouping of static methods and static fields. • Bad reputation – abuse them while thinking in terms of objects • java.lang.Math , java.util.Arrays
  • 109. Utility classes • These classes are not designed to be instantiated (nonsense for such objects) • However without constructor , the complier provides synthesized empty default constructor. • To a user this constructor is un- distinguishable
  • 110. Wrong Solution • Make class abstract doesn’t work (the class can be subclassed and the subclass can be instantiated) • Misleads the user class is designed for inheritance.
  • 111. Solution public class UtilityClass{ private UtilityClass(){ throws new AssertionError(); } }
  • 112. Discussion • Constructor is private thus invisible outside class • AssertionError provides insurance in case the constructor is accidentally invoked inside class • No subclasses
  • 113. Classes and Interfaces • When class implements an interface, the interface serves as type that can be used to refer to instances of the class • It is inappropriate to define interface for any other use
  • 114. Bad Example public interface Constants{ static final int NUM1=0; static final int NUM2=0; static final int NUM3=0; }
  • 115. Discussion • Class uses constants internally is an implementation data • Confuses users • Worse interface is a commitment, in future class modified no use of constants , the class still polluted with constants
  • 116. Better version public class MyConstants{ // prevent instantiation private MyConstants(){} static final int NUM1=0; static final int NUM2=0; static final int NUM3=0; }
  • 117. Intro • A nested class is a class defined within another class to serve it: – Static member class – Non static member class – Anonymous class – Local class • The last three are inner classes
  • 118. Static member classes • Public helper class used with conjunction with its outer class • Access to all static outer class private members • Associated with class and not object name
  • 119. Static member class class Filter{ static class Criterion{ } } filter.addCriterion(new Filter.Criterion());
  • 120. Non-static member class • Each instance associated with enclosing instance of its containing class • Association takes time and place • Common usage Adaptor pattern
  • 121. Non static member class (adaptor example) public class MySet<E> extends AbstractSet<E>{ public Iterator<E>iterator(){ return new MyIterator(); } private class MyIterator implements Iterator<E>{ } }
  • 122. Rule • If you declare a member class that doesn’t require access to an enclosing instance , always put static modifier in its declaration
  • 123. Anonymous class • Declared and instantiated with in the same statement • No name and instantiated only one
  • 124. Anonymous class String[] filelist = f.list(new FilenameFilter() { public boolean accept(File f, String s) { return s.endsWith(".java"); } }); // Don't forget the parenthesis and //semicolon that end the method call! …
  • 125. Local class • A local class is declared locally within a block of Java code, rather than as a member of a class • Typically, a local class is defined within a method, but it can also be defined within a static initializer or instance initializer of a class.
  • 126. Local class // This method creates and returns an Enumeration //object public java.util.Enumeration enumerate(){ // Here's the definition of Enumerator // as a local class class Enumerator implements java.util.Enumeration { } // Now return an instance of the //Enumerator class defined directly //above return new Enumerator(); }
  • 127. Intro • Enums were added at Java 1.5 • Enumerated type -is a type whose values consist of a fixed set of constants • In Java Enum is a class (as opposed to C++)
  • 128. Don’t Do it(int Enum pattern) final int Apple1=1; final int Apple2=2; final int Apple3=3; final int Orange1=1; final int Orange2=3; • No type safety (mix apples with oranges) • No convenience
  • 129. Fix public enum Apple {APP1,APP2}; public enum Orange {ORANGE1,ORANGE2} ;
  • 130. Basic Idea • Enums are classes that export one instance for each enumeration constant via a public static final field • Instance controlled • Generalizations of singletones
  • 131. Static member classes • Public helper class used with conjunction with its outer class • Access to all static outer class private members • Associated with class and not object name
  • 132. Static member class (look at list) public enum Planet { MERCURY(3.302e+23, 2.439e6), private final double surfaceGravity; // In m / s^2 private static final double G = 6.67300E-11; // Constructor Planet(double mass, double radius) { surfaceGravity = G * mass / (radius * radius); } public double surfaceWeight(double mass) { return mass * surfaceGravity; // F = ma } }
  • 133. Notes from example • Constructor inside enum • Enums are immutable , thus all fields final • Static values() array
  • 134. Design • Enum should be top level class • Consistency across the API
  • 135. Don’t do it/Ill design try{ int i=0; while(true) range[i++]. operate; }catch(ArrayOutOfBo unds…){ } • May be save array checking overhead - WRONG • Exception no fast design incentive • Try/catch – optimization limit • JVM optimizes array check
  • 136. Rule • Use exceptions only for exceptional conditions • Never use exceptions for ordinary control flow • A well designed API must not force its clients to use exceptions for ordinary control flow
  • 137. Checked Exceptions • Try/catch block • Use only for conditions from which the caller can reasonably expect to recover • invalid user input, database problems, network outages, absent files • Provide API to check the state
  • 138. Runtime Exceptions • Programming errors, pre-conditions violations • ArrayIndexOutOfBounds ,IllegalArguments, NullPointer,IllegalState
  • 139. Favor The Use Of Standard Exceptions • API easier to learn • Standard reuse • Smaller memory footprint
  • 140. Most Commonly Reused • IllegalArgumentException • IllegalStateException • NullPointerException • IndexOutOfBoundsException • ConcurrentModificationException • UnsupportedOperationException
  • 141. Throw Exceptions Appropriate To the Abstraction • Higher layers should catch lower level exceptions and, in their place , throw exceptions that can be explained in terms of higher level abstractions 1 5 2
  • 142. Code Example Translation try{ }catch(LowLevelException e){ throw new HighLevelException(…); }
  • 143. Code Example Chaining try{ }catch(LowLevelException cause){ throw new HighLevelException(cause); }
  • 144. Exception Chaining • Don’t overuse it • Best way is to avoid low level exceptions by parameters checking