SlideShare une entreprise Scribd logo
1  sur  78
Télécharger pour lire hors ligne
Building Maintainable 
Android Applications 
! 
Kevin Schultz (@kevinrschultz) 
DroidCon NYC 2014 
! 
kevinrschultz.com 
github.com/krschultz/AndroidWeatherBuoyDemo
Apps vs Applications
Treading Water 
Time spent on features dwindles 
Infrequent releases due to high 
QA costs 
Heisenbug whack-a-mole 
Fear of change 
Infrastructure 
Bugs 
Features
Drowning 
Platform Changes 
Business Pivot 
Competitors 
Panic 
How many regressions will 
you cause when 
implementing Material 
Design?
Refactor! Rewrite!
The codebase is a mess!
Unlikely to be better next time 
Clean code is necessary but insufficient for 
maintainability 
We are state of the art today, what about next year? 
Why do Android apps always seem to become 
unmaintainable?
Android was initially for Apps 
Documentation & samples are small scale 
Old build system was deficient 
Testing tools are still sub-par 
Framework was not designed for testability 
Performance trumped clean code
You must build a system to 
counter software entropy
Software Entropy 
“As a system is modified, its disorder, or entropy, always 
increases. This is known as software entropy.” 
- Ivar Jacobson 
“Legacy code is code without tests” 
- Michael Feathers
System 
Espresso 
Functional Tests 
UI Tests 
Build 
Unit Tests App 
CI Server
System Thinking 
How will each component be tested over its lifetime? 
What leads to the minimum cost of development 
including QA time? 
If a library makes it easy to add a feature but harder to 
test, is it worth it? 
If a tool breaks CI, is it worth it?
Testing Strategy 
Customers in Production 
Manual QA by Team 
Unit Tests 
Integration tests 
Automated UI Tests
Manual Testing 
Low initial cost 
Need to acceptance test every feature at least once 
Never can be completely eliminated 
Does not scale with complexity 
Extremely expensive long term
QA Options 
Helps make manual testing 
cheaper & more effective 
Network connectivity 
Environment 
Mock Data
QA Specs 
Look at Gherkin / Cucumber for examples 
Helps to make tests more repeatable 
Can use to outsource testing to other firms 
Painful & expensive
Automated UI Testing 
Appium / UIAutomator type tests 
Usually leveraging the accessibility IDs 
Expensive, flakey 
Can be layered onto most apps after the fact
Functional Testing 
Most Android ‘unit testing’ examples are functional 
Robolectric & InstrumentationTests 
Generally scoped to an Activity / Fragment / Service 
Time consuming to run and nearly as flakey as UI tests 
Useful but should be minimized
Functional Testing Challenges 
Generic Problems 
Asynchronous 
Network based 
! 
! 
Android Specific 
Lifecycle 
Context 
Platform singletons
Functional Test in Theory 
insertMockDataIntoPreferences(conditions) 
waitForActivityAndFragmentToInitialize() 
waitForDataToLoad() 
label = findViewById() 
assertEquals(conditions, label.getText()); 
Preconditions 
Boilerplate 
Actual Test 
testWindSpeedLabel_MetricSystem
Functional Test in Practice
Pitfalls for a Functional Test 
Is the user logged in? 
Wait for Activity, Fragment lifecycle to load screen 
Wait for network call to finish 
Wait for data to load from DB 
Find the TextView 
Finally, check the TextView’s content & color
Unit Testing 
Narrow in scope, each test is 1 case for 1 method 
Do not test Android platform, therefore run quickly 
Cheap to write if architecture is designed for testing 
Flexible for refactoring 
Should be 80% of your tests
Unit Test in Theory 
testWindSpeedLabel_MetricSystem 
given(conditions) 
assertEquals(conditions, label.getText());
Unit Tests in Practice
So why is this so hard?
Activity Fragment Adapter 
ForecastActivity ForecastFragment ForecastAdapter ForecastModel
Keep Android At Arm’s 
Length
Strategies 
Covered 
Dealing with K/V Store 
ViewModels, Presenters, Custom Views 
Not Covered 
Testing network calls 
Testing SQLite / ContentProviders / ORMs
Weather Buoy 
Master list of buoys 
Detail screen with wind 
& wave forecast 
Setting to choose units 
github.com/krschultz/AndroidWeatherBuoyDemo
Tools 
Examples uses only 
Android standard JUnit & InstrumentationTests 
Mockito 
AssertJ 
Better tools exist 
Espresso 
Robolectric 
Dagger
SharedPreferences
How do you catch this?
How do you catch this?
Wrapping Preferences
Testing Preferences Wrapper
Using wrapped Preferences
Using mock Preferences
Wrapping Shared Preferences 
+ Only 1 place to test interaction w/ SharedPreferences 
+ Handle versioning 
+ Keys don’t leak out 
+ Can now mock SharedPreferences w/o Context 
- More code
UI Unit Testing Strategies
Custom Views
Optional TextView 
What happens when we refactor the layout? 
How do we know this feature doesn’t break?
Optional TextView
Testing Optional TextView
Instrument View 
Label 
Value & Units
Custom View 
+ Clean API 
+ Reusable view logic 
- Compose-ability issues
ViewModels
SharedPreferences 
ForecastFragment 
Views 
WaveForecast 
Views 
Views 
WindForecast 
Preferences 
API Client
View Models 
Add presentation logic to underlying models 
Combine multiple models 
Do not have a concept of Activity/Fragment lifecycle 
Do not have a reference to View
Using a ViewModel 
Fragment is responsible for loading models, 
networking, finding views, threading 
ViewModel is responsible for business logic 
Fragment should fail in all cases
“Presentation” Logic 
Colors, visibility 
Interaction between multiple views 
Formatting / humanizing properties 
i18n
Combining Models 
WaveForecast WindForecast Preferences 
BuoyDetailViewModel
SharedPreferences 
Preferences 
API Client 
ForecastFragment WaveForecast 
Views 
Views 
Views 
WindForecast 
ViewModel
ViewModel Creation 
No reference to view at all 
All models can be immutable
Using a ViewModel 
Create view model at the end of network call or DB fetch 
Pass Views to ViewModel for updating
Logic in a ViewModel
Pitfalls 
Creating a ViewModel getter for every view property 
Keeping references to views in the ViewModel
Testing
Use Cases 
Great for screens displaying detail about an object 
Not ideal for collections of items, but Adapters can be 
tested similarly 
Not a great fit for screens with many interactions
Presenters
Presenters 
Same general idea as ViewModel, but includes 
reference to View 
Requires coordinating with Activity/Fragment lifecycle 
Potential for Context leaks if not handled correctly 
More full featured, can take ownership of fetching data, 
threading, network calls, etc
Preferences 
ForecastFragment WaveForecast 
Views 
Views 
Views 
WindForecast 
Presenter 
View Interface
Fragment
Presenter
Fragment Continued 
User interactions delegated to presenter 
Can test using the same methods on the presenter
Presenter Continued 
All business logic belongs in presenter 
Calls back to view for update, remember the view may 
be gone
Use Cases 
Can handle state changes caused by user interaction 
very well 
Really should use Espresso / InstrumentationTests to 
ensure that click handlers call appropriate methods in 
presenter
Summary 
You are building a system, not just an app 
Cost of testing over long term becomes extremely expensive 
Find ways to keep the platform at arms length 
Consider how to test each component from the start
Further Reading 
martinfowler.com/eaaDev/uiArchs.html 
www.objc.io/issue-13/viper.html
Contact 
@kevinrschultz 
github.com/krschultz/AndroidWeatherBuoyDemo 
kevinrschultz.com
Questions?
Backup
Law of Demeter w/ Context
Image Attribution 
! 
Tent - 
House - https://www.flickr.com/photos/18702768@N04/2294709357 
Cake - https://www.flickr.com/photos/personalcreations/14888675499
Long Term Cost 
70 
52.5 
35 
17.5 
0 
Manual Unit Tests UI Tests Test Fixtures 
1 2 3 4 5 6
Stage 1 -> No desire for tests 
Stage 2 -> Desire tests, but can’t build the test 
suite 
Stage 3 -> Have a test suite 
Stage 4 -> Nirvana. Bugs find themselves.
But I Don’t Have Business 
Logic! 
“It’s just simple data in the UI!” 
Not for long (PDP examples) 
Creating a place for the tests to go from the start 
makes it easy to add them (UUID example) 
Every single thing is small, but the sum of testing them 
all is expensive

Contenu connexe

Tendances

Diffy : Automatic Testing of Microservices @ Twitter
Diffy : Automatic Testing of Microservices @ TwitterDiffy : Automatic Testing of Microservices @ Twitter
Diffy : Automatic Testing of Microservices @ TwitterPuneet Khanduri
 
FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09Pyxis Technologies
 
Test Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionTest Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionPyxis Technologies
 
Automation testing strategy, approach & planning
Automation testing  strategy, approach & planningAutomation testing  strategy, approach & planning
Automation testing strategy, approach & planningSivaprasanthRentala1975
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Implementing Test Automation in Agile Projects
Implementing Test Automation in Agile ProjectsImplementing Test Automation in Agile Projects
Implementing Test Automation in Agile ProjectsDominik Dary
 
Android Automation Using Robotium
Android Automation Using RobotiumAndroid Automation Using Robotium
Android Automation Using RobotiumMindfire Solutions
 
Introducing Keyword-Driven Test Automation
Introducing Keyword-Driven Test AutomationIntroducing Keyword-Driven Test Automation
Introducing Keyword-Driven Test AutomationTechWell
 
Testing on Android
Testing on AndroidTesting on Android
Testing on AndroidAri Lacenski
 
Testing Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksTesting Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksŁukasz Morawski
 
Introducing Keyword-driven Test Automation
Introducing Keyword-driven Test AutomationIntroducing Keyword-driven Test Automation
Introducing Keyword-driven Test AutomationTechWell
 
ESLint Plugin for UI Tests
ESLint Plugin for UI TestsESLint Plugin for UI Tests
ESLint Plugin for UI TestsApplitools
 
Testing for Android: When, Where, and How to Successfully Use Test Automation
Testing for Android: When, Where, and How to Successfully Use Test AutomationTesting for Android: When, Where, and How to Successfully Use Test Automation
Testing for Android: When, Where, and How to Successfully Use Test AutomationTrent Peterson
 
Test Automation On Android Platform Using Robotium
Test Automation On Android Platform Using RobotiumTest Automation On Android Platform Using Robotium
Test Automation On Android Platform Using RobotiumIndicThreads
 
Engaging IV&V Testing Services for Agile Projects
Engaging IV&V Testing Services for Agile ProjectsEngaging IV&V Testing Services for Agile Projects
Engaging IV&V Testing Services for Agile ProjectsRavi Kumar
 
Test Automation Techniques for Windows Applications
Test Automation Techniques for Windows ApplicationsTest Automation Techniques for Windows Applications
Test Automation Techniques for Windows ApplicationsTabăra de Testare
 
Unit testing
Unit testing Unit testing
Unit testing dubbu
 

Tendances (20)

Diffy : Automatic Testing of Microservices @ Twitter
Diffy : Automatic Testing of Microservices @ TwitterDiffy : Automatic Testing of Microservices @ Twitter
Diffy : Automatic Testing of Microservices @ Twitter
 
FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09
 
Test Driven Development - Overview and Adoption
Test Driven Development - Overview and AdoptionTest Driven Development - Overview and Adoption
Test Driven Development - Overview and Adoption
 
Automation testing strategy, approach & planning
Automation testing  strategy, approach & planningAutomation testing  strategy, approach & planning
Automation testing strategy, approach & planning
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Implementing Test Automation in Agile Projects
Implementing Test Automation in Agile ProjectsImplementing Test Automation in Agile Projects
Implementing Test Automation in Agile Projects
 
Android Automation Using Robotium
Android Automation Using RobotiumAndroid Automation Using Robotium
Android Automation Using Robotium
 
Introducing Keyword-Driven Test Automation
Introducing Keyword-Driven Test AutomationIntroducing Keyword-Driven Test Automation
Introducing Keyword-Driven Test Automation
 
Testing on Android
Testing on AndroidTesting on Android
Testing on Android
 
Test automation process
Test automation processTest automation process
Test automation process
 
Testing Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksTesting Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation Frameworks
 
Introducing Keyword-driven Test Automation
Introducing Keyword-driven Test AutomationIntroducing Keyword-driven Test Automation
Introducing Keyword-driven Test Automation
 
ESLint Plugin for UI Tests
ESLint Plugin for UI TestsESLint Plugin for UI Tests
ESLint Plugin for UI Tests
 
Testing for Android: When, Where, and How to Successfully Use Test Automation
Testing for Android: When, Where, and How to Successfully Use Test AutomationTesting for Android: When, Where, and How to Successfully Use Test Automation
Testing for Android: When, Where, and How to Successfully Use Test Automation
 
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAUTest Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
 
Automation testing
Automation testingAutomation testing
Automation testing
 
Test Automation On Android Platform Using Robotium
Test Automation On Android Platform Using RobotiumTest Automation On Android Platform Using Robotium
Test Automation On Android Platform Using Robotium
 
Engaging IV&V Testing Services for Agile Projects
Engaging IV&V Testing Services for Agile ProjectsEngaging IV&V Testing Services for Agile Projects
Engaging IV&V Testing Services for Agile Projects
 
Test Automation Techniques for Windows Applications
Test Automation Techniques for Windows ApplicationsTest Automation Techniques for Windows Applications
Test Automation Techniques for Windows Applications
 
Unit testing
Unit testing Unit testing
Unit testing
 

Similaire à Building Maintainable Android Apps (DroidCon NYC 2014)

Automated Testing Of EPiServer CMS Sites
Automated Testing Of EPiServer CMS SitesAutomated Testing Of EPiServer CMS Sites
Automated Testing Of EPiServer CMS Sitesjoelabrahamsson
 
Automated Testing vs Manual Testing
Automated Testing vs Manual TestingAutomated Testing vs Manual Testing
Automated Testing vs Manual TestingDirecti Group
 
Automated+Testing+Vs+Manual+Testing
Automated+Testing+Vs+Manual+TestingAutomated+Testing+Vs+Manual+Testing
Automated+Testing+Vs+Manual+Testinggueste1e4db
 
Creating a successful continuous testing environment by Eran Kinsbruner
Creating a successful continuous testing environment by Eran KinsbrunerCreating a successful continuous testing environment by Eran Kinsbruner
Creating a successful continuous testing environment by Eran KinsbrunerQA or the Highway
 
Automation testing
Automation testingAutomation testing
Automation testingTomy Rhymond
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestSeb Rose
 
Automating The Process For Building Reliable Software
Automating The Process For Building Reliable SoftwareAutomating The Process For Building Reliable Software
Automating The Process For Building Reliable Softwareguest8861ff
 
Stepin evening presented
Stepin evening presentedStepin evening presented
Stepin evening presentedVijayan Reddy
 
Making the Unstable Stable - An Intro To Testing
Making the Unstable Stable - An Intro To TestingMaking the Unstable Stable - An Intro To Testing
Making the Unstable Stable - An Intro To TestingCameron Presley
 
Appium Interview Questions and Answers | Edureka
Appium Interview Questions and Answers | EdurekaAppium Interview Questions and Answers | Edureka
Appium Interview Questions and Answers | EdurekaEdureka!
 
[DevDay 2017] Automation Testing - Speaker: Nghia Khuong - Project Manager at...
[DevDay 2017] Automation Testing - Speaker: Nghia Khuong - Project Manager at...[DevDay 2017] Automation Testing - Speaker: Nghia Khuong - Project Manager at...
[DevDay 2017] Automation Testing - Speaker: Nghia Khuong - Project Manager at...DevDay.org
 
Let's banish "it works on my machine"
Let's banish "it works on my machine"Let's banish "it works on my machine"
Let's banish "it works on my machine"Stephanie Locke
 
Automated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra SolutionsAutomated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra SolutionsQuontra Solutions
 
Performance Testing REST APIs
Performance Testing REST APIsPerformance Testing REST APIs
Performance Testing REST APIsJason Weden
 
Automation Best Practices.pptx
Automation Best Practices.pptxAutomation Best Practices.pptx
Automation Best Practices.pptxpavelpopov43
 
Testing Big in JavaScript
Testing Big in JavaScriptTesting Big in JavaScript
Testing Big in JavaScriptRobert DeLuca
 

Similaire à Building Maintainable Android Apps (DroidCon NYC 2014) (20)

Automated Testing Of EPiServer CMS Sites
Automated Testing Of EPiServer CMS SitesAutomated Testing Of EPiServer CMS Sites
Automated Testing Of EPiServer CMS Sites
 
Automated Testing vs Manual Testing
Automated Testing vs Manual TestingAutomated Testing vs Manual Testing
Automated Testing vs Manual Testing
 
Automated+Testing+Vs+Manual+Testing
Automated+Testing+Vs+Manual+TestingAutomated+Testing+Vs+Manual+Testing
Automated+Testing+Vs+Manual+Testing
 
Design pattern
Design patternDesign pattern
Design pattern
 
Creating a successful continuous testing environment by Eran Kinsbruner
Creating a successful continuous testing environment by Eran KinsbrunerCreating a successful continuous testing environment by Eran Kinsbruner
Creating a successful continuous testing environment by Eran Kinsbruner
 
Automation testing
Automation testingAutomation testing
Automation testing
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
Automating The Process For Building Reliable Software
Automating The Process For Building Reliable SoftwareAutomating The Process For Building Reliable Software
Automating The Process For Building Reliable Software
 
Stepin evening presented
Stepin evening presentedStepin evening presented
Stepin evening presented
 
E2 e test with testcafe
E2 e test with testcafeE2 e test with testcafe
E2 e test with testcafe
 
Making the Unstable Stable - An Intro To Testing
Making the Unstable Stable - An Intro To TestingMaking the Unstable Stable - An Intro To Testing
Making the Unstable Stable - An Intro To Testing
 
Appium Interview Questions and Answers | Edureka
Appium Interview Questions and Answers | EdurekaAppium Interview Questions and Answers | Edureka
Appium Interview Questions and Answers | Edureka
 
[DevDay 2017] Automation Testing - Speaker: Nghia Khuong - Project Manager at...
[DevDay 2017] Automation Testing - Speaker: Nghia Khuong - Project Manager at...[DevDay 2017] Automation Testing - Speaker: Nghia Khuong - Project Manager at...
[DevDay 2017] Automation Testing - Speaker: Nghia Khuong - Project Manager at...
 
Let's banish "it works on my machine"
Let's banish "it works on my machine"Let's banish "it works on my machine"
Let's banish "it works on my machine"
 
Automated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra SolutionsAutomated Software Testing Framework Training by Quontra Solutions
Automated Software Testing Framework Training by Quontra Solutions
 
Future of QA
Future of QAFuture of QA
Future of QA
 
Futureofqa
FutureofqaFutureofqa
Futureofqa
 
Performance Testing REST APIs
Performance Testing REST APIsPerformance Testing REST APIs
Performance Testing REST APIs
 
Automation Best Practices.pptx
Automation Best Practices.pptxAutomation Best Practices.pptx
Automation Best Practices.pptx
 
Testing Big in JavaScript
Testing Big in JavaScriptTesting Big in JavaScript
Testing Big in JavaScript
 

Dernier

Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 

Dernier (20)

Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 

Building Maintainable Android Apps (DroidCon NYC 2014)

  • 1. Building Maintainable Android Applications ! Kevin Schultz (@kevinrschultz) DroidCon NYC 2014 ! kevinrschultz.com github.com/krschultz/AndroidWeatherBuoyDemo
  • 3.
  • 4. Treading Water Time spent on features dwindles Infrequent releases due to high QA costs Heisenbug whack-a-mole Fear of change Infrastructure Bugs Features
  • 5. Drowning Platform Changes Business Pivot Competitors Panic How many regressions will you cause when implementing Material Design?
  • 7. The codebase is a mess!
  • 8. Unlikely to be better next time Clean code is necessary but insufficient for maintainability We are state of the art today, what about next year? Why do Android apps always seem to become unmaintainable?
  • 9. Android was initially for Apps Documentation & samples are small scale Old build system was deficient Testing tools are still sub-par Framework was not designed for testability Performance trumped clean code
  • 10. You must build a system to counter software entropy
  • 11. Software Entropy “As a system is modified, its disorder, or entropy, always increases. This is known as software entropy.” - Ivar Jacobson “Legacy code is code without tests” - Michael Feathers
  • 12. System Espresso Functional Tests UI Tests Build Unit Tests App CI Server
  • 13. System Thinking How will each component be tested over its lifetime? What leads to the minimum cost of development including QA time? If a library makes it easy to add a feature but harder to test, is it worth it? If a tool breaks CI, is it worth it?
  • 14. Testing Strategy Customers in Production Manual QA by Team Unit Tests Integration tests Automated UI Tests
  • 15. Manual Testing Low initial cost Need to acceptance test every feature at least once Never can be completely eliminated Does not scale with complexity Extremely expensive long term
  • 16. QA Options Helps make manual testing cheaper & more effective Network connectivity Environment Mock Data
  • 17. QA Specs Look at Gherkin / Cucumber for examples Helps to make tests more repeatable Can use to outsource testing to other firms Painful & expensive
  • 18. Automated UI Testing Appium / UIAutomator type tests Usually leveraging the accessibility IDs Expensive, flakey Can be layered onto most apps after the fact
  • 19. Functional Testing Most Android ‘unit testing’ examples are functional Robolectric & InstrumentationTests Generally scoped to an Activity / Fragment / Service Time consuming to run and nearly as flakey as UI tests Useful but should be minimized
  • 20. Functional Testing Challenges Generic Problems Asynchronous Network based ! ! Android Specific Lifecycle Context Platform singletons
  • 21. Functional Test in Theory insertMockDataIntoPreferences(conditions) waitForActivityAndFragmentToInitialize() waitForDataToLoad() label = findViewById() assertEquals(conditions, label.getText()); Preconditions Boilerplate Actual Test testWindSpeedLabel_MetricSystem
  • 22. Functional Test in Practice
  • 23. Pitfalls for a Functional Test Is the user logged in? Wait for Activity, Fragment lifecycle to load screen Wait for network call to finish Wait for data to load from DB Find the TextView Finally, check the TextView’s content & color
  • 24. Unit Testing Narrow in scope, each test is 1 case for 1 method Do not test Android platform, therefore run quickly Cheap to write if architecture is designed for testing Flexible for refactoring Should be 80% of your tests
  • 25. Unit Test in Theory testWindSpeedLabel_MetricSystem given(conditions) assertEquals(conditions, label.getText());
  • 26. Unit Tests in Practice
  • 27. So why is this so hard?
  • 28. Activity Fragment Adapter ForecastActivity ForecastFragment ForecastAdapter ForecastModel
  • 29. Keep Android At Arm’s Length
  • 30. Strategies Covered Dealing with K/V Store ViewModels, Presenters, Custom Views Not Covered Testing network calls Testing SQLite / ContentProviders / ORMs
  • 31. Weather Buoy Master list of buoys Detail screen with wind & wave forecast Setting to choose units github.com/krschultz/AndroidWeatherBuoyDemo
  • 32. Tools Examples uses only Android standard JUnit & InstrumentationTests Mockito AssertJ Better tools exist Espresso Robolectric Dagger
  • 34. How do you catch this?
  • 35. How do you catch this?
  • 40. Wrapping Shared Preferences + Only 1 place to test interaction w/ SharedPreferences + Handle versioning + Keys don’t leak out + Can now mock SharedPreferences w/o Context - More code
  • 41. UI Unit Testing Strategies
  • 43. Optional TextView What happens when we refactor the layout? How do we know this feature doesn’t break?
  • 46. Instrument View Label Value & Units
  • 47. Custom View + Clean API + Reusable view logic - Compose-ability issues
  • 49. SharedPreferences ForecastFragment Views WaveForecast Views Views WindForecast Preferences API Client
  • 50. View Models Add presentation logic to underlying models Combine multiple models Do not have a concept of Activity/Fragment lifecycle Do not have a reference to View
  • 51. Using a ViewModel Fragment is responsible for loading models, networking, finding views, threading ViewModel is responsible for business logic Fragment should fail in all cases
  • 52. “Presentation” Logic Colors, visibility Interaction between multiple views Formatting / humanizing properties i18n
  • 53. Combining Models WaveForecast WindForecast Preferences BuoyDetailViewModel
  • 54. SharedPreferences Preferences API Client ForecastFragment WaveForecast Views Views Views WindForecast ViewModel
  • 55. ViewModel Creation No reference to view at all All models can be immutable
  • 56. Using a ViewModel Create view model at the end of network call or DB fetch Pass Views to ViewModel for updating
  • 57. Logic in a ViewModel
  • 58. Pitfalls Creating a ViewModel getter for every view property Keeping references to views in the ViewModel
  • 60. Use Cases Great for screens displaying detail about an object Not ideal for collections of items, but Adapters can be tested similarly Not a great fit for screens with many interactions
  • 62. Presenters Same general idea as ViewModel, but includes reference to View Requires coordinating with Activity/Fragment lifecycle Potential for Context leaks if not handled correctly More full featured, can take ownership of fetching data, threading, network calls, etc
  • 63. Preferences ForecastFragment WaveForecast Views Views Views WindForecast Presenter View Interface
  • 66. Fragment Continued User interactions delegated to presenter Can test using the same methods on the presenter
  • 67. Presenter Continued All business logic belongs in presenter Calls back to view for update, remember the view may be gone
  • 68. Use Cases Can handle state changes caused by user interaction very well Really should use Espresso / InstrumentationTests to ensure that click handlers call appropriate methods in presenter
  • 69. Summary You are building a system, not just an app Cost of testing over long term becomes extremely expensive Find ways to keep the platform at arms length Consider how to test each component from the start
  • 70. Further Reading martinfowler.com/eaaDev/uiArchs.html www.objc.io/issue-13/viper.html
  • 74. Law of Demeter w/ Context
  • 75. Image Attribution ! Tent - House - https://www.flickr.com/photos/18702768@N04/2294709357 Cake - https://www.flickr.com/photos/personalcreations/14888675499
  • 76. Long Term Cost 70 52.5 35 17.5 0 Manual Unit Tests UI Tests Test Fixtures 1 2 3 4 5 6
  • 77. Stage 1 -> No desire for tests Stage 2 -> Desire tests, but can’t build the test suite Stage 3 -> Have a test suite Stage 4 -> Nirvana. Bugs find themselves.
  • 78. But I Don’t Have Business Logic! “It’s just simple data in the UI!” Not for long (PDP examples) Creating a place for the tests to go from the start makes it easy to add them (UUID example) Every single thing is small, but the sum of testing them all is expensive