A Moderately Directed Rant.  It’s very likely that you’ve been writing totally incorrect code without realizing it  Once you do realize it, it’s usually.

Slides:



Advertisements
Similar presentations
Chapter 5 Errors Bjarne Stroustrup
Advertisements

Writing Modern C++ Marc Grégoire Software Architect April 3 rd 2012.
S3 Useful Expressions.
Authority 2. HW 8: AGAIN HW 8 I wanted to bring up a couple of issues from grading HW 8. Even people who got problem #1 exactly right didn’t think about.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
Error Handling with Exceptions Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established.
Monday, Mar 24, 2003Kate Gregory with material from Deitel and Deitel Week 11 Exceptions.
The Pocket Protectors of Algebra
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.
. Plab – Tirgul 10 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
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.
Plab – Tirgul 8 Exceptions. Error handling in C Up to now we handled our errors in the “C way”: assert return codes global error variable ( errno and.
Pointers and Dynamic Variables. Objectives on completion of this topic, students should be able to: Correctly allocate data dynamically * Use the new.
Microprocessors Frame Pointers and the use of the –fomit-frame-pointer switch Feb 25th, 2002.
CSC 160 Computer Programming for Non-Majors Lecture #7: Variables Revisited Prof. Adam M. Wittenstein
Week 14 - Monday.  What did we talk about last time?  Image manipulation  Inheritance.
ICAPRG301A Week 4Buggy Programming ICAPRG301A Apply introductory programming techniques Program Bugs US Navy Admiral Grace Hopper is often credited with.
Chapter 5 Being a Web App. Very few servlet or JSP stands alone Many times in our application, different servlets or JSPs need to share information 
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
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?
During Circle Work One Person speaks at a time Right to Pass No Put-downs.
CSE 332: C++ memory management idioms C++ Memory Management Idioms Idioms are reusable design techniques in a language –We’ll look at 4 important ones.
CSSE501 Object-Oriented Development. Chapter 12: Implications of Substitution  In this chapter we will investigate some of the implications of the principle.
Breaking up is Hard to Do Advice on how to end a relationship.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Exceptions Handling Exceptionally Sticky Problems.
Storage Management. The stack and the heap Dynamic storage allocation refers to allocating space for variables at run time Most modern languages support.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
Optimistic Design 1. Guarded Methods Do something based on the fact that one or more objects have particular states  Make a set of purchases assuming.
MA 1128: Lecture 17 – 6/17/15 Adding Radicals Radical Equations.
C++ Memory Overview 4 major memory segments Key differences from Java
1 Dynamic Memory Allocation –The need –malloc/free –Memory Leaks –Dangling Pointers and Garbage Collection Today’s Material.
Debugging and Profiling With some help from Software Carpentry resources.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
Word problems DON’T PANIC! Some students believe they can’t do word problem solving in math. Don’t panic. It helps to read the question more than once.
1 CS161 Introduction to Computer Science Topic #9.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Week 14 - Monday.  What did we talk about last time?  Inheritance.
Conditional Statements.  Quiz  Hand in your jQuery exercises from last lecture  They don't have to be 100% perfect to get full credit  They do have.
Love it or Leave it? Job Interview Assignment Instructions: This class is all about MONEY right? Well, in order to manage money you have to have some money!
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 10 – C: the heap and manual memory management.
CSE 143 Lecture 13 Recursive Backtracking slides created by Ethan Apter
ARM-7 Assembly: Example Programs 1 CSE 2312 Computer Organization and Assembly Language Programming Vassilis Athitsos University of Texas at Arlington.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
Binary & Normalization What is Normalization? We discussed this the other day (special review session slides, near the end) Can someone tell us.
CHAPTER 18 C – C++ Section 1: Exceptions. Error Handling with Exceptions Forces you to defend yourself Separates error handling code from the source.
Introduction to Exceptions in Java CS201, SW Development Methods.
Division Brought to you by powerpointpros.com. Lesson Menu Click on the links below to start with a specific topic. What is Division? Using Division Practice.
OOP Tirgul 7. What We’ll Be Seeing Today  Packages  Exceptions  Ex4 2.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
CSE 374 Programming Concepts & Tools
Storage Management.
Week 14 - Wednesday CS 121.
Pointers and Dynamic Variables
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Exceptions 10-Nov-18.
Lesson 2: Building Blocks of Programming
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Overview of Memory Layout in C++
Exceptions 2 CMSC 202.
Coding Concepts (Basics)
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Exceptions 19-Feb-19.
Exceptions 7-Apr-19.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exceptions 10-May-19.
Exceptions 5-Jul-19.
Presentation transcript:

A Moderately Directed Rant

 It’s very likely that you’ve been writing totally incorrect code without realizing it  Once you do realize it, it’s usually not too hard to fix the problem, depending on the language  This is information that isn’t all that widely known, for whatever reason  You can use it to show off at interviews!  You can use it to start arguments about which programming language is the best!

 We need to define a couple basic things at the beginning so everybody’s on the same page  It’ll be quick, I promise  Garbage collection is a method of managing dynamic (heap-allocated) memory  It’s non-deterministic, and there is usually no guarantee that memory is cleaned up at all  Most modern languages use garbage collection

 A resource is anything you need to return to the system once you’re done using it  File handles, dynamic memory, locks, etc.  Exception safety means that you can throw an exception in the middle of your function without bad things happening  There’s a complicated formal definition with degrees of exception safety but this is good enough for our purposes

 Let’s look at some C code so we can figure out what this talk is even about void example() { lock(&g_mutex); int* my_int_pointer = (int*)malloc(sizeof(int)); do_something_with(my_int_pointer); free(my_int_pointer); unlock(&g_mutex); }  This is fairly reasonable, safe C code. It executes deterministically and everyone is happy

 Let’s see that exact same code, but now we’ll pretend that it was compiled as C++ void example() { lock(&g_mutex); int* my_int_pointer = (int*)malloc(sizeof(int)); do_something_with(my_int_pointer); free(my_int_pointer); unlock(&g_mutex); }  Catastrophe! This is going to compile and run without warnings, but be completely and totally unsafe!  Why? Exceptions!

 Yes, it does suck! It’s such a problem that people were motivated to go try to solve it  Bjarne Stroustrup (C++ language creator) came up with a solution which he named Resource Acquisition Is Initialization (RAII)  Incidentally, in addition to providing exception safety, RAII made C++ way easier to use  Let’s look at a correct C++ version of our code example, using RAII

void example() { Lock my_lock(&g_mutex); auto_ptr my_int_pointer(new int()); do_something_with(my_int_pointer); }  Thanks to RAII this example is exception safe, and we don’t have to worry about cleanup.  auto_ptr is part of the C++ standard library, but we’ve just made up Lock  Let’s look at the code for our made-up Lock class so we can see how RAII actually works

class Lock { private: mutex* m_pMutex; public: Lock(mutex* pMutex) : m_pMutex(pMutex) { lock(m_pMutex); } ~Lock() { unlock(m_pMutex); } };  In C++ a stack-allocated object’s destructor is always called once it goes out of scope, whether due to a function returning, due to normal code execution, or due to stack unwinding caused by a thrown exception

 That’s understandable. We are (for better or worse) a Java school, so let’s see if we can’t make RAII work in Java  Immediately we run into some problems  Java doesn’t have destructors  Java doesn’t have stack allocation for objects  So RAII won’t work with Java, then. What else have we got?  For dynamic memory we have garbage collection, but that’s a special case of the problem that doesn’t really need (or provide) determinism  The best we can do is the Dispose pattern

void example() { Integer myInteger = new Integer(0); Lock lock = new Lock(g_mutex); try { doSomethingWith(myInteger); } finally { lock.dispose(); }  While rewriting this every time gives you exception safety, it’s really easy to forget it  If you forget to do this, your program will still compile and run with no warnings, despite being wrong. Awesome!  This is more verbose than even the C example, yet is the minimum amount of code required for Java

void example() { File myFile = new File(filename); try { DBConnection dbConn = new DBConnection(credentials); try { Lock myLock = new Lock(g_mutex); try { doSomething(myFile, dbConn); } finally { myLock.dispose(); } } finally { dbConn.dispose(); } } finally { myFile.dispose(); }  This is again the minimum code required to be correct

void example() { File myFile(filename); DBConnection dbConn(credentials); Lock myLock(&g_mutex); doSomething(myFile, dbConn); }

void example() { scope myFile = new File(filename); scope dbConn = new DBConnection(credentials); scope myLock = new Lock(g_mutex); doSomething(myFile, dbConn); }

“You can take my deterministic resource management when my cold dead hand goes out of scope.” -- Anon

 By choice. You can have deterministic resource management alongside garbage collection, but the Java guys specifically chose not to  The D programming language supports RAII and has a garbage collector, so it’s definitely possible  Java, C#, Python, Ruby all screw this up to varying degrees ▪ The latter three have some syntactic sugar for resource management, but the onus is still on you to remember to use it ▪ Java 7 catches up with C# and adds the same syntactic sugar, but still doesn’t solve the problem  Perl, PHP, C++ and D all get it right to varying degrees ▪ If PHP gets something right before your language does, you should reassess your life goals

 My (unpopular) answer? Use C++ and Perl/PHP for everything until the D ecosystem matures a bit, then switch over to D entirely  C++ has its own set of problems, but it’s my opinion that they’re exaggerated and the benefits far outweigh them  If you’re stuck using a broken language like Java, I really don’t know what to tell you  I guess you could cry a little bit, but I don’t think it would solve the problem  Learn the Dispose pattern, always remember to use it

 I wish I had more helpful advice for Java, C#, Python, Ruby users, but this is the unfortunate state we find ourselves in  If you want more information about anything mentioned:  The D Programming Language by Andrei Alexandrescu is an excellent D introduction  If you want to learn how to code modern C++, you should read Effective C++ by Scott Meyers  The Boost website has good information about exception safety and reference-counted smart pointers, which I didn’t really talk about (Scott Meyers does in Effective C++)  Google knows all  Questions?