You are on page 1of 57

ISM 6225

Distributed
Information Systems
LECTURE 2 – GIT, OBJECT -ORIENTED PROGRAMMING
Contents
• Object-oriented programming – basic concepts
◦ Classes and objects
◦ Access and access permissions
◦ Constructors
◦ Declaration, instantiation, assignment
◦ Instance methods, static methods
◦ Passing by value and reference
◦ Inheritance
◦ Properties – getters, setters

• Content versioning system – Git


• List data structure as an example of using OOP

2
Approach
• We will proceed mostly using simple, intuitive examples
◦ Build up slowly as we motivate the need for various OOP concepts

• Early examples will not necessarily be the best way to do things


◦ But should be easy to comprehend

3
Object-oriented programming
• Motivation
◦ Computers natively handle primitive data types
◦ But developers and end users typically need to work with more expressive
data types
◦ E.g. people, organizations, courses, programs etc

• Object-oriented programming allows developers to write programs


with data types that closely represent the entities they deal with
◦ http://qr.ae/TUNMPk
◦ https://en.wikipedia.org/wiki/Object-oriented_programming

4
Motivation example
• Primitive programming
◦ string firstNameUser1 = "John";
◦ string lastNameUser1 = "Doe";
◦ string nameCourse1 = "ISM 6225";
◦ registerCourse(nameCourse1, firstNameUser1);

• Object-oriented programming
◦ User User1 = new User("John");
◦ Course Course1 = new Course("ISM 6225");
◦ Course1.Register(User1);

5
Motivation example (contd.)
• Without object oriented programming

◦ Variables associated with the same entity are not naturally associated in the
program
◦ E.g. first name and last name strings

◦ Business operations are not naturally associated with the entities they work
with
◦ E.g. course registration

6
Object-oriented programming basics
• Languages which support object-oriented programming (OOP) allow
programmers to define classes
◦ Classes can have variables inside them
◦ These variables can themselves be classes
◦ These variables are typically called properties

/// <summary>
/// Define a class for people
/// </summary>
class Person
{
string firstName;
string lastName;
}

7
Classes
• Classes can also have methods
◦ These methods typically act on the class properties

class Person
{
string firstName;
string lastName;

string getName()
{
return firstName + " " + lastName;
}
}

8
Using classes
• Classes can be used in programs just like any other primitive type

Person Student = new Person {


firstName = "John",
lastName = "Doe"
};

• Uh oh

9
Access permissions
• In object-oriented programming
◦ Properties are associated with classes
◦ Appropriate that classes should have control over their properties
◦ Who can see and edit these properties
◦ I should not be able to change your first name

• Implemented through access permissions


◦ By default, properties can only be accessed within the class
◦ Hence, compilation errors in creating the student object
◦ Common permissions are
◦ public
◦ protected
◦ Private
◦ https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/accessibility-levels

10
Update class with access
permissions
class Person
{
public string firstName;
public string lastName;

public string getName()


{
return firstName + " " + lastName;
}
}

11
Using the class
namespace Project02_ObjectOrientedProgramming
{
class Program
{

static void Main(string[] args)


{
Person Student = new Person { firstName = "John", lastName = "Doe" };
}
}

/// <summary>
/// Define a class for people
/// </summary>
class Person
{
public string firstName;
public string lastName;

public string getName()


{
return firstName + " " + lastName;
}
}

12
Accessing the class properties
and methods
• How can we access the firstName, lastName properties and the
getName() method?
• The typical syntax used to access the properties of a class is the dot
notation
◦ <Class>.<Item>

• Say we want to use the getName() method to print the name of the
student
◦ We can use Student.getName()
◦ E.g.
◦ Debug.WriteLine(Student.getName());

13
Exercise
• Add a field to the Person class
◦ Type: string
◦ Name: Salutation

• Update the program to use the Salutation field


◦ Update getName() to use the Salutation field
◦ Update the Student object with the Salutation field
◦ Check that the output now includes the Salutation

14
Static methods and fields
• Most of the time, we work with instances of classes
◦ E.g. the Student instance of the Person class

• Instances are commonly called Objects


• But, there can also be a need for fields and methods that are
associated with the class, not instances, e.g.
◦ Common to all objects of the class
◦ Utility methods

• These are called static methods and fields


◦ https://code.tutsplus.com/tutorials/as3-101-quick-tip-when-to-use-static-
properties-and-methods--active-7832

15
Example of static property
• Say we limit the available salutations to “Mr”, “Ms”, “Other”
◦ All persons will have one of these salutations (or none)

• How do we implement this?


◦ Some kind of constant in the application?
◦ Property file in the application?

16
Example of static property
• One possibility is to define these as static properties of the Person
class
static void Main(string[] args)
{
Person Student = new Person { salutation = Person.salutationMr,
firstName = "John",
lastName = "Doe" };
}

class Person
{
public static string salutationMr = "Mr";
public string salutation;

}

• This keeps all features of the Person object within the class definition

17
Accessing static properties
• Static properties do not need an instance of the class
◦ They are therefore accessed using the class name
◦ Instead of the instance name
◦ E.g.
◦ Person.salutationMr

18
Constructors
• We created the Student object by directly accessing the properties of
the class
◦ Person Student = new Person { salutation = Person.salutationMr, firstName = "John", lastName = "Doe" };

• This is generally not good practice


◦ Direct access is unsafe
◦ Validations may be appropriate
◦ There could be rules to be imposed when creating an instance
◦ E.g. say, Last Name MUST be specified

19
Constructors (contd.)
• Therefore, object-oriented programming supports constructors
◦ Create a new instance of an object
◦ Automatically invoked by the language when a new instance is created

• Typically two types of constructors


◦ Default constructor
◦ Takes no arguments
◦ Most languages offer one even if not defined by developers
◦ Parametrized constructor
◦ Takes at least one argument
◦ More details: https://www.c-
sharpcorner.com/UploadFile/0c1bb2/constructors-and-its-types-in-C-Sharp/

20
Constructors (contd.)
class Person
{
public static string salutationMr = "Mr";
public static string salutationMs = "Ms";
public static string defaultlastName = "NLN";

public string firstName;


public string lastName;
public string salutation;

public Person()
{
firstName = "";
lastName = defaultlastName;
salutation = salutationMs;
}

public Person(string salutation, string fName, string lName)


{
salutation = salutation; // needs refinement
firstName = fName;
lastName = lName;
}


}

21
Constructors – features and usage
• Constructors have two special properties
◦ They have the same name as the class
◦ They do not have a return type
◦ Allows the language to identify the methods as constructor methods
• A class can have any number of constructors
◦ Most frameworks provide a large number of constructors
◦ Allows use of appropriate constructor depending upon information available at the time of object
creation
◦ Missing information filled in with default values
◦ E.g. MVC framework offers constructors to create URLs with
◦ Just the action name (constructor name, HTTP method etc filled by default)
◦ Full specification (allows defining action method, HTTP method, JavaScript parameters, styling
details etc)

• Constructors can only be used when creating a new object

22
Constructors – features and usage
• Usage
Person Student1 = new Person();
Person Student2 = new Person(Person.salutationMr, "John", "Doe");

• Our constructor needs refinement


• Check value of Student2.salutation
• null
• Why?

23
Constructors - this
• The problem is that within the constructor, the variable salutation can
refer to two objects
◦ The argument passed to the method
◦ The salutation field of the class

• Resolution
◦ Variables are typically resolved to the most local values
◦ Hence, salutation refers to the argument passed to the constructor
◦ To refer to the salutation field of the object
◦ Use this.salutation
◦ this.salutation = salutation;
◦ this is an OOP keyword in most languages
◦ Refers to the current object instance

24
Exercise
• Check out language default constructor
◦ Comment out all constructors
◦ Create a new Person object
Person Student1 = new Person();

◦ Use breakpoints to see the values of firstName, lastName and salutation

25
Creating objects - definitions
• Declaration
◦ Person Student;
◦ Creates storage space to refer to the object
◦ No object created yet

• Instantiation
◦ new Person();
◦ Creates the object
◦ But no access to it, cannot be used in the program

• Assignment
◦ Student = Student1;
◦ Variable refers to object

26
Typical usage
• Combine all three
◦ Person Student2 = new Person(Person.salutationMr,
"John", "Doe");
1. Declares variable Student2 as object of class Person
2. Instantiates a new Person object
3. Assigns the Person object to Student2 variable

27
Passing by value and reference
• One key difference in treatment of primitive variables and objects
• Motivation is to conserve resources
◦ Primitive variables are passed by value
◦ Objects are passed by reference

• Consider 2 examples

28
Passing by value and reference
PASSING BY VALUE PASSING BY REFERENCE
Person Student3 = new Person(Person.salutationMs, "Jane", "Doe");
int testVar1 = 3; Person Student4 = modifyArgumentperson(Student3);
int y = modifyArgument(testVar1);
Debug.WriteLine(Student3.lastName + ", " + Student4.lastName);
Debug.WriteLine(testVar1 + ", " + y);

static Person modifyArgumentperson(Person x)


static int modifyArgument(int x)
{ {
x = 6; x.lastName = "Dane";
return x; return x;
}
}

29
Passing by value and reference
• When passed by value
◦ A copy of the variable is created
◦ Changes to the variable within the called method do not change the value
in the calling method

• When passed by reference


◦ A reference to the variable is created
◦ The called method works on the same variable as the calling method
◦ Hence, changes to the variable within the called method directly impact the
variable in the calling method

30
Inheritance
• Also seen as specialization
• Many business objects share properties with more general objects
◦ But have special properties of their own

• E.g.
◦ All students are persons
◦ getName() is relevant to students just as well as any generic person
◦ But all students have student numbers, whereas a generic person does not need one
◦ All students have a major, but a generic person may not

• How to model this?

31
Inheritance
• We could create separate classes for Person and Student
◦ Will work
◦ But lose the relationship between Person and Student
◦ Also, will lead to method duplication
◦ Multiple implementations of getName()
◦ Can lead to lost updates
◦ E.g. if we decide to update getName(), we will need to remember all the different
implementations to update

• Inheritance allows us to model this relationship between Person and


Student
◦ Student is a type of Person
◦ Modeled as Student inherits from Person

32
Implementing inheritance
class Student : Person
{
public string studentNumber;

public Student()
{
studentNumber = "U1234";
firstName = "";
lastName = defaultlastName;
salutation = salutationMs;
}
}

33
Implementing inheritance
• The above works
◦ But has some limitations
◦ We have essentially repeated the constructor of the Person object
◦ What happens if that constructor evolves?
◦ We would like to make changes in just one place if something changes

• We can re-write the constructor using inheritance as


public Student() : base()
{
studentNumber = "U1234";
}

34
Updated Student class
class Student : Person
{
public string studentNumber;

public Student() : base()


{
studentNumber = "U1234";
}

public Student(string sNumber, string sal, string ftName, string ltName) : base(sal, ftName, ltName)
{
studentNumber = sNumber;
}

new public string getName()


{
return studentNumber + " " + base.getName();
}
}

35
Using the student class
• An inherited class is used just like the parent class
◦ And really, almost like a primitive type
◦ Of course, with the dotted notation and passing by reference

Student Student1 = new Student();


Debug.WriteLine(Student1.getName());

Student Student2 = new Student("U123X", "Ms.", "Jane", "Doe");


Debug.WriteLine(Student2.getName());

36
Final touches
• Thus far, we have worked directly with the class fields
◦ firstName, lastName etc

• This is not best practice


◦ You generally do not want programs to directly access your fields
◦ Validation before assignment
◦ Maintain consistent public interface, even if the internal representation changes
◦ May only want fields to be read (not set)
◦ Getter may involve some computation

• But also read this:


◦ https://stackoverflow.com/questions/1568091/why-use-getters-and-
setters-accessors

37
Using getters and setters
private string SSN;

public string getSSN()


{
return SSN;
}

public void setSSN(string value)


{
SSN = value;
}

• Person1.setSSN("123");

38
C# approach
• C# allows you to define and use properties using a friendly syntax
◦ Combines both worlds

• Since the typical getters and setters follow a very specific pattern
◦ Compiler can hide the complexity from developers
◦ Use the getter and setter methods
◦ But allow developers to access the properties directly

• public string SSN { get; set; }


• Person1.SSNProperty = "123";

39
Exercise
• Change all existing fields to properties
◦ Add the get and set methods

• May find useful when programming


◦ Creating properties is a very common task
◦ Useful for IDEs to simplify
◦ Visual Studio offers the prop shortcut to create a property
◦ Type “prop” on a new line
◦ Visual Studio creates a property template
◦ Use TAB to switch between type and name
◦ Use ENTER to complete

40
Example of using objects
• As an example of using objects, let us consider a Linked List
◦ Subject of assignment 2

• Motivations for considering a linked list in the assignment


◦ Introduces you to probably the most important data structure
◦ Gives you practice in creating and using objects
◦ Most selective employers are likely to test you on using Linked Lists

41
Some useful references
• Introduction
◦ Wikipedia: https://en.wikipedia.org/wiki/Linked_list
◦ CMU: https://www.cs.cmu.edu/~adamchik/15-
121/lectures/Linked%20Lists/linked%20lists.html

• C# implementation example
◦ http://adt-csharp.blogspot.com/2016/09/list-adt-linked-list-
implementation.html

42
Linked Lists
• Definition
◦ A linear collection of data nodes, where each node contains a value and a
reference to the next data node

• Importance
◦ Almost any data in a computer that is of arbitrarily varying length is stored
as a linked list, e.g.
◦ Files list
◦ Processes list
◦ Program stack

• Many specialized data structures are linked lists with constrained set
of operations
◦ E.g. stacks, queues

43
Stock portfolio as object
• Consider the stock portfolio of a client
◦ It has
◦ Client information
◦ Potentially, portfolio value for quick reference
◦ A list of stocks

Client Portfolio
Client information
Portfolio value
Stock List
Stock node Stock node Stock node
Head Stock Stock Stock Head

44
Using these objects
• When a client joins a firm
◦ Create a new portfolio object
◦ Constructor initializes
◦ Client information, portfolio value
◦ New Stock list object

• When a client makes a trade


◦ Buy operations insert a stock into the list, or
◦ Add to existing holdings of the same stock
◦ Sell operations reduce existing holdings
◦ If holdings are zero, can delete the stock from the list

• Note
◦ A more complete application can maintain a list of transactions for each stock
◦ To maintain trade history

45
Stock class
public class Stock
{
public string Symbol { get; set; }
public string Name { get; set; }
public decimal Holdings { get; set; }
public decimal CurrentPrice { get; set; }

// default constructor
public Stock()
{
Symbol = "NA"; Name = "Invalid"; Holdings = 0; CurrentPrice = -99;
}

// Constructor for initialization


public Stock(string symbol, string name, decimal holdings, decimal currentPrice)
{
Symbol = symbol; Name = name; Holdings = holdings; CurrentPrice = currentPrice;
}

// overridden ToString method to customize the return value


public override string ToString()
{
return Symbol + ", " + Name + ", " + Holdings + ", " + CurrentPrice;
}
}

46
StockNode class
public class StockNode
{
public Stock StockHolding;

public StockNode Next;

//constructor to initialize the variables


public StockNode(Stock stockHolding)
{
StockHolding = stockHolding;
Next = null;
}
}

47
StockList class
public class StockList
{
private StockNode head;

//Constructor for initialization


public StockList()
{
this.head = null;
}

/*
* param : NA
* summary : checks if the list is empty
* return : true if list is empty, false otherwise
* return type : bool
*/
public bool IsEmpty()
{
if (this.head == null)
{
return true;
}
return false;
}
}

48
Example StockList methods
/*
* param (Stock)stock : stock that is to be added
* summary : Add node at first position in list
* return : NA
* return type : NA
*/
public void AddFirst(Stock stock)
{
StockNode nodeToAdd = new StockNode(stock);
nodeToAdd.Next = head;
head = nodeToAdd;
}

49
Example StockList methods
/*
* param (Stock)stock : stock that is to be added
* summary : Add mode at last position of list
* return :
* return type :
*/
public void AddLast(Stock stock)
{
if (this.IsEmpty())
AddFirst(stock);
else
{
StockNode current = this.head;
while (current.Next != null)
current = current.Next;

StockNode nodeToAdd = new StockNode(stock);


current.Next = nodeToAdd;
}
}

50
Example StockList methods
/*
* param (Stock)stock : stock that is to be checked
* summary : checks if list contains stock passed as parameter
* return : Reference of node with matching stock
* return type : StockNode
*/
public StockNode Contains(Stock stock)
{
StockNode nodeReference = null;
if (this.IsEmpty())
return nodeReference;
else
{
StockNode current = this.head;
StockNode previous = this.head;
while (current.Next != null)
{
Stock currentStock = current.StockHolding;
if (currentStock.Equals(stock))
{
nodeReference = previous;
break;
}
previous = current;
current = current.Next;
}
}
return nodeReference;
}

51
Assignment 2
• The assignment asks you to write a few methods to develop familiarity
with Linked Lists and Object Oriented programming

• Requirement
◦ The group must use Github to collaborate
◦ Last exercise asks you to report on the number of lines contributed by each team member
◦ Companion site has a video that shows how to use Github
◦ Recommendation 1: Add your Github link to your EdvisionApp profile
◦ And resume
◦ Recommendation 2: Use Giithub for all your coding projects in the program
◦ And any other suitable use cases
◦ Build a demonstrable repository

52
Git
• All professional developers are expected to be comfortable using a
source control and collaboration system
◦ E.g. Perforce, Git
◦ Maintain code history
◦ Simplify sharing code with collaborators
◦ Think of it as a super-charged version of online documents

• We will enforce this in class going forward


• Strongly recommended that you use Git for as many course projects as
possible
◦ Build a demonstrable record of work
◦ Students from all top colleges do

53
Git
• Check out videos on companion site:
◦ http://www.ismlab.usf.edu/dis/

• Also Microsoft tutorial on using Github with Visual Studio


◦ https://docs.microsoft.com/en-us/vsts/repos/git/gitworkflow?view=vsts

• Useful blog post


◦ https://henrikwarne.com/2018/06/25/6-git-aha-moments/

54
Steps
• Create a Github account
• Follow Github getting started guide
◦ https://guides.github.com/activities/hello-world/ (Fall 2018)

• Initially you may work on just the master branch


◦ Each group member works on separate files to avoid conflicts
◦ But, once you develop comfort, challenge yourself to create and work with
branches
◦ Create and merge pull reguests

55
Exercise
• Create a Github account if not already done

• Connect it to Visual Studio

56
References
• Josh Hug, CS 61B slides, UC Berkeley, https://sp18.datastructur.es/

57

You might also like