!!! Global Variables!!! are EVIL SSimply because you just write a school boy/gal?

Slides:



Advertisements
Similar presentations
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Advertisements

Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Concurrency 101 Shared state. Part 1: General Concepts 2.
Road Map Introduction to object oriented programming. Classes
Assignment – no class Wednesday All: watch the Google Techtalk “Getting C++ Threads Right” by Hans Boehm at the following link in place of Wednesday’s.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
1 Sharing Objects – Ch. 3 Visibility What is the source of the issue? Volatile Dekker’s algorithm Publication and Escape Thread Confinement Immutability.
29-Jun-15 Java Concurrency. Definitions Parallel processes—two or more Threads are running simultaneously, on different cores (processors), in the same.
1 Further OO Concepts II – Java Program at run-time Overview l Steps in Executing a Java Program. l Loading l Linking l Initialization l Creation of Objects.
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
Abstract Data Types and Encapsulation Concepts
Storage & Linkage: Effects on Scope Rudra Dutta CSC Spring 2007, Section 001.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Chapter 7 Designing Classes. Class Design When we are developing a piece of software, we want to design the software We don’t want to just sit down and.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
1 Thread II Slides courtesy of Dr. Nilanjan Banerjee.
Object Oriented Programming Philosophy. Part 1 -- Basic Understanding & Encapsulation.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Nachos Phase 1 Code -Hints and Comments
Copyright 2001 Oxford Consulting, Ltd1 January Storage Classes, Scope and Linkage Overview Focus is on the structure of a C++ program with –Multiple.
Object Oriented Programming Elhanan Borenstein Lecture #4.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
50.003: Elements of Software Construction Week 8 Composing Thread-safe Objects.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Technical Module : Pointers #1 2000/01Scientific Computing in OOCourse code 3C59 Technical Module : Pointers In this module we will cover Pointers to primitives.
CPS120: Introduction to Computer Science Functions.
ICS 313: Programming Language Theory Chapter 13: Concurrency.
Sharing Objects  Synchronization  Atomicity  Specifying critical sections  Memory visibility  One thread’s modification seen by the other  Visibility.
Java Thread and Memory Model
SPL/2010 Synchronization 1. SPL/2010 Overview ● synchronization mechanisms in modern RTEs ● concurrency issues ● places where synchronization is needed.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
The Object-Oriented Thought Process Chapter 03
Constructors and Destructors
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Java Primer 1: Types, Classes and Operators
Stack Data Structure, Reverse Polish Notation, Homework 7
Threads and Memory Models Hal Perkins Autumn 2011
Packages and Interfaces
Threads and Memory Models Hal Perkins Autumn 2009
Constructors and Destructors
Dr. Mustafa Cem Kasapbaşı
Java Concurrency 17-Jan-19.
Applying OO Concepts Using Java
Java Programming Language
Java Concurrency.
Java Concurrency.
Java Concurrency 29-May-19.
ENERGY 211 / CME 211 Lecture 17 October 29, 2008.
The Three Attributes of an Identifier
Review for Midterm 3.
Threads and concurrency / Safety
Presentation transcript:

!!! Global Variables!!! are EVIL

SSimply because you just write a school boy/gal?

 Non-locality -- Source code is easiest to understand when the scope of its individual elements are limited. Global variables can be read or modified by any part of the program, making it difficult to remember or reason about every possible use.  No Access Control or Constraint Checking -- A global variable can be get or set by any part of the program, and any rules regarding its use can be easily broken or forgotten. (In other words, get/set accessors are generally preferable over direct data access, and this is even more so for global data.) By extension, the lack of access control greatly hinders achieving security in situations where you may wish to run untrusted code (such as working with 3rd party plugins).

 Implicit coupling -- A program with many global variables often has tight couplings between some of those variables, and couplings between variables and functions. Grouping coupled items into cohesive units usually leads to better programs.  Concurrency issues -- if globals can be accessed by multiple threads of execution, synchronization is necessary (and too-often neglected). When dynamically linking modules with globals, the composed system might not be thread-safe even if the two independent modules tested in dozens of different contexts were safe.  Namespace pollution -- Global names are available everywhere. You may unknowingly end up using a global when you think you are using a local (by misspelling or forgetting to declare the local) or vice versa. Also, if you ever have to link together modules that have the same global variable names, if you are lucky, you will get linking errors. If you are unlucky, the linker will simply treat all uses of the same name as the same object.

 Memory allocation issues -- Some environments have memory allocation schemes that make allocation of globals tricky. This is especially true in languages where "constructors" have side-effects other than allocation (because, in that case, you can express unsafe situations where two globals mutually depend on one another). Also, when dynamically linking modules, it can be unclear whether different libraries have their own instances of globals or whether the globals are shared.  Testing and Confinement - source that utilizes globals is somewhat more difficult to test because one cannot readily set up a 'clean' environment between runs. More generally, source that utilizes global services of any sort (e.g. reading and writing files or databases) that aren't explicitly provided to that source is difficult to test for the same reason. For communicating systems, the ability to test system invariants may require running more than one 'copy' of a system simultaneously, which is greatly hindered by any use of shared services - including global memory - that are not provided for sharing as part of the test.

class X { ……. }; Main() { X ux = new X(); …….. b.dosomthing(ux, ….) ; // we need object b to do something // but it needs cooperation of X // and ux is unique ; } Class B { void dosomething(X ux,..) { …… C.domyjob(ux, …); // ok we need c to do something // and it needs the cooperation of ux } In order to let other classes being able to access the unique object, we pass ux all around

Class GLOBAL { static X ux ; Static void init() { ux = new X(); } Somewhere in main() or in any class GLOBAL.ux.dosomething(); NOTE: you do not new an object from a control class Class scope Make the variable to be static so that it has only one instance which comes with class not object

 You assign an object to a global variable  You call init() to create that object when your application begins  If the object requires intensive resource and your application never run to the cases which use the object – this is not good.  We always want an object to be created only when they are needed  Bad example: You have many image objects and you load them all in the beginning

 No public constructor to allow any program to “new” the object  The new object is created in the getInstance()  The variable inside the singleton is declared as static

 suppose you have a singleton object called class wife { public wife* getInstance(); void getMoney(); }  to call singleton methods  in C++  wife.getInstance()->getMoney()  in Java or C#  wife.getInstance().getMoney()

 Sometimes. In a multithreading applications, a singleton will be accessed by more than one thread.  The synchronization problem arises 

At its simplest level, a block of code that is marked as synchronized in Java tells the JVM : "only let one thread in here at a time"

 Every Java object created, including every Class loaded, has an associated lock or monitor. Putting code inside a synchronized block makes the compiler append instructions to acquire the lock on the specified object before executing the code, and release it afterwards (either because the code finishes normally or abnormally).

 It's probably fair to say that on the whole, the volatile keyword in Java is poorly documented, poorly understood, and rarely used. To make matters worse, its formal definition actually changed as of Java 5.  Essentially, volatile is used to indicate that a variable's value will be modified by different threadsthreads  Cited from tion_volatile.shtml Cited from tion_volatile.shtml

 Declaring a volatile Java variable means: The value of this variable will never be cached thread-locally: all reads and writes will go straight to "main memory"; Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.synchronized block

 final can be used to make sure that when you construct an object, another thread accessing that object doesn't see that object in a partially-constructed state, as could otherwise happen.  When the constructor exits, the values of final fields are guaranteed to be visible to other threads accessing the constructed object.

 One answer to this is "whenever you possibly can". Any field that you never expect to be changed (be that a primitive value, or a reference to an object, whether or not that particular object is itself immutable or not), should generally be declared final. Another way of looking at things is:  If your object is accessed by multiple threads, and you don't declare its fields final, then you must provide thread-safety by some other means.

 It's important to emphasise that storing a reference to an object in a final field only makes the reference immutable, not the actual object.  For examlple, if a list is declared as follows:  private final List myList = new ArrayList();  there's nothing to stop modifications to the list:  myList.add("Hello");  However, the following would not be possible:  myList = new ArrayList();  myList = someOtherList;

 The difference: I would not consider a singleton as a global variable unless the singleton exposed its internal variable through an accessor. Absent accessors, a singleton provides controlled access to the variable, greatly reducing the programming problems.  Cohesive Methods : One of the major arguments against global variables is that they defy the basic OO concept of cohesive methods. With a global variable all of the accesses and operations on the variable are scattered around the code. By pulling all of the methods into a single class or module, they can be evaluated and maintained as a unit.  Should I simply convert a global variable to Singleton to resolve the evil? Converting to the SingletonPattern is common, but you may discover that it makes more sense for the data element to be a member of an existing singleton, or maybe even an instance variable.SingletonPattern