Functional principles for object-oriented

Slides:



Advertisements
Similar presentations
ACM/JETT Workshop - August 4-5, Classes, Objects, Equality and Cloning.
Advertisements

CMSC 330: Organization of Programming Languages Tuples, Types, Conditionals and Recursion or “How many different OCaml topics can we cover in a single.
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
1 Working with References. 2 References Every object variable is a reference to an object Also true when an object is passed as an argument When the object.
Logic & program control part 2: Simple selection structures.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
START DEFINITIONS values (3) N1 = (8, 1,-9) i N1 average N3,2 sum N2 = 0 temp N1 Do not guess or assume any values! Follow the values of the variables.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
James Tam Object-Oriented Design Approaches to object-oriented design Some principles for good design Benefits and Drawbacks of the Object-Oriented Approach.
Defining classes and methods Recitation – 09/(25,26)/2008 CS 180 Department of Computer Science, Purdue University.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Functional Design and Programming Lecture 1: Functional modeling, design and programming.
1 Gentle Introduction to Programming Session 2: Functions.
Loops – While, Do, For Repetition Statements Introduction to Arrays
COMS S1007 Object-Oriented Programming and Design in Java August 7, 2007.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Programming in Scala Chapter 1. Scala: both object-oriented and functional Scala blends –object-oriented and –functional programming in a –statically.
Javascript II Expressions and Data Types. 2 JavaScript Review programs executed by the web browser programs embedded in a web page using the script element.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
TODAY’S LECTURE Review Chapter 2 Go over exercises.
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
1 Identifiers  Identifiers are the words a programmer uses in a program  An identifier can be made up of letters, digits, the underscore character (
Announcements  If you need more review of Java…  I have lots of good resources – talk to me  Use “Additional Help” link on webpage  Weekly assignments.
CIS Computer Programming Logic
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Java: Chapter 1 Computer Systems Computer Programming II.
The Java Programming Language
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
Best Practices. Contents Bad Practices Good Practices.
 The if statement and the switch statement are types of conditional/decision controls that allow your program.  Java also provides three different looping.
© The McGraw-Hill Companies, 2006 Chapter 2 Selection.
Module 3: Steering&Arrays #1 2000/01Scientific Computing in OOCourse code 3C59 Module 3: Algorithm steering elements If, elseif, else Switch and enumerated.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Functions and Methods. Definitions and types A function is a piece of code that takes arguments and returns a result A pure function is a function whose.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
Introduction to Programming
22/11/ Selection If selection construct.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
RUBY by Ryan Chase.
More About Data Types & Functions. General Program Structure #include statements for I/O, etc. #include's for class headers – function prototype statements.
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
Introduction to Java John Lewis. Course Overview Introduction Object Orientated Programming Java Structure and Syntax Using the Java Platform Advanced.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Mid-Year Review. Coding Problems In general, solve the coding problems by doing it piece by piece. Makes it easier to think about Break parts of code.
100e Hosted by vhs © Don Link, Indian Creek School, 2004 Jeopardy.
Sequences and for loops. Simple for loops A for loop is used to do something with every element of a sequence scala> for (i
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Objects and Memory Mehdi Einali Advanced Programming in Java 1.
Equality, references and mutability COMPSCI 105 SS 2015 Principles of Computer Science.
CS314 – Section 5 Recitation 9
Object-Oriented Concepts
The need for Programming Languages
CIS3931 – Intro to JAVA Lecture Note Set 2 17-May-05.
null, true, and false are also reserved.
Conditional Statements
CSC1018F: Intermediate Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Tonga Institute of Higher Education
Presentation transcript:

functional principles for object-oriented

Imperative Procedural Object-Oriented Functional Aspect-Oriented Logic

Data In, Data Out Immutability Verbs Are People Too Declarative Style Specific Typing Lazy Evaluation

What is it? Principle What is it? We already do it What’s the point? What is it? Scala / F# Java / C#

Data In, Data Out

access global state modify input change the world

Data In -> ? -> Data out input output

Testable Easier to understand

the flow of data

List List > List

Problem easier, because we know each step of the way of data.

public string CreateAccount(UserDbService db, String , String password) { … }

String password; String ; private boolean invalidPassword() { return !password.contains( ); }

private boolean invalidPassword(String password, String ) { return !password.contains( ); }

Immutability

modify anything

Concurrency fewer possibilities

NPE

c c

String Effective Java Effective C#

Scala val qty = 4 // immutable var n = 2 // mutable

let qty = 4 // immutable let mutable n = 2 // mutable n = 4 // false n <- 4 // destructive update F#

C#: easy public struct Address { private readonly string city; public Address(string city) : this() { this.city = city; } public string City { get { return city; } }

Java: defensive copy private final ImmutableList phones; public Customer (Iterable phones) { this.phones = ImmutableList.copyOf(phones); }

Java: copy on mod public Customer addPhone(Phone newPhone) { Iterable morePhones = ImmutableList.builder().addAll(phones).add(newPhone).build(); return new Customer(morePhones); }

fruit fruit.add(tomato)

F#: copy on mod member this.AddPhone (newPhone : Phone) { new Customer(newPhone :: phones) }

C#: shallow copy public Customer AddPhone(Phone newPhone) { IEnumerable morePhones = // create list return new Customer(morePhones, name, address, birthday, cousins); }

this talk is brought to you by… the Option type! NPE Thing doStuff() NullThing doStuff() {} SomeThing doStuff() {…} Option None Some

… because null is not a valid object reference. Optional FSharpOption

Verbs Are People Too

Imperative Procedural Object-Oriented Functional Aspect-Oriented Logic !=

Strategy Command OnClick() release ( )

class CostInflation implements FunctionOverTime { public float valueAt(int t) { return // some calculated value; } Java

val costInflation = Variable ( “Cost Inflation”, t => Math.pow(1.15,t)) val seasonalVolume = Array(0.95,0.99,1.01,…) val seasonalAdjustment = Variable(“Season”, t => seasonalVolume(t)) Scala

C# private readonly Func calc; public Func ValueAt { get { return calc; } }

C# var inflation = new Variable(“Inflation”, t => Math.Pow(1.15,t)); inflation.ValueAt(3);

Java Variable inflation = new Variable (“Inflation”, new Function () public Double apply(Integer input) { return Math.pow(1.15, input); } });

Java 8 Variable inflation = new Variable (“Inflation”, t => Math.pow(1.15, t) );

Declarative Style

say what you’re doing, not how you’re doing it

Select ROLE_NAME, UPDATE_DATE From USER_ROLES Where USER_ID = :userId

smaller pieces readable code

familiar != readable

Java public List findBugReports(List lines) { List output = new LinkedList(); for(String s : lines) { if(s.startsWith(“BUG”)) { output.add(s); } return output; }

Scala lines.filter( _.startsWith(“BUG”)) lines.par.filter( _.startsWith(“BUG”))

Java final Predicate startsWithBug = new Predicate () { public boolean apply(String s) { return s.startsWith("BUG"); } }; filter(list, startsWithBug);

C# lines.Where(s => s.StartsWith(“BUG”)).ToList

this talk is brought to you by… the Tuple type! function new Tuple (“You win!”, )

When one return value is not enough! Tuple

Specific Typing

expressiveness catch errors early

The beginning of wisdom is to call things by their right names.

F# [ ] type cents let price = 599

Scala type FirstName = String // type alias Customer(name : FirstName, home : Address)

Scala case class FirstName(value : String) let friend = FirstName(“Ivana”);

Java public User(FirstName name, Address login) public class FirstName { public final String stringValue; public FirstName(final String value) { this.stringValue = value; } public String toString() {...} public boolean equals() {...} public int hashCode() {...} }

State everything you need State only what you need

Scala List [+A] def indexOf [B >: A] (elem: B): IntInt def sameElements (that: GenIterable[A]): BooleanIterable[A]

C#: weak public boolean Valid(Customer cust) { Address = cust. Address; // exercise business logic return true; }

C#: weak public boolean Valid(IHas Address anything) { Address = anything. Address; // exercise business logic return true; } interface IHas Address { string Address {get; } }

Lazy Evaluation

delay evaluation until the last responsible moment

save work separate “what to do” from “when to stop”

int bugCount = 0; String nextLine = file.readLine(); while (bugCount < 40) { if (nextLine.startsWith("BUG")) { String[] words = nextLine.split(" "); report("Saw "+words[0]+" on "+words[1]); bugCount++; } waitUntilFileHasMoreData(file); nextLine = file.readLine(); } Java

for (String s : FluentIterable.of(new RandomFileIterable(br)).filter(STARTS_WITH_BUG_PREDICATE).transform(TRANSFORM_BUG_FUNCTION).limit(40).asImmutableList()) { report(s); } Java Iterable: laziness is a virtue

C# IEnumerable ReadLines(StreamReader r) { while (true) { WaitUntilFileHasMoreData(r); yield return r.ReadLine(); }

Data In, Data Out Immutability Verbs Are People Too Declarative Style Specific Typing Lazy Evaluation

I promise not to exclude from consideration any idea based on its source, but to consider ideas across schools and heritages in order to find the ones that best suit the current situation.

Man, the living creature, the creating individual, is always more important than any established style or system. – Bruce Jessica Kerr blog.jessitron.com github.com/jessitron/fp4ood