Spartan Programming Technion – Institute of Technology 236700 Author: Gal Lalouche - Technion 2016 © 1 “Minimalism isn't always the right choice, but it's.

Slides:



Advertisements
Similar presentations
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Advertisements

Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Coding Standard: General Rules 1.Always be consistent with existing code. 2.Adopt naming conventions consistent with selected framework. 3.Use the same.
CS0007: Introduction to Computer Programming
Written by: Dr. JJ Shepherd
Internal Documentation Conventions. Kinds of comments javadoc (“doc”) comments describe the user interface: –What the classes, interfaces, fields and.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
11-Jun-15 Exceptions. 2 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.
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.
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 reference.
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
Make Sure You Know All This!. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling 2 Objects and Classes.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
Guide To UNIX Using Linux Third Edition
Algorithm Programming Coding Advices Bar-Ilan University תשס " ו by Moshe Fresko.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Interlude: Functional Programming CSE 331 Section 2 James Daly.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
Monads Technion – Institute of Technology Software Design (236700) Author: Gal Lalouche - Technion 2015 © 1.
Java 8 Lambda expressions and you Technion – Institute of Technology Software Design (236700) Based on slides by: Sagie Davidovich, Assaf Israel Author:
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
A Computer Science Tapestry 1 Recursion (Tapestry 10.1, 10.3) l Recursion is an indispensable technique in a programming language ä Allows many complex.
Lists in Python.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
1 Object Oriented Programming Lecture IX Some notes on Java Performance with aspects on execution time and memory consumption.
Exceptions Handling Exceptionally Sticky Problems.
1 Software Construction and Evolution - CSSE 375 Exception Handling - Principles Steve Chenoweth, RHIT Above – Exception handling on the ENIAC. From
CIT 590 Intro to Programming First lecture on Java.
Testing. 2 Overview Testing and debugging are important activities in software development. Techniques and tools are introduced. Material borrowed here.
Best Practices. Contents Bad Practices Good Practices.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
CS242.  Reduce Complexity  Introduce an intermediate, understandable abstraction  Avoid code duplication  Support subclassing  Hide sequences  Hide.
Documentation Dr. Andrew Wallace PhD BEng(hons) EurIng
Object Oriented Software Development
Refactoring 2. Admin Blackboard Quiz Acknowledgements Material in this presentation was drawn from Martin Fowler, Refactoring: Improving the Design of.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Javadoc. Purpose of javadoc javadoc is a program that reads your Java program and produces great-looking documentation in HTML format Without any help,
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
GoodOO Programming Practice in Java © Allan C. Milne v
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
SEG 4110 – Advanced Software Design and Reengineering Topic T Introduction to Refactoring.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
Refactoring Agile Development Project. Lecture roadmap Refactoring Some issues to address when coding.
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
Written by: Dr. JJ Shepherd
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Effective Java, Chapter 9: Exceptions Items Last modified Fall 2012 Paul Ammann.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
Monads Technion – Institute of Technology Software Design (236700) Author: Gal Lalouche - Technion 2016 © 1.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
More Sophisticated Behavior
C++ coding standard suggestion… Separate reasoning from action, in every block. Hi, this talk is to suggest a rule (or guideline) to simplify C++ code.
Lecture 15 (Notes by P. N. Hilfinger and R. Bodik)
Homework Any Questions?.
Peter Seibel Practical Common Lisp Peter Seibel
Effective Java, Chapter 9: Exceptions
„Lambda expressions, Optional”
Refactoring.
Testing Slides adopted from John Jannotti, Brown University
Presentation transcript:

Spartan Programming Technion – Institute of Technology Author: Gal Lalouche - Technion 2016 © 1 “Minimalism isn't always the right choice, but it's rarely the wrong choice”

Spartanization What it is A refactoring method A powerful tool when used right Often in conflict with what you’ve learnt in MATAM But it’s not A style convention A practice to adhere to at all costs Something to get worked up about Author: Gal Lalouche - Technion 2016 © 2

What are (some of) the reasons for complex code? Inability see all the code at once Long methods Many variables / method arguments Error handling Complex state mutability in general Hidden side effects Complex controls Nested If-statements Complex Loops (Index iterations) Conditional expressions are vague Author: Gal Lalouche - Technion 2016 © 3

Spartan Programming Principles: Eliminate duplications Minimize: #lines #columns #tokens #variables #branches #nested statements How? Everything should be as short as possible, but not shorter Minimize comments Frugal use of variables Small interfaces Minimal use of control Monadic Design Think of code as Lines spent not lines written Author: Gal Lalouche - Technion 2016 © 4

Minimize comments Comments are usually a code smell Your code should be understandable without reading walls of text If it isn’t, make it so; if you can’t, ask yourself why Comments are a subtle form of code duplication If the code changes, they should change too But you don’t always remember to… Instead, use comments to explain decisions that are out of the ordinary, to ensure they don’t accidentally deleted or changed // the algorithm works better with a linked // list than an array list List list = new LinkedList<>() But! You should still use javadoc to document all accessible classes and methods that are part of your API Rule of thumb: Javadocs explain what, code explains how, comments explain why Author: Gal Lalouche - Technion 2016 © 5

Frugal Use of Variables Minimize: Number of variables: inline what is possible, minimize what cannot “But naming a variable explains its meaning!” – if that variable is inlined, then there is nothing that needs to be explained Life time of variable Scope and context where can they be used Prefer local variables to fields, scoped variables to local Everything should live in the smallest possible context Reduces namespace pollution Can use extra context to reduce name size (see next slide) Author: Gal Lalouche - Technion 2016 © 6

Small Interfaces Avoid Arrays! Minimize mutability Minimize side-affecting parameters Parameters that can be mutated, or mutate the object accepting them Parameter kind priority Input parameters Output parameters Input-output parameters Pass by name (e.g. file names as Strings) But you should have a really good reason why you are using the above three… Minimize the number of method parameters Avoid flags, i.e., Boolean parameters Use a method with a different name open() and close() are better than setOpened(boolean b) Avoid consecutive parameters of the same type Prefer builder objects to method overloads Author: Gal Lalouche - Technion 2016 © 7

Small Interfaces – Short method names Shorter method names are easier to remember and think about Prefer one word verb method names e.g., map, filter, reduce Use two words to differentiate methods e.g., map, flatMap; fold, foldLeft, foldRight; Methods that return a modified copy should be in the passive voice, e.g., sorted, reversed Add question modifier for methods returning boolean e.g., isEmpty, hasValues Use class context to cut words Url.getUrlAddress() vs. Url.getAddress() Author: Gal Lalouche - Technion 2016 © 8

Small Interfaces – Short variable names The previous discussion also applies to variable and field names, but there is more to add… Use $ for a “special” variable e.g., return value of a function, object undergoing test, temporary variable Use generic names whenever possible If a method can accept any value, there’s no need for a long name Compare: isPalindrome(String possiblePalindrome) with isPalindrome(String s) or isPrime(int number) with isPrime(int n) Use a qualified name if there are expectations: connectTo(String urlAddress) But prefer not to have any expectation! If you can’t use a generic name, always ask yourself “why?” Author: Gal Lalouche - Technion 2016 © 9

Minimal use of Control Prefer declarative code to imperative code Avoid conditionals Ternary operators ( ?: ) are evil when composed Avoid else as much as possible Avoid complicated boolean expressions; avoid two or more connectors If possible, avoid if altogether Use more OO approaches, such as polymorphism, or Monads Early exits: Using compact blocks and eliminating dead branches (i.e., ones that are impossible to reach) iteratively, we can greatly reduce the horizontal complexity of our program! Author: Gal Lalouche - Technion 2016 © 10 if ($ != null) { // bad // code } if ($ == null) // good return; //code

Minimal Control – Branches You can use code coverage tools to find impossible paths You can use Monads to replace if/else controls Before: After: Author: Gal Lalouche - Technion 2016 © 11 public Double getLatInNorthernHemisphere() { Location l = getLocation(); if (l == null || l.latitude < 0) { return null; } return l.latitude; } public Optional getLatInNorthernHemisphere() { return getLocation().map(l => l.latitude).filter(l => l >= 0); }

Minimal Control – Monads Avoid loops Almost all looping constructs can be achieved using lambdas Stream’s API is actually very thin compared to other languages, but you can wrap it to add missing functionality: e.g., zip, take, fold, mkString Avoid nesting Can usually be replaced with composing higher order functions A Fluent API is a great help here… Do not use null except when explicitly required by legacy APIs When returning a collection, an empty collection is better than null Collections.emptySet(), Collections.emptyList() Optional is far better and safer than a null able value Question to consider: is it better to throw an exception or return an Optional ? What’s common should be easy, and what’s uncommon should be possible Author: Gal Lalouche - Technion 2016 © 12

Minimal Control – Exceptions Fail as early as possible on bad input Avoid explicitly failing if possible, e.g., checked exceptions But do not “fail silently”! Do not use exceptions as a control mechanism e.g., try/catch instead of if/else Use try-with-resource statements ( try in Java, using in C#) as an alternative to try/finally Do not use checked exceptions in a public API 99% of the time, the API client will want to crash on error The remaining 1% can be handled using try/catch anyway Prefer a Try monad. Author: Gal Lalouche - Technion 2016 © 13 try (BufferedReader br = new BufferedReader(new FileReader(path))) { return br.readLine(); }

Careful use of Screen Space K&R Style Eliminate unnecessary parenthesis/braces Yes, it’s okay to remove them if the statement is only one line In fact, you should strive to make it only a single statement Fluent API helps immensely Refactor code into helper methods Shortens the primary method But try to avoid short, single-use methods “Hand rule”: Width, Height You should be able to completely obscure a method by placing your hand on the screen. Know your standard library! Many common patterns are already implemented; there’s rarely a need to reinvent the wheel Know your IDE! IDEs have many refactoring features Don’t be afraid to learn the keyboard shortcuts Mastering what your IDE has to offer will make your life easier! Author: Gal Lalouche - Technion 2016 © 14

Extra Reading GNU parser case study Spartan programming Succinctness is power – talks about programming languages, but it applies naturally to DSLs as well Succinctness is power programming/ programming/ Eclipse plugin Writing code that is easy to delete Author: Gal Lalouche - Technion 2016 © 15