Practical Programming in an Exception Free World

Slides:



Advertisements
Similar presentations
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Advertisements

Advanced Java Course Exception Handling. Throwables Class Throwable has two subclasses: –Error So bad that you never even think about trying to catch.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
Exceptions Handling Exceptionally Sticky Problems.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Creating a GUI Class An example of class design using inheritance and interfaces.
Using Sequential Containers Lecture 8 Hartmut Kaiser
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Introduction to Exceptions in Java CS201, SW Development Methods.
Coming up ArrayList ArrayList vs Array – Declaration – Insertion – Access – Removal Wrapper classes Iterator object.
Anger will never disappear so long as thoughts of resentment are cherished in the mind. Anger will disappear just as soon as thoughts of resentment.
JavaScript Part 1 Introduction to scripting The ‘alert’ function.
Putting Yourself into Words
Material Handling Business Goals
Essentials of UrbanCode Deploy v6.1 QQ147
Generics, Exceptions and Undo Command
Linked Lists in Action Chapter 5 introduces the often-used data public classure of linked lists. This presentation shows how to implement the most common.
May 17th – Comparison Sorts
Handling Exceptionally Sticky Problems
GETTING OUT OF PERSUASIVE SITUATIONS
Chapter 6: The Stack Abstract Data Type
Java Programming Language
10.3 Details of Recursion.
Addressing Pushback from Patients
C++ Standard Library.
English Proficiency Workshop
CS4450: Principles of Programming Languages
Syntax, semantics, and pragmatics
Reasonable adjustments and communication
Entry Task #1 – Date Self-concept is a collection of facts and ideas about yourself. Describe yourself in your journal in a least three sentences. What.
What Are They? Who Needs ‘em? An Example: Scoring in Tennis
Error Handling Summary of the next few pages: Error Handling Cursors.
WHY GOD CREATED CHILDREN
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
PROGRAMMING IN HASKELL
Functions Inputs Output
Lesson 2: Building Blocks of Programming
Learning to Program in Python
Final Project Details Note: To print these slides in grayscale (e.g., on a laser printer), first change the Theme Background to “Style 1” (i.e., dark.
Access Services 2.0: Tools for the new era
My Story Andrew.
Part B – Structured Exception Handling
We’re slowly working our way towards classes and objects
Object Oriented Practices
PROGRAMMING IN HASKELL
PROGRAMMING IN HASKELL
What Are They? Who Needs ‘em? An Example: Scoring in Tennis
ARRAYS 1 GCSE COMPUTER SCIENCE.
CSCE 489- Problem Solving Programming Strategies Spring 2018
Welcome Student SOAR to SOAR.
PROGRAMMING IN HASKELL
Fundamentals of Functional Programming
Focus of the Course Object-Oriented Software Development
Tonga Institute of Higher Education IT 141: Information Systems
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
New country and Varied Cultures
Tonga Institute of Higher Education IT 141: Information Systems
Review of Previous Lesson
Plan to Do Student Speeches
Handling Exceptionally Sticky Problems
Teaching speaking Aims:
Exceptions 10-May-19.
CMSC 202 Exceptions.
Lecture 3 More on Flow Control, More on Functions,
Difficult Conversation
Functions, Procedures, and Abstraction
Qualities for success bravery confidence creativity dedication enthusiasm flexibility talent wisdom.
Presentation transcript:

Practical Programming in an Exception Free World Sharon Holliday sharon.holliday@rea-group.com

Who am I? (what is important to me) a professional software developer (at REA Group, parent company of realestate.com.au) a polyglot – currently mostly scala need to deliver business functionality efficiently to do this, I need to not only write code but more often read and reason about existing code What’s not here : My goal is not to write “functional” code. My goal is not to “use folds” or “tail recursion”. I am not aiming to write “pure code”

☕ ☕ ☕ ☕ Sharon’s universal code metric: per LOC ☕ What is important to me Sharon’s universal code metric: ☕ per LOC ☕ ☕ ☕ Both when I am writing code, but more importantly, when I an reasoning about code. Less coffee is good More coffee is bad ☕

What we are going to cover today Why avoid exceptions? So how do we handle error situations? Real world examples Effect on my ☕ per LOC Why would we want an “exception free world”

Adam is going to offer us words of FP wisdom. Meet Adam Adam is going to offer us words of FP wisdom. Adam was my pair when I was first learning this stuff. He speaks “fluent FP” … which actually meant I didn’t understand a lot of what he tried to say to me.

… they break referential transparency Exceptions - why not? Don’t use exceptions … they break referential transparency

Vector[Int]: def max : Int Exceptions - why not? What does this do? How do I read that? parameters (name : Type) function name return type function body Vector[Int]: def max : Int Exceptions reduce my ability to reason about code

So how do we handle error situations? declare the error in the return type this will catch any error and convert it to a “Try” when we have no error when we have an error Try is an “abstract type” … two possible implementations All done right … well not quite lets try using it a bit more... Try[A] Failure(exception) Success(a:A)

So how do we handle error situations? Check for an empty vector: I had to create an exception I know I might get an empty vector. I want to handle that myself. Just in case Yuk! That doesn’t look “exception free”

Lets define our own error class So how do we handle error situations? Lets define our own error class So we don’t throw away information from a 3rd party … and lets use a scalaz “disjunction” to give us our return type A \/ B \/-(B) -\/(A) So we don’t throw away information from a 3rd party

So how do we handle error situations? How does our code look now: Informative return type No exception easy to wrap 3rd party code

So how do we handle error situations? Why did we use a Scalaz either? Why not a scala Either? Scala’s Either is not right biased The Scalaz disjunction comes with type-class instances for Functor, Monad, Applicative and more

Type-classes – a mental model So how do we handle error situations? Type-classes – a mental model Functor \/ def map(…) def lift(…) Monad def flatmap(…) Applicative We don’t have time to cover this. For the purposes of this talk they are a bag of methods that are made available on our class def … Traversable

And lets store them Property Agent agentId agents properties Real world example agentId Property Agent And lets store them agents Why would we need these bags of functions Lets create some stores to hold each of these (I’ve used maps here .. they might be a database, or some in-memory store) properties

Getting things from our store get the agent with this id Real world example Getting things from our store get the agent with this id we get back the agent or an error error if we didn’t find it return the agent Lets set the scene with a couple of methods that might give us errors

Given the agent id tell me the agent’s name, or an error if no agent Real world example ErrorOr[Agent] has a functor Look at the map method Follow the types Sharon Given the agent id tell me the agent’s name, or an error if no agent s"The agent is ${agent.name}” ErrorOr[A]: def map[B](g: A => B): ErrorOr[B] ‘A’ is Agent Agent => String ErrorOr[String] ErrorOr[Agent] We have a couple of stores with a way to get things out of them, that may succeed and may give us an error. Nice, but how are we going to use these in our real world program. Lets look at some examples. Some function that takes an agent and turns it into the string I need ‘B’ is String (agent name) {agent => agent.name}

We have a property id, get me the agent for the property Real world example ErrorOr[Agent] has a monad Look at the flatMap method We have a property id, get me the agent for the property “look up the property by id, and then use the resulting property's agent id to find the agent. If either of these lookups fail, give me the error” ErrorOr[A]: def flatMap[B](g: A => ErrorOr[B]):ErrorOr[B] Property => ErrorOr[Agent] ‘A’ is Property ‘B’ is Agent ErrorOr[Property] {property => getAgent(property.agentId)} ErrorOr[Agent]

Vector[A]: def map[B](g: A => B): Vector[B] Real world example Vector[Int] has a Functor instance. Look at the map method Given a list of agent ids, find the agents. Tell me whether you found each one. Vector[A]: def map[B](g: A => B): Vector[B] Vector[Int] Vector[ErrorOr[Agent]] Int => ErrorOr[Agent] ‘A’ is Int {agentId=> getAgent(agentId)} ‘B’ is ErrorOr[Agent]

ErrorOr must have an applicative Real world example Vector[A] has a Traverse instance. Take a look at the sequence method Follow the types Sharon Given a list of agentIds, give me all the agents, but if one of my agents doesn’t exist, give me back an error. Vector[A]: def sequence[G[_], B](implicit ev: A === G[B], G: Applicative[G]): G[Vector[B]] Vector[ErrorOr[Agent]] ErrorOr[Agent] ErrorOr[Vector[Agent]] ErrorOr must have an applicative ‘A’ is ErrorOr[Agent] G is ErrorOr B is Agent

B is String (agentName) Real world example Our Vector[Int] has a traverse method. It’s sort of like the sequence method, but applies a function as well. Given a list of agentIds I want a list of agent names, but give me an error if any of them don’t exist. Vector[A]: traverse[G[_], B](f: A => G[B])(implicit G: Applicative[G]): G[Vector[B]] Int => ErrorOr[String] ‘A’ is Int {agentId=> getAgent(agentId).map(_.name)} G is ErrorOr B is String (agentName)

Real world example Take a look at the monad separate method Given a list of agentIds I want a list of all the agents that exist, also give me a list of all the errors for any that didn’t exist Vector[A]: def separate[G[_, _], B, C](…A === G[B, C], …): (Vector[B], Vector[C]) ErrorOr[Agent] Rewrite it as: \/[AppError, Agent] B = AppError, C=Agent ‘A’ – ErrorOr[Agent]

Why was this better than exceptions? We saw a lot of ways to work with our errors We didn’t really do anything other than plug in generic functions (no folds, recursion etc..) We didn’t need any special exception handling syntax We could have done the same thing with Futures, Options, FreeMonads That’s the end of the examples I have for you, So let’s just recap and see why this was better than exceptions We have covered a lot of functionality in the last ten minutes ☕

☕ Powerful Learning/ Discovering it requires Some final thoughts Powerful Learning/ Discovering it requires Learn it once, reapply it lots How can I learn this …I don’t have an “FP in Scala” Paul Chiusano and Rúnar Bjarnason “Cats” library documentation: http://typelevel.org/cats/index.html ☕

QUESTIONS