SlideShare uma empresa Scribd logo
1 de 65
Synthesizing API Usage Examples




Ray Buse   Wes Weimer               ICSE 2012
                           Zurich, Switzerland

                                                 2
Java
Simple Bank Withdraw Function
void withdraw( double amount )
{
   double currentBal = getBalance();
   double newBal = currentBal - amount;

    if( newBal < 0 )
      throw new OverDraftException();

    account.setBalance(newBal);
}




                                          4
Simple Bank Withdraw Function
void withdraw( double amount )
{
   double currentBal = getBalance();
   double newBal = currentBal - amount;

    if( newBal < 0 )
      throw new OverDraftException();

                          Initial
    account.setBalance(newBal); Balance = 2
}
                        withdraw(1.10);
                          Final Balance = ?

                                              5
Simple Bank Withdraw Function
void withdraw( double amount )
{
   double currentBal = getBalance();
   double newBal = currentBal - amount;

    if( newBal < 0 )
      throw new OverDraftException();

                          Initial
    account.setBalance(newBal);Balance = 2
}
                      withdraw(1.10);
                         Final Balance = ?
           Final Balance = 0.8999999999999999

                                                6
7
8
“Improved” Withdraw Function
void withdraw( double amount )
{
   BigDecimal currentBal = getBalance();
   BigDecimal newBal
       = currentBal.subtract(new BigDecimal(amount));

    if( newBal.compareTo(BigDecimal.ZERO) < 0 )
      throw new OverDraftException();

    account.setBalance(newBal);
}




                                                        9
“Improved” Withdraw Function
 void withdraw( double amount )
 {
    BigDecimal currentBal = getBalance();
    BigDecimal newBal
        = currentBal.subtract(new BigDecimal(amount));

    if( newBal.compareTo(BigDecimal.ZERO) < 0 )
      throw new OverDraftException();

                          Initial
                              Balance = 2
    account.setBalance(newBal);
 }
                      withdraw(1.10);
                        Final Balance = ?
Final Balance = 0.899999999999999911182158029987
                                                     10
BigDecimal
public BigDecimal(double val)

Translates a double into a BigDecimal which is the exact
decimal representation of the double's binary floating-
point value. The scale of the returned BigDecimal is the
smallest value such that (10scale × val) is an integer.




 http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html


                                                                      11
“Improved” Withdraw Function
void withdraw( double amount )
{
   BigDecimal currentBal = getBalance();
   BigDecimal newBal
       = currentBal.subtract(new BigDecimal(amount));

    if( newBal.compareTo(BigDecimal.ZERO) < 0 )
      throw new OverDraftException();

                        Initial Balance
    account.setBalance(newBal);      = 1.10
}
                      withdraw(1.10);
                        Final Balance = ?
                     OverDraftException
                                                    12
One Solution: String Constructor
void withdraw( String amount )
{
   BigDecimal currentBal = getBalance();
   BigDecimal newBal
       = currentBal.subtract(new BigDecimal(amount));

    if( newBal.compareTo(BigDecimal.ZERO) < 0 )
      throw new OverDraftException();

    account.setBalance(newBal);
                          Initial
                                Balance = 2
}
                      withdraw(“1.10”);
                        Final Balance = 0.90
                                                    13
“The greatest obstacle to learning an
 API … is insufficient or inadequate
              examples”

   Martin Robillard. What Makes APIs Hard to Learn? Answers
   from Developers. IEEE Software, 26(6):27-34, 2009.
The Rest of this Talk


                              What makes a
                              good example?
        Motivation




Approach: Example Synthesis    Evaluation

                                              15
The Rest of this Talk


                              What makes a
                              good example?




Approach: Example Synthesis    Evaluation

                                              16
What makes a good example?
Some Common Sources of Examples




                                  18
Research Tools
• MAPO
  – H. Zhong, T. Xie, L. Zhang, J. Pei, and H. Mei,
    “MAPO: Mining and recommending API usage
    patterns,” in European Conference on Object-
    Oriented Programming, 2009.
• eXoaDocs
  – J. Kim, S. Lee, S. Hwang, and S. Kim, “Towards an
    intelligent code search engine,” in AAAI
    Conference on Artificial Intelligence, 2010.

                                                        19
Research Tools
• MAPO
  – H. Zhong, T. Xie, L. Zhang, J. Pei, and H. Mei,
    “MAPO: Mining and recommending API usage
    patterns,” in European Conference on Object-
    Oriented Programming, 2009.
• eXoaDocs
  – J. Kim, S. Lee, S. Hwang, and S. Kim, “Towards an
    intelligent code search engine,” in AAAI
    Conference on Artificial Intelligence, 2010.

                                                        20
Gold-Standard Human-Written Examples

      Tutorials          JavaDocs




                                    21
Search-based examples

BufferedReader reader = new BufferedReader(new
                                      InputStreamReader(page));
try {String line = reader.readLine();
while (line != null) {
if (line.matches(substituteWikiWord(wikiWord,newTopicPattern)))
{

JExamples: BufferedReader




                                                            22
Hand-Crafted Examples
                                              Example Data

FileOutputStream fos = new FileOutputStream("t.tmp");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeInt(12345);
oos.writeObject("Today");
oos.writeObject(new Date());
oos.close();
                              JavaDoc: java.util.ObjectOutputStream

Complete


                                                                23
Hand-Crafted Examples
                                        Abstract
                                      Initialization

int glyphIndex = ...;
GlyphMetrics metrics =
   GlyphVector.getGlyphMetrics(glyphIndex);
int isStandard = metrics.isStandard();
float glyphAdvance = metrics.getAdvance();
JavaDoc: java.awt.font.GlyphMetrics




                                                       24
Hand-Crafted Examples
for(char c = iter.first();
     c != CharacterIterator.DONE;
     c = iter.next()) {
   processChar(c);
}                         Hole
JavaDoc: java.text.CharacterIterator

try {
file.delete();                                  Hole
} catch (IOException exc) {
  // failed to delete, do error handling here
}
return FileVisitResult.CONTINUE;
JavaDoc: java.nio.FileVisitor

                                                   25
Our API Examples


FileReader fReader; //initialized previously
BufferedReader br = new BufferedReader(fReader);
while(br.ready()) {
    String line = br.readLine();
    //do something with line
}
br.close();

Query: java.util.BufferedReader



                                                   26
Our API Examples
                               Common          Abstract
                            variable names   Initialization

FileReader fReader; //initialized previously
BufferedReader br = new BufferedReader(fReader);
while(br.ready()) {
    String line = br.readLine();
    //do something with line
}
br.close();                       “Holes”
Query: java.util.BufferedReader
                       Complete

                                                              27
Automatic Documentation
•   Cheap
•   Always up-to-date
•   Complete
•   Well-defined trust properties
•   Structured (searchable)



                                    28
Our Approach
Specification Mining
• ``Common behavior is correct behavior.''

 Software
  Corpus




     Miner


                  Common Patterns


                                             30
Specification Mining
• ``Common behavior is correct behavior.''

 Software
  Corpus




                                       Bug Finder
     Miner


                  Common Patterns


                                                    31
API Example Synthesis
• ``Common behavior makes the best examples.''

 Software
  Corpus




     Miner                           Code Gen



                   Common Patterns


                                                32
Two Key Insights




Dataflow Analysis        Abstraction
Two Key Insights


                          Abstraction
                           Operator




Dataflow Analysis        Abstraction
Search Term
Software      “BufferedReader”
 Corpus                                      Control Flow
                                 <init>         Graph
                                            Representation
                                  ready
           Miner


                                 readLine



                                  print



                                  close


                                                             35
argument
                   Search Term              argument
                                                                  “foo.txt”
Software                                    FileReader
              “BufferedReader”
 Corpus
                                 <init>                identifier
                                                          br

                                  ready
           Miner                                   predicate
                                                       ready()

                                 readLine
                                                        returns
                                                       String:
                                                         line
                                  print
       With Dataflow                               argument
    Annotations Relevant                                 line
     to Documentation             close


                                                                         36
Search Term
Software       “BufferedReader”
 Corpus




           Miner

                                  ...



     Many
  Concrete Uses

                                        37
Multiple Common Patterns
BufferedReader br = new BufferedReader(new FileReader("foo.in"));
while( br.ready() )
{
  String s = br.readLine();
  //Do something with s
}

BufferedReader br = new BufferedReader(new FileReader("foo.in"));
String s;
while( ( s = br.readLine() ) != null )
{
   //Do something with s
}


                                                                    38
Clustering: Group Similar Patterns

Many Concrete
    Uses
                              … Grouped Into
                 Clustering
                              A Few Different
                 Operator        Patterns




                                          39
Clustering
• k-medoids
• Distance metric captures
  difference in order of
  statements and types of
  objects




                             40
Abstraction

  Many
Concrete
Examples
              Abstraction
               Operator
                               … Into One
                            Abstract Example




                                         41
Concrete                        Concrete
if(iter.hasNext()) {             if(iter.hasNext()) {
  set.add( iter.next() );          print( iter.next() );
}                                }




                         Abstraction
 Least-upper-             Operator
 bound types

                if(iter.hasNext()) {
                  Object o = iter.next();       Insert Hole
                  //Do something with o
                }

                                                              42
Concrete
Iterator iter = set.iterator();
...
                                      Concrete
                        Iterator iter = list.iterator();
                        ...



                        Abstraction
                         Operator           Abstract
                                          Initialization

       Iterator iter = SOMETHING.iterator();
       ...


                                                           43
Recap
 Software
  Corpus
              Mine      Cluster   Abstract

Search Term




                                             44
Recap
 Software
  Corpus
              Mine            Cluster    Abstract

Search Term


                     Yield Well-Formed   Code Gen
                        Source Code




                                                    45
Recap
 Software
  Corpus
              Mine            Cluster    Abstract

Search Term


                     Yield Well-Formed   Code Gen
                        Source Code




                                                    46
47
Examples


Calendar calendar = Calendar.getInstance();
Date d = calendar.getTime();
//Do something with d
                              Query: java.util.Calendar




                                                          48
Examples

String regex; //initialized previously
String input; //initialized previously
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(input);
//Do something with m
                          Query: java.util.regex.Pattern




                                                           49
Limitations
• Can’t always be perfectly precise
   – E.g., Aliasing, Types
   – Conservative analysis preserves correctness
• Common usage is not always best
   – E.g., poor exception handling
   – Guarantee representative examples
• Not all APIs have indicative patterns
• Some patterns are difficult to find
   – Message passing over network etc.

                                                   50
Evaluation
Name of Class
                            Two examples
                        randomly drawn from
                          {Our Tool, Human-
                          Written, eXoaDoc}




Participant specifies
     preference                         52
Comparison to Code Search




                            53
Comparison to Human-Written




                              54
Potential Use Cases
Warnings for Likely Mistakes




                               56
Auto Completion




                  57
Conclusion
Future Work
• More Complex Queries
  – How do I use X with Y ?
  – Kuat Yessenov, Zhilei Xu, and Armando Solar-
    Lezama, Data-driven synthesis for object-oriented
    frameworks, OOPSLA, 2011.
• What does this example do?
  – Symbolic execution of the example itself
• Additional Guarantees
  – Proof Carrying Examples

                                                        59
Our Implementation




                     60
Documents how a source code change affects
program behavior.

arrestedcomputing.com/deltadoc


                                             61
62
63
64
Thank You!
Questions?




             66

Mais conteúdo relacionado

Mais procurados

RxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниRxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниStfalcon Meetups
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesDragos Ionita
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架jeffz
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJSKyung Yeol Kim
 
Doc Parsers Api Cheatsheet 1 0
Doc Parsers Api Cheatsheet 1 0Doc Parsers Api Cheatsheet 1 0
Doc Parsers Api Cheatsheet 1 0Oleh Burkhay
 
Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113SOAT
 
Drools Expert and Fusion Intro : London 2012
Drools Expert and Fusion Intro  : London 2012Drools Expert and Fusion Intro  : London 2012
Drools Expert and Fusion Intro : London 2012Mark Proctor
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Ramamohan Chokkam
 
Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Juriy Zaytsev
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java DevelopersChristoph Pickl
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantesmikaelbarbero
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkitwlscaudill
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.JustSystems Corporation
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기Wanbok Choi
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - PraticalsFahad Shaikh
 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to missAndres Almiray
 

Mais procurados (20)

RxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниRxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камни
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
Java 7 & 8 New Features
Java 7 & 8 New FeaturesJava 7 & 8 New Features
Java 7 & 8 New Features
 
Doc Parsers Api Cheatsheet 1 0
Doc Parsers Api Cheatsheet 1 0Doc Parsers Api Cheatsheet 1 0
Doc Parsers Api Cheatsheet 1 0
 
Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113Conf soat tests_unitaires_Mockito_jUnit_170113
Conf soat tests_unitaires_Mockito_jUnit_170113
 
Drools Expert and Fusion Intro : London 2012
Drools Expert and Fusion Intro  : London 2012Drools Expert and Fusion Intro  : London 2012
Drools Expert and Fusion Intro : London 2012
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
 
Say Hello To Ecmascript 5
Say Hello To Ecmascript 5Say Hello To Ecmascript 5
Say Hello To Ecmascript 5
 
Kotlin 101 for Java Developers
Kotlin 101 for Java DevelopersKotlin 101 for Java Developers
Kotlin 101 for Java Developers
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
 
Kotlin meets Gadsu
Kotlin meets GadsuKotlin meets Gadsu
Kotlin meets Gadsu
 
.NET Database Toolkit
.NET Database Toolkit.NET Database Toolkit
.NET Database Toolkit
 
Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.Kotlin is charming; The reasons Java engineers should start Kotlin.
Kotlin is charming; The reasons Java engineers should start Kotlin.
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기
 
JVM Mechanics
JVM MechanicsJVM Mechanics
JVM Mechanics
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to miss
 

Destaque

PhD Proposal talk
PhD Proposal talkPhD Proposal talk
PhD Proposal talkRay Buse
 
Documentation Inference for Exceptions
Documentation Inference for ExceptionsDocumentation Inference for Exceptions
Documentation Inference for ExceptionsRay Buse
 
A Metric for Code Readability
A Metric for Code ReadabilityA Metric for Code Readability
A Metric for Code ReadabilityRay Buse
 
Automatically Documenting Program Changes
Automatically Documenting Program ChangesAutomatically Documenting Program Changes
Automatically Documenting Program ChangesRay Buse
 
The Road Not Taken: Estimating Path Execution Frequency Statically
The Road Not Taken: Estimating Path Execution Frequency StaticallyThe Road Not Taken: Estimating Path Execution Frequency Statically
The Road Not Taken: Estimating Path Execution Frequency StaticallyRay Buse
 
MSR End of Internship Talk
MSR End of Internship TalkMSR End of Internship Talk
MSR End of Internship TalkRay Buse
 
Information Needs for Software Development Analytics
Information Needs for Software Development AnalyticsInformation Needs for Software Development Analytics
Information Needs for Software Development AnalyticsRay Buse
 
Automatically Describing Program Structure and Behavior (PhD Defense)
Automatically Describing Program Structure and Behavior (PhD Defense)Automatically Describing Program Structure and Behavior (PhD Defense)
Automatically Describing Program Structure and Behavior (PhD Defense)Ray Buse
 
Analytics for Software Development
Analytics for Software DevelopmentAnalytics for Software Development
Analytics for Software DevelopmentRay Buse
 
Are APIs and SOA Converging
Are APIs and SOA ConvergingAre APIs and SOA Converging
Are APIs and SOA ConvergingSachin Agarwal
 
Are APIs and SOA Converging?
Are APIs and SOA Converging?Are APIs and SOA Converging?
Are APIs and SOA Converging?Akana
 

Destaque (11)

PhD Proposal talk
PhD Proposal talkPhD Proposal talk
PhD Proposal talk
 
Documentation Inference for Exceptions
Documentation Inference for ExceptionsDocumentation Inference for Exceptions
Documentation Inference for Exceptions
 
A Metric for Code Readability
A Metric for Code ReadabilityA Metric for Code Readability
A Metric for Code Readability
 
Automatically Documenting Program Changes
Automatically Documenting Program ChangesAutomatically Documenting Program Changes
Automatically Documenting Program Changes
 
The Road Not Taken: Estimating Path Execution Frequency Statically
The Road Not Taken: Estimating Path Execution Frequency StaticallyThe Road Not Taken: Estimating Path Execution Frequency Statically
The Road Not Taken: Estimating Path Execution Frequency Statically
 
MSR End of Internship Talk
MSR End of Internship TalkMSR End of Internship Talk
MSR End of Internship Talk
 
Information Needs for Software Development Analytics
Information Needs for Software Development AnalyticsInformation Needs for Software Development Analytics
Information Needs for Software Development Analytics
 
Automatically Describing Program Structure and Behavior (PhD Defense)
Automatically Describing Program Structure and Behavior (PhD Defense)Automatically Describing Program Structure and Behavior (PhD Defense)
Automatically Describing Program Structure and Behavior (PhD Defense)
 
Analytics for Software Development
Analytics for Software DevelopmentAnalytics for Software Development
Analytics for Software Development
 
Are APIs and SOA Converging
Are APIs and SOA ConvergingAre APIs and SOA Converging
Are APIs and SOA Converging
 
Are APIs and SOA Converging?
Are APIs and SOA Converging?Are APIs and SOA Converging?
Are APIs and SOA Converging?
 

Semelhante a Synthesizing API Usage Examples

Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?PVS-Studio
 
Class 26: Objectifying Objects
Class 26: Objectifying ObjectsClass 26: Objectifying Objects
Class 26: Objectifying ObjectsDavid Evans
 
Android UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and TechniquesAndroid UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and TechniquesEdgar Gonzalez
 
Android UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesAndroid UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesMarakana Inc.
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Agora Group
 
Beyond Map/Reduce: Getting Creative With Parallel Processing
Beyond Map/Reduce: Getting Creative With Parallel ProcessingBeyond Map/Reduce: Getting Creative With Parallel Processing
Beyond Map/Reduce: Getting Creative With Parallel ProcessingEd Kohlwey
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?Andrey Karpov
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedInScalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedInVitaly Gordon
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India
 
The Possibilities and Pitfalls of Writing Your Own State Stores with Daan Gertis
The Possibilities and Pitfalls of Writing Your Own State Stores with Daan GertisThe Possibilities and Pitfalls of Writing Your Own State Stores with Daan Gertis
The Possibilities and Pitfalls of Writing Your Own State Stores with Daan GertisHostedbyConfluent
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aopDror Helper
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Jacob Kaplan-Moss
 
Gae icc fall2011
Gae icc fall2011Gae icc fall2011
Gae icc fall2011Juan Gomez
 
FrOScamp Zurich: Introducing JCR - 2010
FrOScamp Zurich: Introducing JCR - 2010FrOScamp Zurich: Introducing JCR - 2010
FrOScamp Zurich: Introducing JCR - 2010David Nuescheler
 
From Java to Kotlin - The first month in practice v2
From Java to Kotlin - The first month in practice v2From Java to Kotlin - The first month in practice v2
From Java to Kotlin - The first month in practice v2StefanTomm
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
 

Semelhante a Synthesizing API Usage Examples (20)

Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?Of complicacy of programming, or won't C# save us?
Of complicacy of programming, or won't C# save us?
 
Class 26: Objectifying Objects
Class 26: Objectifying ObjectsClass 26: Objectifying Objects
Class 26: Objectifying Objects
 
Android UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and TechniquesAndroid UI Development: Tips, Tricks, and Techniques
Android UI Development: Tips, Tricks, and Techniques
 
Android UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesAndroid UI Tips, Tricks and Techniques
Android UI Tips, Tricks and Techniques
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
 
Beyond Map/Reduce: Getting Creative With Parallel Processing
Beyond Map/Reduce: Getting Creative With Parallel ProcessingBeyond Map/Reduce: Getting Creative With Parallel Processing
Beyond Map/Reduce: Getting Creative With Parallel Processing
 
Static code analysis: what? how? why?
Static code analysis: what? how? why?Static code analysis: what? how? why?
Static code analysis: what? how? why?
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedInScalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedIn
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Eclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 OverviewEclipse Day India 2015 - Java 8 Overview
Eclipse Day India 2015 - Java 8 Overview
 
The Possibilities and Pitfalls of Writing Your Own State Stores with Daan Gertis
The Possibilities and Pitfalls of Writing Your Own State Stores with Daan GertisThe Possibilities and Pitfalls of Writing Your Own State Stores with Daan Gertis
The Possibilities and Pitfalls of Writing Your Own State Stores with Daan Gertis
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Js tacktalk team dev js testing performance
Js tacktalk team dev js testing performanceJs tacktalk team dev js testing performance
Js tacktalk team dev js testing performance
 
Introduction to aop
Introduction to aopIntroduction to aop
Introduction to aop
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
 
Gae icc fall2011
Gae icc fall2011Gae icc fall2011
Gae icc fall2011
 
FrOScamp Zurich: Introducing JCR - 2010
FrOScamp Zurich: Introducing JCR - 2010FrOScamp Zurich: Introducing JCR - 2010
FrOScamp Zurich: Introducing JCR - 2010
 
From Java to Kotlin - The first month in practice v2
From Java to Kotlin - The first month in practice v2From Java to Kotlin - The first month in practice v2
From Java to Kotlin - The first month in practice v2
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 

Último

Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Último (20)

Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

Synthesizing API Usage Examples

  • 1. Synthesizing API Usage Examples Ray Buse Wes Weimer ICSE 2012 Zurich, Switzerland 2
  • 3. Simple Bank Withdraw Function void withdraw( double amount ) { double currentBal = getBalance(); double newBal = currentBal - amount; if( newBal < 0 ) throw new OverDraftException(); account.setBalance(newBal); } 4
  • 4. Simple Bank Withdraw Function void withdraw( double amount ) { double currentBal = getBalance(); double newBal = currentBal - amount; if( newBal < 0 ) throw new OverDraftException(); Initial account.setBalance(newBal); Balance = 2 } withdraw(1.10); Final Balance = ? 5
  • 5. Simple Bank Withdraw Function void withdraw( double amount ) { double currentBal = getBalance(); double newBal = currentBal - amount; if( newBal < 0 ) throw new OverDraftException(); Initial account.setBalance(newBal);Balance = 2 } withdraw(1.10); Final Balance = ? Final Balance = 0.8999999999999999 6
  • 6. 7
  • 7. 8
  • 8. “Improved” Withdraw Function void withdraw( double amount ) { BigDecimal currentBal = getBalance(); BigDecimal newBal = currentBal.subtract(new BigDecimal(amount)); if( newBal.compareTo(BigDecimal.ZERO) < 0 ) throw new OverDraftException(); account.setBalance(newBal); } 9
  • 9. “Improved” Withdraw Function void withdraw( double amount ) { BigDecimal currentBal = getBalance(); BigDecimal newBal = currentBal.subtract(new BigDecimal(amount)); if( newBal.compareTo(BigDecimal.ZERO) < 0 ) throw new OverDraftException(); Initial Balance = 2 account.setBalance(newBal); } withdraw(1.10); Final Balance = ? Final Balance = 0.899999999999999911182158029987 10
  • 10. BigDecimal public BigDecimal(double val) Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating- point value. The scale of the returned BigDecimal is the smallest value such that (10scale × val) is an integer. http://docs.oracle.com/javase/6/docs/api/java/math/BigDecimal.html 11
  • 11. “Improved” Withdraw Function void withdraw( double amount ) { BigDecimal currentBal = getBalance(); BigDecimal newBal = currentBal.subtract(new BigDecimal(amount)); if( newBal.compareTo(BigDecimal.ZERO) < 0 ) throw new OverDraftException(); Initial Balance account.setBalance(newBal); = 1.10 } withdraw(1.10); Final Balance = ? OverDraftException 12
  • 12. One Solution: String Constructor void withdraw( String amount ) { BigDecimal currentBal = getBalance(); BigDecimal newBal = currentBal.subtract(new BigDecimal(amount)); if( newBal.compareTo(BigDecimal.ZERO) < 0 ) throw new OverDraftException(); account.setBalance(newBal); Initial Balance = 2 } withdraw(“1.10”); Final Balance = 0.90 13
  • 13. “The greatest obstacle to learning an API … is insufficient or inadequate examples” Martin Robillard. What Makes APIs Hard to Learn? Answers from Developers. IEEE Software, 26(6):27-34, 2009.
  • 14. The Rest of this Talk What makes a good example? Motivation Approach: Example Synthesis Evaluation 15
  • 15. The Rest of this Talk What makes a good example? Approach: Example Synthesis Evaluation 16
  • 16. What makes a good example?
  • 17. Some Common Sources of Examples 18
  • 18. Research Tools • MAPO – H. Zhong, T. Xie, L. Zhang, J. Pei, and H. Mei, “MAPO: Mining and recommending API usage patterns,” in European Conference on Object- Oriented Programming, 2009. • eXoaDocs – J. Kim, S. Lee, S. Hwang, and S. Kim, “Towards an intelligent code search engine,” in AAAI Conference on Artificial Intelligence, 2010. 19
  • 19. Research Tools • MAPO – H. Zhong, T. Xie, L. Zhang, J. Pei, and H. Mei, “MAPO: Mining and recommending API usage patterns,” in European Conference on Object- Oriented Programming, 2009. • eXoaDocs – J. Kim, S. Lee, S. Hwang, and S. Kim, “Towards an intelligent code search engine,” in AAAI Conference on Artificial Intelligence, 2010. 20
  • 20. Gold-Standard Human-Written Examples Tutorials JavaDocs 21
  • 21. Search-based examples BufferedReader reader = new BufferedReader(new InputStreamReader(page)); try {String line = reader.readLine(); while (line != null) { if (line.matches(substituteWikiWord(wikiWord,newTopicPattern))) { JExamples: BufferedReader 22
  • 22. Hand-Crafted Examples Example Data FileOutputStream fos = new FileOutputStream("t.tmp"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeInt(12345); oos.writeObject("Today"); oos.writeObject(new Date()); oos.close(); JavaDoc: java.util.ObjectOutputStream Complete 23
  • 23. Hand-Crafted Examples Abstract Initialization int glyphIndex = ...; GlyphMetrics metrics = GlyphVector.getGlyphMetrics(glyphIndex); int isStandard = metrics.isStandard(); float glyphAdvance = metrics.getAdvance(); JavaDoc: java.awt.font.GlyphMetrics 24
  • 24. Hand-Crafted Examples for(char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) { processChar(c); } Hole JavaDoc: java.text.CharacterIterator try { file.delete(); Hole } catch (IOException exc) { // failed to delete, do error handling here } return FileVisitResult.CONTINUE; JavaDoc: java.nio.FileVisitor 25
  • 25. Our API Examples FileReader fReader; //initialized previously BufferedReader br = new BufferedReader(fReader); while(br.ready()) { String line = br.readLine(); //do something with line } br.close(); Query: java.util.BufferedReader 26
  • 26. Our API Examples Common Abstract variable names Initialization FileReader fReader; //initialized previously BufferedReader br = new BufferedReader(fReader); while(br.ready()) { String line = br.readLine(); //do something with line } br.close(); “Holes” Query: java.util.BufferedReader Complete 27
  • 27. Automatic Documentation • Cheap • Always up-to-date • Complete • Well-defined trust properties • Structured (searchable) 28
  • 29. Specification Mining • ``Common behavior is correct behavior.'' Software Corpus Miner Common Patterns 30
  • 30. Specification Mining • ``Common behavior is correct behavior.'' Software Corpus Bug Finder Miner Common Patterns 31
  • 31. API Example Synthesis • ``Common behavior makes the best examples.'' Software Corpus Miner Code Gen Common Patterns 32
  • 32. Two Key Insights Dataflow Analysis Abstraction
  • 33. Two Key Insights Abstraction Operator Dataflow Analysis Abstraction
  • 34. Search Term Software “BufferedReader” Corpus Control Flow <init> Graph Representation ready Miner readLine print close 35
  • 35. argument Search Term argument “foo.txt” Software FileReader “BufferedReader” Corpus <init> identifier br ready Miner predicate ready() readLine returns String: line print With Dataflow argument Annotations Relevant line to Documentation close 36
  • 36. Search Term Software “BufferedReader” Corpus Miner ... Many Concrete Uses 37
  • 37. Multiple Common Patterns BufferedReader br = new BufferedReader(new FileReader("foo.in")); while( br.ready() ) { String s = br.readLine(); //Do something with s } BufferedReader br = new BufferedReader(new FileReader("foo.in")); String s; while( ( s = br.readLine() ) != null ) { //Do something with s } 38
  • 38. Clustering: Group Similar Patterns Many Concrete Uses … Grouped Into Clustering A Few Different Operator Patterns 39
  • 39. Clustering • k-medoids • Distance metric captures difference in order of statements and types of objects 40
  • 40. Abstraction Many Concrete Examples Abstraction Operator … Into One Abstract Example 41
  • 41. Concrete Concrete if(iter.hasNext()) { if(iter.hasNext()) { set.add( iter.next() ); print( iter.next() ); } } Abstraction Least-upper- Operator bound types if(iter.hasNext()) { Object o = iter.next(); Insert Hole //Do something with o } 42
  • 42. Concrete Iterator iter = set.iterator(); ... Concrete Iterator iter = list.iterator(); ... Abstraction Operator Abstract Initialization Iterator iter = SOMETHING.iterator(); ... 43
  • 43. Recap Software Corpus Mine Cluster Abstract Search Term 44
  • 44. Recap Software Corpus Mine Cluster Abstract Search Term Yield Well-Formed Code Gen Source Code 45
  • 45. Recap Software Corpus Mine Cluster Abstract Search Term Yield Well-Formed Code Gen Source Code 46
  • 46. 47
  • 47. Examples Calendar calendar = Calendar.getInstance(); Date d = calendar.getTime(); //Do something with d Query: java.util.Calendar 48
  • 48. Examples String regex; //initialized previously String input; //initialized previously Pattern pattern = Pattern.compile(regex); Matcher m = pattern.matcher(input); //Do something with m Query: java.util.regex.Pattern 49
  • 49. Limitations • Can’t always be perfectly precise – E.g., Aliasing, Types – Conservative analysis preserves correctness • Common usage is not always best – E.g., poor exception handling – Guarantee representative examples • Not all APIs have indicative patterns • Some patterns are difficult to find – Message passing over network etc. 50
  • 51. Name of Class Two examples randomly drawn from {Our Tool, Human- Written, eXoaDoc} Participant specifies preference 52
  • 52. Comparison to Code Search 53
  • 55. Warnings for Likely Mistakes 56
  • 58. Future Work • More Complex Queries – How do I use X with Y ? – Kuat Yessenov, Zhilei Xu, and Armando Solar- Lezama, Data-driven synthesis for object-oriented frameworks, OOPSLA, 2011. • What does this example do? – Symbolic execution of the example itself • Additional Guarantees – Proof Carrying Examples 59
  • 60. Documents how a source code change affects program behavior. arrestedcomputing.com/deltadoc 61
  • 61. 62
  • 62. 63
  • 63. 64