Whether to Include Java 8 Features James Heliotisjeh/Presentations/TeachingJava8... ·...

Preview:

Citation preview

CCSC Eastern Conference 2015 Tutorial

Whether to Include Java 8 Features in Introductory CS Courses

James HeliotisComputer ScienceRochester Inst. of Technologyjeh@cs.rit.edu

1

Our History in Java Education

❖ 1994: Beginning of OO 1st-year curriculum (Eiffel, C++)

❖ 1998: Switch to Java (C++ in 2nd year)

❖ 2008

❖ 1st two quarters in Python (algs & data structs)

❖ 3rd quarter in Java

❖ 2013: Semesters: CS1-Python; CS2-Java

2

Early Adoption

❖ Swing❖ Scanner

❖ Generics

❖ New for loop

3

Late Adoption

❖ enum

❖ just the C style, no advanced features

❖ packages

4

We do not include…

❖ Annotations

❖ except Override❖ java.util.concurrent ❖ assert

❖ (But a few of us encourage its use.)

5

Development Tools

❖ Originally, javac/java and emacs

❖ Recently, Eclipse, with CVS

❖ Currently, IntelliJ IDEA, with git (not github)

❖ (and PyCharm for Python)

6

Part 1: New Features

❖ Functional Interfaces and Lambda Expressions

❖ Default Methods in Interfaces

❖ JavaFX

7

1a. Functional Interfaces & Lambdas

8

Functional Interface: A Common Property

❖ Interfaces like ActionListener, Runnable, Comparable, and Comparator have a single abstract method(Functional interfaces used to be called SAMs.)

❖ For these cases we simply have a syntax issue called a vertical problem: 5 lines of code for one statement…

9

A Quick Example

❖ new Thread( new Runnable() { public void run() { sendNotification(); }} ).start();

❖ new Thread(() -> sendNotification() ).start();

10

Let’s break this down.❖ The important thing to remember is that this is not a

new feature of the Java Virtual Machine.

❖ It is a syntactic shorthand.

❖ Other examples

❖ Java generics: the casts you did at the turn of the century still happen at run time.

❖ “For each” loop: Iterator methods still called under the hood.

11

A Sample Classclass Person {

private String name;

private int age;

public Person( String n, int a ) { name = n; age = a; }

@Override public int hashCode() { /* … */ }

@Override public boolean equals( Object o ) { /* … */ }

@Override public String toString() { return name + '[' + age + ']'; }

public boolean mayDrink() { return age >= 21; }

}

12

Setup Code

Iterable< Person > people = new HashSet< Person >();

people.add( new Person( "Alice", 20 ) );

people.add( new Person( "Bob", 22 ) );

people.add( new Person( "Carol", 21 ) );

people.add( new Person( "Dan", 18 ) );

13

Example F.I.: Consumer

interface Consumer< T > {

public abstract void accept( T t );

// Default methods not shown.

}

14

Iterable no longer just makes Iterators

interface Iterable< T > {

Iterator<T> iterator(); public void forEach( Consumer< T > );

}

15

Iterable.forEach needs Consumer

interface Consumer< T > {

public abstract void accept( T t );

}

// How it normally works: public void forEach( Consumer< T > ){ for ( T t: this ) { action.accept( t ); } }

16

A Printing Consumer

class PersonPrinter implements Consumer< Person > {

@Override public void accept( Person p ) {

System.out.println( p );

}

}

17

Rewriting Action

people.forEach( new PersonPrinter() );

// See forEach in Iterable interface.Dan[18]Bob[22]Alice[20]Carol[21]

18

Nested Anonymous Class

people.forEach( new Consumer<Person>() {

public void accept( Person p ) {

System.out.println( p );

}

});Dan[18]Bob[22]Alice[20]Carol[21]

19

Lambda #1

people.forEach(

( Person p ) -> {

System.out.println( p );

}

);Dan[18]Bob[22]Alice[20]Carol[21]

20

Lambda #2

people.forEach(

p ->

System.out.println( p )

);Dan[18]Bob[22]Alice[20]Carol[21]

21

Lambda #3

people.forEach(

System.out::println

);Dan[18]Bob[22]Alice[20]Carol[21]

(This is called amethod reference.)

22

Condensing. . .

people.forEach( new Consumer<Person>() { public void accept( Person p ) { System.out.println( p );}});

people.forEach( (Person p) -> { System.out.println(p) ); }

people.forEach( p -> System.out.println(p) );

people.forEach( System.out::println );

23

Exercise❖ Using Person.java, modify it so that the TreeSet is

sorted by age.

❖ (Don’t bother with secondary name sorting.)

❖ I reassert:  its not about loops.  Loops are dead, the OS handles that. Better to know how to enumerate on a list or handle an event, or manage a thread.

❖ Ursula Wolz, 30 August 2013

❖ Modify the file further so that check uses forEach.

24

Technical Details You Should Know❖ Occasionally the type inference engine is unable to

determine the types needed to expand a lambda back to an anonymous class.

❖ A lambda may be cast with a Functional Interface.

❖ Remember that local variables used by an anonymous class’s methods must be final?

❖ This is true of lambdas, too, but now Java allows them to be effectively final.

25

Technical Details You Should Know

❖ One cannot break or continue out of lambda code.

❖ return always means return from the lambda.

❖ this does not refer to the hidden anonymous class instance. It still refers to the object on which the method containing the lambda was invoked.

26

java.util.stream.Stream

❖ If you use a Stream you have access to many methods besides forEach.

❖ Streams are sequences of elements, not necessarily finite.

❖ They often come out of collections.

❖ Their elements can be produced, transformed, and consumed.

27

Using Streams

people.stream()

.forEach(p -> System.out.println(p));

28

Another Functional Interface

interface Predicate< T > {

public abstract boolean test( T t );

// Default methods not shown.

}

29

Exercise

/** * Returns a stream consisting of the * elements of this stream that match the * given predicate. */Stream<T> filter(Predicate<? super T> predicate)

❖ Using this method from the Stream interface, enhance the printing statement so that it only prints people over the minimum drinking age

30

More Stream Operations

public long characterCount() { return children.stream() .mapToLong( text -> text.characterCount() ) .sum();} public void replace( String oldS, String newS ) { children.stream() .forEach( part -> part.replace( oldS, newS ) );}

My solution for an assignment that performed operations on trees

31

Recommendations

❖ Treat lambdas as you would iterators.

❖ It’s a shorthand.

❖ If the longhand way is occasionally needed, you still may have to teach it.

❖ However it is conceivable you could decide to drop anonymous classes altogether, in favor of lambdas and named classes.

32

Recommendations❖ Streams are iffy. You’re trying to get them to stop writing

loops.

❖ Probably don’t go further than forEach and filter.

❖ Currently some of our instructors test them on understanding lambdas and streams, but none so far require that all students be able to write them.

❖ However many students choose to do so.

33

1b. Default Methods in Interfaces

❖ One may now provide an implementation of a method in an interface,

❖ if it is labeled with the default keyword;

❖ if it only calls other methods in the interface, in the interfaces it extends, and in the Object class;

❖ if it does not depend on state.

❖ You still cannot declare (non-static) state in an interface.

34

From Brian Goetz's Article

❖ It is impossible to add methods to an interface without breaking existing implementations.

❖ The addition of closures … place [sic] additional stress on the aging Collection interfaces.

❖ ...C#-style static extension methods … cannot be overridden … so implementations are stuck with "one size fits all"...

35

Some Collection Examples❖ boolean removeIf( Predicate<? super E> filter )

❖ Stream< E > stream()

❖ The above things don’t really concern us.

❖ Different kinds of examples:

❖ Remember Adapter classes?❖ boolean isEmpty() (next slide) ❖ void display()

36

Handy Use of Default Methods

public interface Stuff { : : public int size(); public default boolean isEmpty() { return size() == 0; }}

37

Exercise

❖ Look at the Othello.java and OthelloImpl.java files. Make sure you understand them.

❖ Compile and run them.

❖ Change display so that it is a default method in the Othello interface.

38

Recommendations❖ We do not teach students to write default methods in their

interfaces.

❖ We occasionally use them

❖ when we want students to implement an interface we provide, but

❖ we want a standard way the information in the implementing class is output, and

❖ we don’t want to deal with students getting format wrong.

❖ There may be other cases like this one in the future.

39

Issue

❖ Since underlying differences between interface implementation and class inheritance remain the same, there was no confusion on students’ parts.

❖ Except:

❖ We have always told them methods are not implemented in interfaces. Now that’s a bit of a lie!

40

1c. JavaFX❖ JavaFX is the new preferred way of writing graphical

user interfaces in Java.

❖ In layout features, it is different than Swing, but conceptually not very different.

❖ JavaFX has a built-in MVC model that takes some time to learn.

❖ Programs written to this framework can also be targeted to run off a web server in a browser.

41

Simplest Examplepublic class JFX1 extends Application {

public void start( Stage stage ) {

stage.setTitle( "JFX1" );

stage.show();

}

// public static void main( String[] args ) {

// Application.launch( args );

// }

}

Application Methods: initpublic void init() throws java.lang.ExceptionThe application initialization method. This method is called immediately after the Application class is loaded and constructed. An application may override this method to perform initialization prior to the actual starting of the application.

The implementation of this method provided by the Application class does nothing.

NOTE: This method is not called on the JavaFX Application Thread. An application must not construct a Scene or a Stage in this method. An application may construct other JavaFX objects in this method.

Application Methods: startpublic abstract void start(Stage primaryStage) throws java.lang.ExceptionThe main entry point for all JavaFX applications. The start method is called after the init method has returned, and after the system is ready for the application to begin running.

NOTE: This method is called on the JavaFX Application Thread.

Parameters: primaryStage - the primary stage for this application, onto which the application scene can be set. The primary stage will be embedded in the browser if the application was launched as an applet. Applications may create other stages, if needed, but they will not be primary stages and will not be embedded in the browser.

Application Methods: stop

public void stop() throws java.lang.Exception

This method is called when the application should stop, and provides a convenient place to prepare for application exit and destroy resources. The implementation of this method provided by the Application class does nothing.

NOTE: This method is called on the JavaFX Application Thread.

JavaFX Terms

❖ Stage

❖ Somewhat akin to a window, or JFrame, from Swing

❖ There is a main one, but there may be more than one.

❖ Scene

❖ Something shown on a Stage

❖ You can switch between Scenes on one Stage.

❖ BorderPaneDemo shows a more complex layout with buttons and labels. Note that Swing’s layout managers are gone.

❖ ButtonEvents shows how to attach events to GUI elements (Nodes).

❖ LabelDemoEvents shows some things you can do when the mouse moves into a label.

Sample Code

Recommendations

❖ The jury is still out on this one.

❖ Swing is not liked by everyone, but it is still in use in some circles. A new textbook is coming out that still covers it.

Recommendations

❖ Although layout is not too bad, you have to be careful not to put too much detailed layout code into your examples. It is not as necessary as it appears.

❖ This framework was really designed to be used with a designer tool like netbeans. Most tutorials assume that’s what you’re doing.

Recommendations

❖ Simple event handling is also very similar to Swing.

❖ The MVC model, that automatically connects properties in your model to artifacts in the GUI, is not easy to learn.

Recommendations

❖ In our classes last year, we instead wrote the simple Action handlers you saw, and connected them to our models with the classic Observer/Observable classes found in the Java library.

❖ Our main goal is to teach students event-driven programming, not how to build state-of-the art user interfaces.

The Future of JavaFX at RIT

❖ Some professors want to return to Swing. This is not yet settled.

❖ This is the third term we are trying out JavaFX.

2. Impact on CS1/2

❖ Course Goals

❖ Student Readiness

❖ Part 1 Features Breakdown

53

Course Goals

❖ Most CS programs don’t treat their freshman courses as language training courses.

❖ What are the goals of yours?

❖ Computational thinking?

❖ Algorithms and data structures?

❖ Problem solving?

54

Student Readiness

❖ Experienced programmers tend to gravitate towards more concise expressions of their designs.

❖ But that’s because we already understand the underlying principles.

❖ Most of us try to keep syntactic blathering to a minimum in intro courses.

❖ …

55

Our Experience: Lambdas

❖ Most students seemed to prefer to use them over the old longer form.

❖ We did not test to make sure they knew what was really happening “under the hood”.

❖ We did not test the more compact forms.

56

Default Methods in Interfaces

❖ Students were not tested on this concept.

❖ A few assignments that provided interfaces had default methods, to save the students time.

❖ Classic example: print-game-state

❖ Since underlying differences between interface implementation and class inheritance remain the same, there was no confusion on students’ parts.

57

JavaFX

❖ Structural part is just a different way of expressing what you could express in Swing.

❖ Be careful not to focus on precision layout.

❖ Event handling is more problematic; more of the fundamentals are hidden behind higher-level concepts common in most GUI design frameworks.

58

A Practical Consideration

❖ Conflict!

❖ Is your system administrator, or IT service organization, willing to upgrade all of your lab computers?

❖ Will some students install the latest Java and inadvertently use features that will not compile on the computers you use for functionality assessment?

59

Recommended