SlideShare a Scribd company logo
Tips and Tricks for Testing
Lambda Expressions in Android
David Carver
CareWorks Tech
Google Plus: David Carver
Github: kingargyle
Agenda
● Anonymous Classes and Lambdas
○ Definitions
○ Use in Android Applications
■ Lambdas in Android
● Retro Lambda
● Jack and Jill
● The Problems
● Tips and Tricks
Unit Testing vs Integration Testing
Unit Tests try to test the smallest portion of code individually
and independently … for proper operation.
Integration Tests test blocks of code as a group. It occurs after
unit testing and before validation testing.
About Anonymous Classes and Lambdas
Anonymous Classes
As defined by Java In a Nutshell, “an anonymous class is defined and instantiated in a
single succinct expression using the new operator”
Where are Anonymous Classes Commonly Used in
Android?
● Runnables
● View Listeners
○ OnClickListener, OnLongClickListener, OnFocusChangeListener,
OnDragListener, OnTouchListener, etc
● Comparators
● Handler Callbacks
● Loaders
○ OnLoadCanceledListener
○ OnLoadCompleteListener
What Are Lambda Expressions?
Microsoft MSDN, July 20, 2015
A lambda expression is an anonymous function that you can use to create delegates or
expressions….you can write local functions that can be passed as arguments or returned
as the value of the function.
What Are Lambda Expressions?
Another way to pass code blocks around, but in a more compact syntax.
Lambda encourage you to do functional (what you want down, not specifically how it
is done) programming instead of an imperative (procedural, how it should be done).
Lambdas vs Anonymous Classes
Lambdas allow a cleaner syntax for Anonymous Classes that contain a
single method that needs to be implemented .
Lambda onClickListener implementation
Lambda syntax for an onClickListener representation.
Android and Lambdas
● RetroLambda - https://github.com/orfjackal/retrolambda
○ Backports the Java 8 support for Lambdas
○ Allows the use Lambdas all the way back to Java 5.
○ Generates code at compile time
○ Gradle Plugin - https://github.com/evant/gradle-retrolambda
● Jack and Jill - http://tools.android.com/tech-docs/jackandjill
○ Android specific compiler
○ Natively supports Java 8 and Lambdas
○ Only supports back to Java 7
■ No Java 6 support for older devices
○ Will be the standard android compiler going forward.
So What is the Problem?
Lambdas as used in Java currently, are a cleaner syntax for single method anonymous
classes.
● Trying to write tests leads to writing integration tests
● Leads to duplication of Code
● Can lead to hard to maintain code
○ Multiple inline overrides embedded multiple levels deep.
● Testing code that requires a Framework or other layers to work leads to tests that
need more setup.
○ Can lead to longer execution time of your tests
○ More difficult to setup tests
Performance
Lambda Expressions are not as
optimized by the compiler
currently as standard imperative
ways of accomplishing the same
thing.
Imperative is still faster in the
following areas:
● Iterators
● For Each
Benchmarks are tricky and can be
misleading, but be careful going
hog wild with lambdas as they can
introduce slow points in your code.
http://blog.takipi.com/benchmark-how-java-8-lambdas-and-streams-can-make-your-code-5-times-slower/
Anonymous Classes plague Graphical User Interface work.
They are convenient. However, hard to unit test.
Lambdas can be used many places that you would
implement an Anonymous class.
They suffer the same testing problem as Anonymous
Classes.
It leads to integration testing and not unit testing.
HOW DO WE BRING ORDER OUT OF CHAOS?
AVOID USING ANONYMOUS
CLASSES!
AVOID USING LAMBDAS!
DO NOT OVER USE LAMBDAS
BECAUSE THEY ARE CONVENIENT.
DO WHAT IS RIGHT.
NOT WHAT IS EASY.
You are going to use them anyways
right?
Tips and Tricks
Where are Lambdas Commonly Used in Android?
● RXJava and RXJava for Android
○ Anywhere the Action class/interface would normally be implemented.
○ Anywhere where anonymous inline overrides would have been used.
○ If you are doing RX… you are probably using Lambdas otherwise you go insane.
● Implementation of Interfaces
○ Handlers
○ Runnables
○ Listeners
○ Any place you could use an anonymous class with a single method.
All of these places are also where you typically have Unit Testing pain points.
What is RXJava and RX Android?
A library for composing asynchronous and
event-based programs by using observable
sequences.
It is an implementation of ReactiveX (Reactive
Extensions).
https://github.com/ReactiveX/RxJava/wiki
RXJava Syntax for Java 7
RXJava Syntax for Java 8
Implement Concrete Class from Interface
● Simple POJO
● Typically the fastest to execute
● Typically the least complicated to setup
● Can be reused in other places in your application.
Many Android examples use Anonymous Classes.
Stop following these examples.
Implement the Interface on a View/Fragment/Activity
This is fine .... until your class starts becoming a GOD class that
wants to do everything.
Avoid GOD classes… they become a nightmare to test.
Easier View Listener Testing
Robolectric and Butterknife
● Robolectric
○ Unit Test Framework that runs on your computer
■ No Device needed
■ No Simulator
■ Simulates Android
■ Runs on your machine.
● ButterKnife
○ Developed by Jake Wharton
○ Part of the Square Development Stack
○ Generates Code based on Annotations
■ @BindView, @BindInt, @BindBoolean
■ @OnClick, @OnLongClick
ButterKnife onClick Binding Example
ButterKnife onClick Binding Example
ButterKnife Testing Advantages
● No Anonymous classes
● Lambdas are not necessary
● Less Likely to lead to an Integration Test
○ Allows for a pure unit test without executing more code than necessary
● Simpler tests
○ Leading to faster execution of the tests
● Cleaner Code leading to easier maintenance
● Can Bind onClicks to multiple views allowing for easier code re-use.
Testing Lambdas in RXJava
● RXJava allows for easier implementation of Async Tasks
○ File operations
○ Database Acccess
○ Remote Procedure Calls
○ Any type of Background Tasks
○ Can support Event Bus style notifications
● Lambdas can make writing RXJava Observables cleaner
○ No Messy inline override syntax
● However, RXJava leads to more Integration Style Tests
● Tests are harder to setup, and more complicated to verify and isolate.
Common RXJava Test Situations
● Subscribers and Error conditions
● Subjects
● Map Flatteners
● Joins
The simplest way to test these is to extract the functionality to a method, and test the
code that is intended to be executed separately.
Extract to Method
Extract to Method
Extracting this out allows for testing of the expected behavior of this code without
executing the subscribe directly. It also keeps your code potentially cleaner.
RXJava TestSubscriber
● Allows you to execute the subscribe, and error portions of an RXJava Observable.
● Provides the simplest method for executing the least amount of code possible.
● Use in combination with Mockito/EasyMock to provide mocks for the
Observables that are being subscribed too.
● This is still an Integration Test
○ Requires RXJava Framework to execute in order to test the conditions and code in the Lambda
expression.
○ Less Complicated though than trying to Mock Out the RXJava Framework itself.
RXJava Testing Error Conditions
RXJava TestSubscriber - code under test
RXJava TestSubscriber - subscribe
RXJava - Testing Subjects with Schedulers
Summary
● Leverage Lambdas
○ Make sure you are using for the right reasons, not because you can.
○ They can provide cleaner code, but can make it more complicated to test.
● Prefer implementing your Interfaces as re-usable classes
○ Easier to strictly unit test
○ Reduce code duplication
● Leverage Butterknife when possible for binding click events
○ Allows simpler tests
○ Cleaner test setup and execution
● Consider extracting lambdas that contain complicated code to either Classes or
methods.
Resources
● RXJava - https://github.com/ReactiveX/RxJava
● RXJava for Android - https://github.com/ReactiveX/RxAndroid
● RetroLambda - https://github.com/orfjackal/retrolambda
● ButterKnife - http://jakewharton.github.io/butterknife/
● Robolectric - https://github.com/robolectric/robolectric
● Mockito - http://site.mockito.org/
● Testing RX Java Observables -
https://labs.ribot.co.uk/unit-testing-rxjava-6e9540d4a329#.9ydk0xq9b
● Testing Lambda Expressions -
http://radar.oreilly.com/2014/12/unit-testing-java-8-lambda-expressions-and-strea
ms.html
Resources

More Related Content

What's hot

Amazon EventBridge
Amazon EventBridgeAmazon EventBridge
Amazon EventBridge
Dhaval Nagar
 
Deploy Secure Network Architectures for The Connected Enterprise
Deploy Secure Network Architectures for The Connected EnterpriseDeploy Secure Network Architectures for The Connected Enterprise
Deploy Secure Network Architectures for The Connected Enterprise
Rockwell Automation
 
Mulesoft meetup slides mumbai_20113019_exception_handling
Mulesoft meetup slides mumbai_20113019_exception_handlingMulesoft meetup slides mumbai_20113019_exception_handling
Mulesoft meetup slides mumbai_20113019_exception_handling
Manish Kumar Yadav
 
Token Authentication in ASP.NET Core
Token Authentication in ASP.NET CoreToken Authentication in ASP.NET Core
Token Authentication in ASP.NET Core
Stormpath
 
Gateway/APIC security
Gateway/APIC securityGateway/APIC security
Gateway/APIC security
Shiu-Fun Poon
 
Postman. From simple API test to end to end scenario
Postman. From simple API test to end to end scenarioPostman. From simple API test to end to end scenario
Postman. From simple API test to end to end scenario
HYS Enterprise
 
Redis and Ohm
Redis and OhmRedis and Ohm
Redis and Ohm
awksedgreep
 
Amazon QLDB를 통한 원장 기반 운전 면허 검증 서비스 구현 - 윤석찬 :: AWS Unboxing 온라인 세미나
Amazon QLDB를 통한 원장 기반 운전 면허 검증 서비스 구현 - 윤석찬 :: AWS Unboxing 온라인 세미나Amazon QLDB를 통한 원장 기반 운전 면허 검증 서비스 구현 - 윤석찬 :: AWS Unboxing 온라인 세미나
Amazon QLDB를 통한 원장 기반 운전 면허 검증 서비스 구현 - 윤석찬 :: AWS Unboxing 온라인 세미나
Amazon Web Services Korea
 
Scaling Apache Pulsar to 10 PB/day
Scaling Apache Pulsar to 10 PB/dayScaling Apache Pulsar to 10 PB/day
Scaling Apache Pulsar to 10 PB/day
Karthik Ramasamy
 
Log analytics with ELK stack
Log analytics with ELK stackLog analytics with ELK stack
Log analytics with ELK stack
AWS User Group Bengaluru
 
Oracle application testing suite (OATS)
Oracle application testing suite (OATS)Oracle application testing suite (OATS)
Oracle application testing suite (OATS)
Koushik Arvapally
 
Orchestrating Microservices
Orchestrating MicroservicesOrchestrating Microservices
Orchestrating Microservices
Mauricio (Salaboy) Salatino
 
Comenzando con aplicaciones serverless en AWS
Comenzando con aplicaciones serverless en AWSComenzando con aplicaciones serverless en AWS
Comenzando con aplicaciones serverless en AWS
Amazon Web Services LATAM
 
Anypoint Custom Metrics Mastery
Anypoint Custom Metrics MasteryAnypoint Custom Metrics Mastery
Anypoint Custom Metrics Mastery
MuleSoft Meetups
 
Eggplant Digital Automation Intelligence for Epic
Eggplant Digital Automation Intelligence for EpicEggplant Digital Automation Intelligence for Epic
Eggplant Digital Automation Intelligence for Epic
Eggplant
 
Amazon GameLift – 김성수 (AWS 솔루션즈 아키텍트)
Amazon GameLift – 김성수 (AWS 솔루션즈 아키텍트)Amazon GameLift – 김성수 (AWS 솔루션즈 아키텍트)
Amazon GameLift – 김성수 (AWS 솔루션즈 아키텍트)
Amazon Web Services Korea
 
Amazon Virtual Private Cloud (VPC) - Networking Fundamentals and Connectivity...
Amazon Virtual Private Cloud (VPC) - Networking Fundamentals and Connectivity...Amazon Virtual Private Cloud (VPC) - Networking Fundamentals and Connectivity...
Amazon Virtual Private Cloud (VPC) - Networking Fundamentals and Connectivity...
Amazon Web Services
 
AWS VPC & Networking basic concepts
AWS VPC & Networking basic conceptsAWS VPC & Networking basic concepts
AWS VPC & Networking basic concepts
Abhinav Kumar
 
Cloud Computing: Overview and Examples
Cloud Computing: Overview and ExamplesCloud Computing: Overview and Examples
Cloud Computing: Overview and Examples
Eueung Mulyana
 
Scaling to millions of users with Amazon CloudFront - April 2017 AWS Online T...
Scaling to millions of users with Amazon CloudFront - April 2017 AWS Online T...Scaling to millions of users with Amazon CloudFront - April 2017 AWS Online T...
Scaling to millions of users with Amazon CloudFront - April 2017 AWS Online T...
Amazon Web Services
 

What's hot (20)

Amazon EventBridge
Amazon EventBridgeAmazon EventBridge
Amazon EventBridge
 
Deploy Secure Network Architectures for The Connected Enterprise
Deploy Secure Network Architectures for The Connected EnterpriseDeploy Secure Network Architectures for The Connected Enterprise
Deploy Secure Network Architectures for The Connected Enterprise
 
Mulesoft meetup slides mumbai_20113019_exception_handling
Mulesoft meetup slides mumbai_20113019_exception_handlingMulesoft meetup slides mumbai_20113019_exception_handling
Mulesoft meetup slides mumbai_20113019_exception_handling
 
Token Authentication in ASP.NET Core
Token Authentication in ASP.NET CoreToken Authentication in ASP.NET Core
Token Authentication in ASP.NET Core
 
Gateway/APIC security
Gateway/APIC securityGateway/APIC security
Gateway/APIC security
 
Postman. From simple API test to end to end scenario
Postman. From simple API test to end to end scenarioPostman. From simple API test to end to end scenario
Postman. From simple API test to end to end scenario
 
Redis and Ohm
Redis and OhmRedis and Ohm
Redis and Ohm
 
Amazon QLDB를 통한 원장 기반 운전 면허 검증 서비스 구현 - 윤석찬 :: AWS Unboxing 온라인 세미나
Amazon QLDB를 통한 원장 기반 운전 면허 검증 서비스 구현 - 윤석찬 :: AWS Unboxing 온라인 세미나Amazon QLDB를 통한 원장 기반 운전 면허 검증 서비스 구현 - 윤석찬 :: AWS Unboxing 온라인 세미나
Amazon QLDB를 통한 원장 기반 운전 면허 검증 서비스 구현 - 윤석찬 :: AWS Unboxing 온라인 세미나
 
Scaling Apache Pulsar to 10 PB/day
Scaling Apache Pulsar to 10 PB/dayScaling Apache Pulsar to 10 PB/day
Scaling Apache Pulsar to 10 PB/day
 
Log analytics with ELK stack
Log analytics with ELK stackLog analytics with ELK stack
Log analytics with ELK stack
 
Oracle application testing suite (OATS)
Oracle application testing suite (OATS)Oracle application testing suite (OATS)
Oracle application testing suite (OATS)
 
Orchestrating Microservices
Orchestrating MicroservicesOrchestrating Microservices
Orchestrating Microservices
 
Comenzando con aplicaciones serverless en AWS
Comenzando con aplicaciones serverless en AWSComenzando con aplicaciones serverless en AWS
Comenzando con aplicaciones serverless en AWS
 
Anypoint Custom Metrics Mastery
Anypoint Custom Metrics MasteryAnypoint Custom Metrics Mastery
Anypoint Custom Metrics Mastery
 
Eggplant Digital Automation Intelligence for Epic
Eggplant Digital Automation Intelligence for EpicEggplant Digital Automation Intelligence for Epic
Eggplant Digital Automation Intelligence for Epic
 
Amazon GameLift – 김성수 (AWS 솔루션즈 아키텍트)
Amazon GameLift – 김성수 (AWS 솔루션즈 아키텍트)Amazon GameLift – 김성수 (AWS 솔루션즈 아키텍트)
Amazon GameLift – 김성수 (AWS 솔루션즈 아키텍트)
 
Amazon Virtual Private Cloud (VPC) - Networking Fundamentals and Connectivity...
Amazon Virtual Private Cloud (VPC) - Networking Fundamentals and Connectivity...Amazon Virtual Private Cloud (VPC) - Networking Fundamentals and Connectivity...
Amazon Virtual Private Cloud (VPC) - Networking Fundamentals and Connectivity...
 
AWS VPC & Networking basic concepts
AWS VPC & Networking basic conceptsAWS VPC & Networking basic concepts
AWS VPC & Networking basic concepts
 
Cloud Computing: Overview and Examples
Cloud Computing: Overview and ExamplesCloud Computing: Overview and Examples
Cloud Computing: Overview and Examples
 
Scaling to millions of users with Amazon CloudFront - April 2017 AWS Online T...
Scaling to millions of users with Amazon CloudFront - April 2017 AWS Online T...Scaling to millions of users with Amazon CloudFront - April 2017 AWS Online T...
Scaling to millions of users with Amazon CloudFront - April 2017 AWS Online T...
 

Similar to Tips and Tricks for Testing Lambda Expressions in Android

Evolve with laravel
Evolve with laravelEvolve with laravel
Evolve with laravel
Gayan Sanjeewa
 
Unit testing hippo
Unit testing hippoUnit testing hippo
Unit testing hippo
Ebrahim Aharpour
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your code
Pascal Larocque
 
Javascript Unit Testing Tools
Javascript Unit Testing ToolsJavascript Unit Testing Tools
Javascript Unit Testing Tools
PixelCrayons
 
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
DicodingEvent
 
Making Strongly-typed NETCONF Usable
Making Strongly-typed NETCONF UsableMaking Strongly-typed NETCONF Usable
Making Strongly-typed NETCONF Usable
Open Networking Summit
 
Progressive Web App Testing With Cypress.io
Progressive Web App Testing With Cypress.ioProgressive Web App Testing With Cypress.io
Progressive Web App Testing With Cypress.io
Knoldus Inc.
 
Angular Unit testing.pptx
Angular Unit testing.pptxAngular Unit testing.pptx
Angular Unit testing.pptx
RiyaBangera
 
Java introduction
Java introductionJava introduction
Java introduction
logeswarisaravanan
 
Efficient mobile automation
Efficient mobile automationEfficient mobile automation
Efficient mobile automation
Vitaly Tatarinov
 
Cypress for Testing
Cypress for TestingCypress for Testing
Cypress for Testing
PoojaSingh1123
 
Best practices for JavaScript RIAs
Best practices for JavaScript RIAsBest practices for JavaScript RIAs
Best practices for JavaScript RIAsCarlos Ble
 
Front-end Testing (manual, automated, you name it) - Erich Jagomägis - Develo...
Front-end Testing (manual, automated, you name it) - Erich Jagomägis - Develo...Front-end Testing (manual, automated, you name it) - Erich Jagomägis - Develo...
Front-end Testing (manual, automated, you name it) - Erich Jagomägis - Develo...
MobileMonday Estonia
 
Tdd - introduction
Tdd - introductionTdd - introduction
Tdd - introduction
Samad Koushan
 
OWF12/PAUG Conf Days Dart a new html5 technology, nicolas geoffray, softwar...
OWF12/PAUG Conf Days Dart   a new html5 technology, nicolas geoffray, softwar...OWF12/PAUG Conf Days Dart   a new html5 technology, nicolas geoffray, softwar...
OWF12/PAUG Conf Days Dart a new html5 technology, nicolas geoffray, softwar...Paris Open Source Summit
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
eMexo Technologies
 
1.Intro--Why Java.pptx
1.Intro--Why Java.pptx1.Intro--Why Java.pptx
1.Intro--Why Java.pptx
YounasKhan542109
 
Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer tool
Gabor Paller
 
Lamba scaffold webinar
Lamba scaffold webinarLamba scaffold webinar
Lamba scaffold webinar
Matt Billock
 
Java
JavaJava

Similar to Tips and Tricks for Testing Lambda Expressions in Android (20)

Evolve with laravel
Evolve with laravelEvolve with laravel
Evolve with laravel
 
Unit testing hippo
Unit testing hippoUnit testing hippo
Unit testing hippo
 
Test driven development - Zombie proof your code
Test driven development - Zombie proof your codeTest driven development - Zombie proof your code
Test driven development - Zombie proof your code
 
Javascript Unit Testing Tools
Javascript Unit Testing ToolsJavascript Unit Testing Tools
Javascript Unit Testing Tools
 
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
Play with Testing on Android - Gilang Ramadhan (Academy Content Writer at Dic...
 
Making Strongly-typed NETCONF Usable
Making Strongly-typed NETCONF UsableMaking Strongly-typed NETCONF Usable
Making Strongly-typed NETCONF Usable
 
Progressive Web App Testing With Cypress.io
Progressive Web App Testing With Cypress.ioProgressive Web App Testing With Cypress.io
Progressive Web App Testing With Cypress.io
 
Angular Unit testing.pptx
Angular Unit testing.pptxAngular Unit testing.pptx
Angular Unit testing.pptx
 
Java introduction
Java introductionJava introduction
Java introduction
 
Efficient mobile automation
Efficient mobile automationEfficient mobile automation
Efficient mobile automation
 
Cypress for Testing
Cypress for TestingCypress for Testing
Cypress for Testing
 
Best practices for JavaScript RIAs
Best practices for JavaScript RIAsBest practices for JavaScript RIAs
Best practices for JavaScript RIAs
 
Front-end Testing (manual, automated, you name it) - Erich Jagomägis - Develo...
Front-end Testing (manual, automated, you name it) - Erich Jagomägis - Develo...Front-end Testing (manual, automated, you name it) - Erich Jagomägis - Develo...
Front-end Testing (manual, automated, you name it) - Erich Jagomägis - Develo...
 
Tdd - introduction
Tdd - introductionTdd - introduction
Tdd - introduction
 
OWF12/PAUG Conf Days Dart a new html5 technology, nicolas geoffray, softwar...
OWF12/PAUG Conf Days Dart   a new html5 technology, nicolas geoffray, softwar...OWF12/PAUG Conf Days Dart   a new html5 technology, nicolas geoffray, softwar...
OWF12/PAUG Conf Days Dart a new html5 technology, nicolas geoffray, softwar...
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
1.Intro--Why Java.pptx
1.Intro--Why Java.pptx1.Intro--Why Java.pptx
1.Intro--Why Java.pptx
 
Understanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer toolUnderstanding the Dalvik bytecode with the Dedexer tool
Understanding the Dalvik bytecode with the Dedexer tool
 
Lamba scaffold webinar
Lamba scaffold webinarLamba scaffold webinar
Lamba scaffold webinar
 
Java
JavaJava
Java
 

Tips and Tricks for Testing Lambda Expressions in Android

  • 1. Tips and Tricks for Testing Lambda Expressions in Android David Carver CareWorks Tech Google Plus: David Carver Github: kingargyle
  • 2. Agenda ● Anonymous Classes and Lambdas ○ Definitions ○ Use in Android Applications ■ Lambdas in Android ● Retro Lambda ● Jack and Jill ● The Problems ● Tips and Tricks
  • 3.
  • 4. Unit Testing vs Integration Testing Unit Tests try to test the smallest portion of code individually and independently … for proper operation. Integration Tests test blocks of code as a group. It occurs after unit testing and before validation testing.
  • 6. Anonymous Classes As defined by Java In a Nutshell, “an anonymous class is defined and instantiated in a single succinct expression using the new operator”
  • 7. Where are Anonymous Classes Commonly Used in Android? ● Runnables ● View Listeners ○ OnClickListener, OnLongClickListener, OnFocusChangeListener, OnDragListener, OnTouchListener, etc ● Comparators ● Handler Callbacks ● Loaders ○ OnLoadCanceledListener ○ OnLoadCompleteListener
  • 8. What Are Lambda Expressions? Microsoft MSDN, July 20, 2015 A lambda expression is an anonymous function that you can use to create delegates or expressions….you can write local functions that can be passed as arguments or returned as the value of the function.
  • 9. What Are Lambda Expressions? Another way to pass code blocks around, but in a more compact syntax. Lambda encourage you to do functional (what you want down, not specifically how it is done) programming instead of an imperative (procedural, how it should be done).
  • 10. Lambdas vs Anonymous Classes Lambdas allow a cleaner syntax for Anonymous Classes that contain a single method that needs to be implemented .
  • 11. Lambda onClickListener implementation Lambda syntax for an onClickListener representation.
  • 12. Android and Lambdas ● RetroLambda - https://github.com/orfjackal/retrolambda ○ Backports the Java 8 support for Lambdas ○ Allows the use Lambdas all the way back to Java 5. ○ Generates code at compile time ○ Gradle Plugin - https://github.com/evant/gradle-retrolambda ● Jack and Jill - http://tools.android.com/tech-docs/jackandjill ○ Android specific compiler ○ Natively supports Java 8 and Lambdas ○ Only supports back to Java 7 ■ No Java 6 support for older devices ○ Will be the standard android compiler going forward.
  • 13. So What is the Problem? Lambdas as used in Java currently, are a cleaner syntax for single method anonymous classes. ● Trying to write tests leads to writing integration tests ● Leads to duplication of Code ● Can lead to hard to maintain code ○ Multiple inline overrides embedded multiple levels deep. ● Testing code that requires a Framework or other layers to work leads to tests that need more setup. ○ Can lead to longer execution time of your tests ○ More difficult to setup tests
  • 14. Performance Lambda Expressions are not as optimized by the compiler currently as standard imperative ways of accomplishing the same thing. Imperative is still faster in the following areas: ● Iterators ● For Each Benchmarks are tricky and can be misleading, but be careful going hog wild with lambdas as they can introduce slow points in your code. http://blog.takipi.com/benchmark-how-java-8-lambdas-and-streams-can-make-your-code-5-times-slower/
  • 15. Anonymous Classes plague Graphical User Interface work. They are convenient. However, hard to unit test. Lambdas can be used many places that you would implement an Anonymous class. They suffer the same testing problem as Anonymous Classes. It leads to integration testing and not unit testing.
  • 16. HOW DO WE BRING ORDER OUT OF CHAOS?
  • 19. DO NOT OVER USE LAMBDAS BECAUSE THEY ARE CONVENIENT.
  • 20. DO WHAT IS RIGHT. NOT WHAT IS EASY.
  • 21. You are going to use them anyways right?
  • 23. Where are Lambdas Commonly Used in Android? ● RXJava and RXJava for Android ○ Anywhere the Action class/interface would normally be implemented. ○ Anywhere where anonymous inline overrides would have been used. ○ If you are doing RX… you are probably using Lambdas otherwise you go insane. ● Implementation of Interfaces ○ Handlers ○ Runnables ○ Listeners ○ Any place you could use an anonymous class with a single method. All of these places are also where you typically have Unit Testing pain points.
  • 24. What is RXJava and RX Android? A library for composing asynchronous and event-based programs by using observable sequences. It is an implementation of ReactiveX (Reactive Extensions). https://github.com/ReactiveX/RxJava/wiki
  • 27. Implement Concrete Class from Interface ● Simple POJO ● Typically the fastest to execute ● Typically the least complicated to setup ● Can be reused in other places in your application. Many Android examples use Anonymous Classes. Stop following these examples.
  • 28. Implement the Interface on a View/Fragment/Activity This is fine .... until your class starts becoming a GOD class that wants to do everything. Avoid GOD classes… they become a nightmare to test.
  • 30. Robolectric and Butterknife ● Robolectric ○ Unit Test Framework that runs on your computer ■ No Device needed ■ No Simulator ■ Simulates Android ■ Runs on your machine. ● ButterKnife ○ Developed by Jake Wharton ○ Part of the Square Development Stack ○ Generates Code based on Annotations ■ @BindView, @BindInt, @BindBoolean ■ @OnClick, @OnLongClick
  • 33. ButterKnife Testing Advantages ● No Anonymous classes ● Lambdas are not necessary ● Less Likely to lead to an Integration Test ○ Allows for a pure unit test without executing more code than necessary ● Simpler tests ○ Leading to faster execution of the tests ● Cleaner Code leading to easier maintenance ● Can Bind onClicks to multiple views allowing for easier code re-use.
  • 34. Testing Lambdas in RXJava ● RXJava allows for easier implementation of Async Tasks ○ File operations ○ Database Acccess ○ Remote Procedure Calls ○ Any type of Background Tasks ○ Can support Event Bus style notifications ● Lambdas can make writing RXJava Observables cleaner ○ No Messy inline override syntax ● However, RXJava leads to more Integration Style Tests ● Tests are harder to setup, and more complicated to verify and isolate.
  • 35. Common RXJava Test Situations ● Subscribers and Error conditions ● Subjects ● Map Flatteners ● Joins The simplest way to test these is to extract the functionality to a method, and test the code that is intended to be executed separately.
  • 37. Extract to Method Extracting this out allows for testing of the expected behavior of this code without executing the subscribe directly. It also keeps your code potentially cleaner.
  • 38. RXJava TestSubscriber ● Allows you to execute the subscribe, and error portions of an RXJava Observable. ● Provides the simplest method for executing the least amount of code possible. ● Use in combination with Mockito/EasyMock to provide mocks for the Observables that are being subscribed too. ● This is still an Integration Test ○ Requires RXJava Framework to execute in order to test the conditions and code in the Lambda expression. ○ Less Complicated though than trying to Mock Out the RXJava Framework itself.
  • 39. RXJava Testing Error Conditions
  • 40. RXJava TestSubscriber - code under test
  • 42. RXJava - Testing Subjects with Schedulers
  • 43. Summary ● Leverage Lambdas ○ Make sure you are using for the right reasons, not because you can. ○ They can provide cleaner code, but can make it more complicated to test. ● Prefer implementing your Interfaces as re-usable classes ○ Easier to strictly unit test ○ Reduce code duplication ● Leverage Butterknife when possible for binding click events ○ Allows simpler tests ○ Cleaner test setup and execution ● Consider extracting lambdas that contain complicated code to either Classes or methods.
  • 44. Resources ● RXJava - https://github.com/ReactiveX/RxJava ● RXJava for Android - https://github.com/ReactiveX/RxAndroid ● RetroLambda - https://github.com/orfjackal/retrolambda ● ButterKnife - http://jakewharton.github.io/butterknife/ ● Robolectric - https://github.com/robolectric/robolectric ● Mockito - http://site.mockito.org/ ● Testing RX Java Observables - https://labs.ribot.co.uk/unit-testing-rxjava-6e9540d4a329#.9ydk0xq9b ● Testing Lambda Expressions - http://radar.oreilly.com/2014/12/unit-testing-java-8-lambda-expressions-and-strea ms.html