How Scala Improved Our Java



Similar documents

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

CS 335 Lecture 06 Java Programming GUI and Swing

Programming with Java GUI components

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Using A Frame for Output

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

JiST Graphical User Interface Event Viewer. Mark Fong

Fundamentals of Java Programming

Introducing Apache Pivot. Greg Brown, Todd Volkert 6/10/2010

Extending Desktop Applications to the Web

GUI Event-Driven Programming

Assignment # 2: Design Patterns and GUIs

Syllabus for CS 134 Java Programming

Java Application Developer Certificate Program Competencies

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

How To Build A Swing Program In Java.Java.Netbeans.Netcode.Com (For Windows) (For Linux) (Java) (Javax) (Windows) (Powerpoint) (Netbeans) (Sun) (

Advanced Network Programming Lab using Java. Angelos Stavrou

Karsten Lentzsch JGoodies SWING WITH STYLE

Nexawebホワイトペーパー. Developing with Nexaweb ~ Nexaweb to Improve Development Productivity and Maintainability

Developing GUI Applications: Architectural Patterns Revisited

Computing Concepts with Java Essentials

Swing. A Quick Tutorial on Programming Swing Applications

How To Use The Command Pattern In Java.Com (Programming) To Create A Program That Is Atomic And Is Not A Command Pattern (Programmer)

Essentials of the Java(TM) Programming Language, Part 1

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition

History OOP languages Year Language 1967 Simula Smalltalk

Tutorial on Writing Modular Programs in Scala

Tutorial: Time Of Day Part 2 GUI Design in NetBeans

Graphical User Interfaces

How to Convert an Application into an Applet.

public class Craps extends JFrame implements ActionListener { final int WON = 0,LOST =1, CONTINUE = 2;

A Scala Tutorial for Java programmers

Java SE 6 Update 10. la piattaforma Java per le RIA. Corrado De Bari. Sun Microsystems Italia Spa. Software & Java Ambassador

How To Program In Java (Ipt) With A Bean And An Animated Object In A Powerpoint (For A Powerbook)

Principles of Software Construction: Objects, Design and Concurrency. GUIs with Swing. toad Spring 2013

Mobile Web Design with HTML5, CSS3, JavaScript and JQuery Mobile Training BSP-2256 Length: 5 days Price: $ 2,895.00

Artificial Intelligence. Class: 3 rd

Visualizing Software Projects in JavaScript

AP Computer Science Java Subset

Tutorial Reference Manual. Java WireFusion 4.1

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

LAB4 Making Classes and Objects

Chapter 1 Fundamentals of Java Programming

Frameworks & Android. Programmeertechnieken, Tim Cocx

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Object Oriented Programming with Java. School of Computer Science University of KwaZulu-Natal

Lab 9. Spam, Spam, Spam. Handout 11 CSCI 134: Spring, To gain experience with Strings. Objective

Model-View-Controller (MVC) Design Pattern

Analyse et Conception Formelle. Lesson 5. Crash Course on Scala

Yosemite National Park, California. CSE 114 Computer Science I Inheritance

Software Design: Figures

Java the UML Way: Integrating Object-Oriented Design and Programming

Essentials of the Java Programming Language

Fondamenti di Java. Introduzione alla costruzione di GUI (graphic user interface)

Homework/Program #5 Solutions

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Eclipse with Mac OSX Getting Started Selecting Your Workspace. Creating a Project.

The Needle Programming Language

file://c:\dokumente und Einstellungen\Marco Favorito\Desktop\ScanCmds.html

Java Interview Questions and Answers

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Specialized Programme on Web Application Development using Open Source Tools

Kotlin for Android Developers

Semantic Analysis: Types and Type Checking

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Java is commonly used for deploying applications across a network. Compiled Java code

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

#820 Computer Programming 1A

BHARATHIAR UNIVERSITY COIMBATORE SCHOOL OF DISTANCE EDUCATION

Skills and Topics for TeenCoder: Java Programming

Java (12 Weeks) Introduction to Java Programming Language

Java Programming Fundamentals

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

The Basic Java Applet and JApplet

Java 7 Recipes. Freddy Guime. vk» (,\['«** g!p#« Carl Dea. Josh Juneau. John O'Conner

Computer Programming I

Konzepte objektorientierter Programmierung

The BSN Hardware and Software Platform: Enabling Easy Development of Body Sensor Network Applications

Android Application Development Course Program

Software Engineering Techniques

Rich Internet Applications

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

CS 111 Classes I 1. Software Organization View to this point:

TATJA: A Test Automation Tool for Java Applets

Specialized Android APP Development Program with Java (SAADPJ) Duration 2 months

Computer Programming I

RuleBender Tutorial

An Overview of Java. overview-1

Moving from CS 61A Scheme to CS 61B Java

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Transcription:

How Scala Improved Our Java Sam Reid PhET Interactive Simulations University of Colorado http://spot.colorado.edu/~reids/

PhET Interactive Simulations Provides free, open source educational science simulations at http://phet.colorado.edu/ Used in middle school, high school, college Translated into 58 languages Launched over 2 million times per month, and growing Simulations written in Java, Flash, Flex & Scala 2

3

PhET s Scala Simulations Gravity Force Lab Ladybug Motion 2D Forces and Motion Ramp: Forces and Motion Launched over 50,000 times in the last month Translated into over 25 languages 4

5

Advantages of Scala over Java Function literals useful in GUI callbacks and observer pattern Operator infix notation useful in 2D vector arithmetic Case classes and immutability simplified record/playback For comprehensions If/else more readable than Java s ternary Many more! 6

Better Java 1. Improved object initialization 2. Improved management of boilerplate 3. Reduced code duplication 4. Improved code organization 7

1. Idiomatic Java for Object Initialization JButton button = new JButton("Click Me"); JLabel label = new JLabel("No clicks yet"); JPanel contentpane = new JPanel(); contentpane.add( button ); contentpane.add( label ); JFrame frame = new JFrame("Reactive Swing App"); frame.setcontentpane( contentpane ); 8

Idiomatic Scala def top = new MainFrame { title = "Reactive Swing App" val button = new Button { text = "Click me val label = new Label { text = "No clicks yet contents = new BoxPanel(Orientation.Vertical) { contents += button contents += label 9

Idiomatic Scala + Inline Declarations def top = new MainFrame { title = "Reactive Swing App" contents = new BoxPanel(Orientation.Vertical) { contents += new Button {text = "Click me contents += new Label {text = "No clicks yet 10

Advantages of Scala initialization Structural instead of procedural More natural: a frame with a button Intended scope clear Top down instead of bottom-up Object correct upon instantiation, instead of mutating through a series of incorrect states No need to build a mental model of many-tomany map; code is a tree like the object graph 11

Double Brace Initialization JFrame frame = new JFrame("Reactive Swing App") {{ setcontentpane( new JPanel() {{ add(new JButton( "Click Me" ) ); add(new JLabel( "No clicks yet" ) ); ); ; 12

DBI Issues Like Scala, creates an anonymous subclass About 454 bytes each 100 DBI s increases a 2MB JAR by about 2% Need to be cautious about equals, hashcode, serialization Unfamiliar style to idiomatic Java programmers? 13

When to use anonymous subclass? Describing object state in an object tree Constructor is insufficient When not to use? Too many nested levels can be confusing Especially when nesting objects of similar type No name for intermediate this 14

Better Java 1. Improved object initialization 2. Improved management of boilerplate 3. Reduced code duplication 4. Improved code organization 15

2. Closure Folding: Before and After //Idiomatic Java model.addlistener( new Listener() { public void update() { trace( "hello" ); ); //Idiomatic Scala m.addlistener( ()=>{trace("hello") //Java code with closure folding m.addlistener(listener(){trace( "hello" );); 16

Benefits of Closure Folding Easier to read and understand Helps you focus on the tricky parts See more code at once In production code, 49 lines of code reduced to 9 in one file Closure folding accentuates advantages in Listener callbacks Inner functions 17

Better Java 1. Improved object initialization 2. Improved management of boilerplate 3. Reduced code duplication 4. Improved code organization 18

3. Listeners in Java public class Player { private String name = ;//set in constructor private List<Listener> listeners = new ArrayList<Listener>(); public void addlistener( Listener listener ) { listeners.add( listener ); public void setname( String name ) { this.name = name; //Copy since list may be modified during traversal for ( Listener listener : new ArrayList(listeners) ) listener.namechanged( this ); public static interface Listener { void namechanged( Player player ); void agechanged( Player player ); 19

Listener Client Code public class ListenerClient { public static void main( String[] args ) { Player player = new Player( Larry ); final JTextField tf = new JTextField( Name is: " + player.getname() ); player.addlistener( new Listener() { public void namechanged( Player player ) { tf.settext( "The name is: " + player.getname() ); public void agechanged( Player player ) { ); 20

Problems with Java Idiom Duplicated code to implement observers Duplicated code in synchronizing a client with the observable Potential mismatch between initial and subsequent values Duplicated code in wiring up to GUI controls 21

Control Structure in Scala var text: String = null val player = new Player("Larry") invokeandpass(player.addlistener) { tf.settext( "The name is: " + player.getname() ) player.name = "Steve" //Result //The name is: Larry //The name is: Steve 22

Reusable Check Box in Scala class FunctionCheckBox( text: String, actionlistener: Boolean => Unit, getter: () => Boolean, addlistener: ( () => Unit ) => Unit ) extends CheckBox //How to encapsulate all these parts? 23

Property<T> and Binding name = new Property<String>( Larry ); name.addobserver( n{ tf.settext( The name is: + n );); name.set( Steve ); //Displayed in the text field: // The name is: Larry // The name is: Steve See also: Maier s Signal[+A] Deprecating the Observer Pattern, EPFL Report: Maier, Rompf, Odersky Scala.React JavaFX Java API for properties and binding 24

ObservableProperty class ObservableProperty<T>{ List<VoidFunction1<T>> observers = abstract T get(); //Adds an observer that will be automatically notified with the current value, and when the value changes addobserver(voidfunction1<t> observer){ observers.add(observer); observer.apply(get()); 25

Property Composition DSL public class DividedBy extends CompositeDoubleProperty{ public DividedBy( final ObservableProperty<Double> num, final ObservableProperty<Double> den){ super(function0(){return num.get()/den.get();,num,den); //Compute concentration of salt = moles/volume ObservableProperty<Double> saltconcentration= salt.molesdissolved.dividedby(solution.volume); //Show remove button if any salt or sugar ObservableProperty<Boolean> anysolutes = salt.greaterthan( 0 ).or(sugar.greaterthan( 0 )); 26

PropertyCheckBox in Java public PropertyCheckBox( String text, super( text ); final SettableProperty<Boolean> p) { // update the model when the check box changes addchangelistener(changelistener(e) {p.set( isselected() ); ); // update the check box when the model changes p.addobserver(simpleobserver() {setselected( p.get() );); //Sample usage add(new PropertyCheckBox( gravity on, gravityenabled)); add(new PropertyCheckBox( gravity off, not(gravityenabled))); 27

Pros and Cons of Property<T> Pro Uniform API for dealing with mutable state Good for binding/synchronization Useful in removing duplicated code Blocks against redundant messages Con Impedance mismatch when interfacing with legacy code Sometimes harder to debug than primitives Most suitable for 1-way flow of information 28

Better Java 1. Improved object initialization 2. Improved management of boilerplate 3. Reduced code duplication 4. Improved code organization 29

4. Private Methods in Java public PrismGraphic(){ //Initialization code color = createcolor(wavelength); neighborcolor = createcolor(wavelength+10); //Many more lines //of complex initialization code // //Other methods private Color createcolor(double wavelength){ //code to return the Color for a wavelength 30

Vs. Inner Functions in Scala public PrismGraphic(){ def createcolor = (d:double)=>{ color = createcolor(wavelength); neighborcolor=createcolor (wavelength+10); 31

Inner Functions Pro Local scope makes it obvious to maintainer where it is supposed to be used Reduces clutter in class namespace Con Sometimes good to move implementation away from usage point to improve readability 32

Inner Function in Java public PrismGraphic(){ Function1<Double,Color> createcolor = Function1(Double wavelength) { return ; color = createcolor.apply(wavelength); neighborcolor=createcolor.apply(wavelength+10); 33

Larger Example/Idiomatic Java public class TestWithoutDBI { private Color color = Color.red; private ArrayList<ColorChangeListener> listeners = new public interface ColorChangeListener { void colorchanged( Color color ); public void addcolorchangelistener( ColorChangeListener cl ) { listeners.add( cl ); private void start() { JFrame frame = new JFrame(); final JPanel contentpane = new JPanel(); 34

//Button that makes the label red final JButton redbutton = new JButton( "Make it Red" ); redbutton.addactionlistener( new ActionListener() { public void actionperformed( ActionEvent e ) { setcolor( Color.red ); ); contentpane.add( redbutton ); //Radio boxes to change the color final JRadioButton greenradiobutton = new JRadioButton( "Green" ); greenradiobutton.addactionlistener( new ActionListener() { public void actionperformed( ActionEvent e ) { setcolor( Color.green ); ); contentpane.add( greenradiobutton ); final JRadioButton blueradiobutton = new JRadioButton( "Blue" ); 35

blueradiobutton.addactionlistener( new ActionListener() { public void actionperformed( ActionEvent e ) { setcolor( Color.blue ); ); contentpane.add( blueradiobutton ); ButtonGroup buttongroup = new ButtonGroup(); buttongroup.add( greenradiobutton ); buttongroup.add( blueradiobutton ); buttongroup.add( redbutton ); //A label whose color is set based on the property final JLabel label = new JLabel( "A Colored Label" ); addcolorchangelistener( new ColorChangeListener() { public void colorchanged( Color color ) { label.setforeground( color ); ); label.setforeground( color ); 36

contentpane.add( label ); frame.setcontentpane( contentpane ); frame.pack(); frame.setvisible( true ); private void setcolor( Color color ) { boolean changed =!this.color.equals( color ); this.color = color; if ( changed ) { for ( ColorChangeListener listener : listeners ) { listener.colorchanged( color ); 37

Same Example: Folding/DBI/Properties new JFrame() {{ final Property<Color> color = new Property<Color>( red ); //Set the content pane, which contains controls for changing the red property and a label that is shown in the selected color setcontentpane( new JPanel() {{ //Button that makes the label red add( new JButton( "Make it Red" ) {{ addactionlistener( event { color.set( red ); ); ); //Radio boxes to change the color add( new PropertyRadioButton<Color>( Green", color, green ) ); add( new PropertyRadioButton<Color>( Blue", color, blue ) ); //A label whose color is set based on the property add( new JLabel( "A Colored Label" ) {{ color.addobserver( color { setforeground( color ); ); ); ); pack();.setvisible( true ); 38

Conclusion Goal: code easier to write/read/maintain Improved object initialization Double-brace pattern Improved management of boilerplate Closure folding Reduced code duplication Variable binding Improved code organization Local function objects 39

Questions? 40