17-Jun-15 Which is better?. 2 Assume s1 and s2 are Strings: A.if (s1 == s2) {... } B.if (s1.equals(s2)) {... } ?

Slides:



Advertisements
Similar presentations
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Advertisements

CIT 590 Intro to Programming Java lecture 3. Hashmaps The equivalent of python dictionaries. With both ArrayLists and Hashmaps, the syntax only allows.
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
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.
Access to Names Namespaces, Scopes, Access privileges.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
16-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
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.
18-Jun-15 Arrays. 2 A problem with simple variables One variable holds one value The value may change over time, but at any given time, a variable holds.
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.
19-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
26-Jun-15 Methods. About methods A method is a named group of declarations and statements If a method is in the same class, you execute those declarations.
28-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
29-Jun-15 Recursion. 2 Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example:
30-Jun-15 Profiling. Optimization Optimization is the process of making a program as fast (or as small) as possible Here’s what the experts say about.
Which is better?. Assume s1 and s2 are Strings: A.if (s1 == s2) {... } B.if (s1.equals(s2)) {... }
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
Slides by Vinod Rathnam with material from Alex Mariakakis Kellen Donohue, David Mailhot, and Hal Perkins Midterm Review.
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
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?
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Best Practices. Contents Bad Practices Good Practices.
Character Arrays Based on the original work by Dr. Roger deBry Version 1.0.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
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.
24-Dec-15 Class Structure. 2 Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance.
Static?. Static Not dynamic class Widget { static int s; int d; // dynamic // or instance // variable }
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
27-Jan-16 Analysis of Algorithms. 2 Time and space To analyze an algorithm means: developing a formula for predicting how fast an algorithm is, based.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Building Java Programs Chapter 15 Lecture 15-2: testing ArrayIntList; pre/post conditions and exceptions reading:
BASICS OF CODE DESIGN.  Modular  Reusable  Easy to Read  Maintainable  Testable  Easy to Change  Easy to Understand THE GOAL.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Introduction to Exceptions in Java CS201, SW Development Methods.
Slides by Alex Mariakakis Section 5: Midterm Review.
Class Structure 15-Jun-18.
Some Eclipse shortcuts
Introduction to Computer Science / Procedural – 67130
Namespaces, Scopes, Access privileges
Recursion 12-Nov-18.
Class Structure 16-Nov-18.
Class Structure 28-Nov-18.
slides created by Ethan Apter
Recursion 2-Dec-18.
Recursion 2-Dec-18.
Which is better? 4-Dec-18.
Class Structure 7-Dec-18.
Recursion 29-Dec-18.
Class Structure 2-Jan-19.
slides created by Ethan Apter
Namespaces, Scopes, Access privileges
Exceptions 19-Feb-19.
Class Structure 25-Feb-19.
Exceptions 7-Apr-19.
Recursion 23-Apr-19.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exceptions 10-May-19.
Which is better? 15-May-19.
LCC 6310 Computation as an Expressive Medium
Which is better? 28-May-19.
Exceptions 5-Jul-19.
Classes and Methods 15-Aug-19.
Presentation transcript:

17-Jun-15 Which is better?

2 Assume s1 and s2 are Strings: A.if (s1 == s2) {... } B.if (s1.equals(s2)) {... } ?

3 Answer: B s1 == s2 tests whether s1 and s2 reference the same string; s1.equals(s2) tests whether they reference equal strings String s1 = "ABC"; String s2 = s1; String s3 = "ABC"; String s4 = "AB" + "C" All these strings are equal; but s4 is in a different memory location than the others, so the == test yields false

4 Which is better? Assume s1 is a String : A.if (s1.equals("OK")) {... } B.if ("OK".equals(s1)) {... } ?

5 Answer: B s1.equals("OK") sends a message to s1 asking if it is equal to "OK" "OK".equals(s1) sends a message to "OK" asking if it is equal to s1 This is legal, because "OK" is a String If s1 is null, then: s1.equals("OK") gives a NullPointerException "OK".equals(s1) gives false (Of course, in some circumstances you might prefer to get a NullPointerException )

6 Which is best? Assume int numbers[ ] = new int[100]; A.for (int i = 0; i < 100; i++) numbers[i] = i; B.for (int i = 0; i <= 99; i++) numbers[i] = i; C.for (int i = 0; i < ARRAY_SIZE; i++) numbers[i] = i; D.for (int i = 0; i < numbers.length; i++) numbers[i] = i; ?

7 Answer: D D is best: for (int i = 0; i < numbers.length; i++) numbers.length changes automatically if array size is changed C is OK: for (int i = 0; i < ARRAY_SIZE; i++) Changing ARRAY_SIZE will fix this loop if array size is changed B is poor: for (int i = 0; i < 100; i++) Uses a “magic number” Must track down and change each occurrence if array size is changed A is worst: for (int i = 0; i <= 99; i++) This has all the same problems as B B is more traditional and therefore less “surprising” The array size is 100, not 99, so it’s more obvious where the number came from You have to do some arithmetic to get 99 If you change the array size, a search for 100 won’t find the loop that uses 99

8 Which is better? Assume finished is a boolean variable: A.if (finished == true) {...} B.if (finished) {...} ?

9 Answer: B finished == true is redundant: If finished is true, then finished==true will be true If finished is false, then finished==true will be false The extra words don’t gain you anything finished==true might seem more readable to a beginner, but you quickly learn to read the shorter form Brevity in programming, as in writing, is a virtue You can avoid the possible mistake of saying if (finished = true) {... }

10 Which is better? Assume foo, bar, and larger are integers A.if (foo > bar) larger = foo; else larger = bar; B.larger = foo > bar ? foo : bar; ?

11 Answer: neither For each of these, you have to look at the code carefully to make sure it is correct larger = Math.max(foo, bar); is easier to read and more obviously correct

12 Which is better? A.String s = "Hello"; B.String s = new String("Hello"); ?

13 Answer: A "Hello" is special syntax to implicitly construct a string String s = new String("Hello"); actually constructs two strings: "Hello" constructs the first string, then it is given as a parameter to an explicit constructor, which constructs the second string

14 Which is better? Suppose p is a JPanel with a BorderLayout and okButton is a JButton : A.p.add(okButton, BorderLayout.NORTH); B.p.add(okButton, "North"); Note: BorderLayout.NORTH is a String constant whose value is "North" ?

15 Answer: A p.add(okButton, BorderLayout.NORTH); is strongly recommended over the shorter form p.add(okButton, "North") -- but why? Answer: The former gives better error detection If you type p.add(okButton, "north"), there is no error, but it doesn’t do what you want If you type p.add(okButton, BorderLayout.North) you will get a syntax error, because BorderLayout has no such variable as North

16 Which is best? Suppose n is an int and s is a String : A.s = Integer.toString(n); B.s = String.valueOf(n); C.s = new Integer(n).toString(); D.s = n + ""; ?

17 Answer: D I prefer D ( s = n + ""; ) because: It’s a common idiom, therefore easily recognized It’s short It works for any type

18 Which is best? Assume n is an integer: A.if (n < 0) n = 0; B.if (n < 0) n = 0; C.if (n < 0) { n = 0; } ?

19 Answer: C If, later on, you want to add a statement, it’s easy to make this mistake with B: if (n < 0) System.out.println("n was " + n); n = 0; You won’t make this mistake with A or C With C (using braces), you don’t have to change anything that’s already there However, A (all on one line) is often convenient

20 Which is better? Assume n is an integer: A.int factorial = 1; for (int i = 2; i < n; i++) { factorial *= n; } B.int factorial = 1; int i; for (i = 2; i < n; i++) { factorial *= n; } ?

21 Answer: A In most cases, you don’t care about the index of a for loop outside the loop You typically give it an initial value in the loop You typically already have its final value in some variable or by some simple computation If you don’t need a variable, you shouldn’t have that variable It doesn’t help anything, and it might get in the way

22 Which is better? A.int search(int[] array, int target) { for (int i = 0; i < array.length; i++) { if (array[i] == target) return i; } return -1; } B.int search(int[] array, int target) throws NotFoundException() { for (int i = 0; i < array.length; i++) { if (array[i] == target) return i; } return new NotFoundException(); } ?

23 Answer: A Exceptions should be used for exceptional cases, not for normal program control In almost all cases, not finding something in an array search is one of the expected outcomes Of course, there can be exceptions

24 Which is better? A.private void combinations(int n, int t) throws InvalidArgumentException { if (t n) { throw new InvalidArgumentException();... B.private void combinations(int n, int t) { assert t >= 0 && t <= n;... ?

25 Answer: B The method is marked private, so you (the person writing this class) will be the only one using this method If you call it incorrectly, it’s most likely a bug, not just an unexpected external event, and should be fixed, not tested for Besides, using an assert statement is a lot less work

26 Which is better? A.class Line { public Point start; public Point end; public double length;... } B.class Line { public Point start; public Point end; public int length() {...};... } ?

27 Answer: B Two main reasons: The DRY principle says: Don’t repeat yourself The length variable is a subtle kind of repetition; its value is determined by the start and end points Whenever you have the same information represented in two places, you have the extra requirement to keep them consistent The length variable makes the object vulnerable to inconsistent changes If some external agency changed only the start or the end point, the length variable would become incorrect The length method would continue to give correct results If efficiency is a critical issue, use setters and getters

28 Which is better? You need to write a class which splits input lines into fields: A.class Split { public Split(InputStreamReader reader) // constructor public void readNextLine() throws IOException {...} public int numFields() {...} public String getField(int fieldNumber) {...} } B.class Split { public Split(String line) {...} //constructor public int numFields() {...} public String getField() {...} } ?

29 Answer: B The second Split class just splits lines; it isn’t concerned with where the lines come from The first version can only split lines that come from an input stream, and is therefore less versatile

30 Conclusions There are various ways to do things One way may be better than another because: It’s easier to read and understand It’s more familiar—the way things are usually done It’s less error prone, or provides better error detection It’s more efficient This is a good reason when the savings are dramatic enough to be noticeable

31 The End “More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason -- including blind stupidity.” -- W.A. Wulf “We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.” -- Donald Knuth