CAB201 – Programming Principles Study Notes

CAB201 – Programming Principles

TEQSA Provider Information

  • TEQSA Provider ID: PRV12079

  • CRICOS No: 00213J

Acknowledgment of Traditional Owners

  • QUT acknowledges the Turrbal and Yugara as the First Nations owners of the lands where QUT now stands.

  • Respect is paid to the Elders, lores, customs, and creation spirits.

  • Recognition of the role of Aboriginal and Torres Strait Islander people in the QUT community.

Introduction to Object-Oriented Programming (OOP)

  • Definition: Object-oriented programming is a software development paradigm in which data is packaged with the operations that execute on it.

  • Contrast: Traditional programming processes separate procedures and data, even if some procedures operate only on certain types of data.

  • Object Concept: The combined package is known as an object; the data are referred to as fields and the operations as methods.

  • Industry Standard: OOP has been the industry-standard paradigm for decades due to its ability to scale effectively compared to traditional approaches.

Four Principles of OOP

  1. Abstraction: Complex details can be hidden within an object, presenting a simplified external interface.

  2. Encapsulation: The internal workings of an object are shielded by allowing it to be used only through its external interface.

  3. Inheritance: New objects can extend the capabilities of existing objects while remaining useable as the original (parent) objects.

  4. Polymorphism: Objects can interact in different ways when identical operations are performed on them.

Defining a Class

Classes
  • Classes are fundamental to OOP, enabling the creation of custom object types.

  • In C#, all code and fields are part of a class (or struct).

  • Classes support various programming paradigms.

What is a Class?
  • Definition: Classes act as templates for creating objects, specifying essential details that apply to all members and defining variable attributes.

  • Metaphor: Classes are like cookie cutters; objects are the cookies made with those cutters.

  • They encapsulate both data and the operations performed on that data, and they can serve as custom types (though not all classes are custom).

Grouping Related Data
  • Scenario: Storing student information with names, IDs, and GPA values.

  • Without classes, arrays of different types (e.g., string for names, int for IDs, float for GPA) can lead to complicated, out-of-sync data.

  • Instead, create a single array of student objects.

class Student {
   public int ID;
   public string Name;
   public float GPA;
}
Student[] students = new Student[10];
Instantiating a Class
  • Objects are instances of classes.

  • Instantiation: Objects are created using the new keyword:

  Classname variablename = new Classname();
  // Example: Student student = new Student();
  • In this example, Student is the class and student is the object (instance of Student).

Fields and Classes

Fields
  • Fields: Variables declared within classes, holding data relevant to that class (can be primitives or objects).

  • Accessing an object's field utilizes the . operator:

  student.ID = 12345678;
  • Fields are also termed instance variables due to their specificity to the class instance.

  • Unlike JavaScript or Python, fields must be defined in the class; arbitrary storage is not allowed.

Methods

Methods in C#
  • Methods in C# are akin to functions in other programming languages.

  • Methods may also accept parameters, execute instructions, and optionally return a value. Example:

double HarmonicMean(double a, double b) {
   double mean = 2.0 * a * b / (a + b);
   return mean;
}
  • This includes:

    • Return type

    • Method name

    • Parameters

    • Method body

Void Methods
  • A void method specifies void as its return type, indicating it does not return a value.

  • Not necessitated to include a return statement, as it exits reaching the end of the method.

  • Example:

public void PrintGreeting() {
   Console.WriteLine("Hello World");
}
Invoking Methods
  • Methods are invoked on objects of the class in which the method is defined.

  • The exception: static methods exist at the class level and do not require an instance to be called.

  • Accessing fields from methods:

class Coordinate {
   int x, y;
   public void PrintLocation() {
       Console.WriteLine($"The coordinate is {x},{y}");
   }
}
coordinate.PrintLocation();
Method Parameters
  • Parameters can be prefixed with keywords like in, ref, or out to define how they are passed (by value/reference).

  • in parameters are read-only for input.

  • ref allows both input and output, altering the original variable value.

  • out is purely output, omitted upon entry, requiring output assignment.

Handling Parsing with TryParse
  • int.TryParse(): Safely converts a string to an int, providing an output parameter for results.

  • If parsing fails, it does not throw an exception but returns a successful parse boolean instead:

int result;
bool success = int.TryParse("123", out result);

Procedural Abstraction

  • Essential in computer science.

  • Identifies common tasks, isolating them into reusable procedures, reducing code length, potential bugs, and consolidating change control.

  • Well-designed procedures are self-documenting.

Constructors

Constructors
  • Special methods called to initialize object fields when an object is created.

  • No return type (you can use return; to exit early).

  • Absence of a constructor results in a default parameterless constructor being auto-generated. E.g.:

public Student(int id, string name, float gpa) {
   ID = id;
   Name = name;
   GPA = gpa;
}
  • Creating an instance now requires parameters, e.g.:

Student student = new Student(12345678, "Alice", 7.0f);

Creating Well-Designed Procedures

  • Naming: Use concise yet descriptive method names aligning with their purposes.

  • Single Responsibility: Each method should do one distinct thing, making refactoring easier and methods clearer.

Handling Abstraction Challenges

  • Sometimes method details matter to the caller, requiring thorough documentation.

  • Key questions about method interactions should be addressed in comments to mitigate ambiguity.

NULL Values

null
  • Indicates that an object reference points to no object. An uninitialized variable is considered null by default.

  • Calling methods or accessing fields on a null reference will result in runtime errors.

Nullable Types
  • C# introduces nullable types to safely reference objects. They are denoted by a ? after the type name:

int? nullableInt;
Student? myStudent;
  • Nullable values can be null, but operations should ensure null checks to avoid runtime exceptions.

Working with Null Operators
  • C# provides null operators to manage possibly null values, including:

    • Null coalesce: L ?? R returns L unless L is null, returning R instead.

    • Null coalescing assignment: L ??= R assigns R to L if L is null.

    • Null conditional access: ?. or ?[] safely accesses members, resulting in null if the base call is null.

Examples of Null Operators
string response = Console.ReadLine() ?? "";
Console.WriteLine("You entered a {0}-length string", response.Length);
Nullable Parameters
  • Methods can receive nullable parameters, denoting their optional nature.

  • Non-nullable parameters are assumed to remain non-null, and no checks are enforced by the compiler, although warnings may issue.

Overloading

Method Overloading
  • Permits multiple methods of the same name with different argument types/numbers:

public void Method(int a, int b);
public void Method(int a, float b);
  • The correct method resolves at compile time based on the static types of provided arguments.

Uses and Tips
  • Utilizes method overloading for variances of the same method with diverse argument types. However, redundant overloads can complicate maintenance.

  • Instead of default arguments, consider using optional arguments for more clarity.

Visibility

  • Class elements have access modifiers:

    • private: Internal to the class only.

    • public: Accessible from anywhere.

    • internal: Essentially synonymous with public in specific contexts.

The 'this' Keyword

  • this references members of the class/object the method utilizes, crucial for clear scope distinction.

XML Comments

  • C# allows XML comments for methods, providing usage details that appear in IDEs and enhancing readability:

/// <summary>
/// Returns the current location of this actor
/// </summary>
public void GetLocation(out int x, out int y) { ... }

Pre- and Post-Conditions

  • Formal method documentation structures:

    • Pre-conditions: Must hold true before invoking the function.

    • Post-conditions: Must hold true after the function execution.

/// <summary>
/// Sets actor's location
/// Pre: x and y non-negative
/// Post: Actor's location set to (x,y)
/// </summary>

Properties

Issues with Public Fields
  • Public fields expose underlying representations causing design fragility and invalid value exposure.

  • Non-static fields should typically be private to limit access and potential misuse.

Property Usage
  • Properties have field-like semantics while preserving getter/setter functionality, effectively limiting operations. They act as a replacement for traditional getter/setter methods.

Declaring Properties
class Customer {
   private string name;
   public string Name {
       get { return name; }
       set { name = value; }
   }
}
Getters and Setters
  • Getters provide read access and can return either direct field values or process data:

public int Count {
   get { return customers.Count; }
}
  • Setters control write access and can include validation conditions.

Auto-Implemented Properties
public string Address { get; set; }
  • This simplifies property declaration while automatically managing backing fields in the background.

Using Properties Over Fields
  • Properties allow alteration from simple to complex without breaking external code references.

Tips for Properties
  • Similar to methods, properties should maintain consistent semantics and minimize side effects.

Static Concept

Static Overview

The static keyword can define:

  • Static methods,

  • Static properties,

  • Static fields,

  • Static classes.

Static Methods and Properties
  • Static methods are invoked on the class, not requiring instances, suitable for shared functionalities.

Employee.PayAll(List<Employee> employees);
Static Fields
  • Static fields are shared across instances but caution is advised as they may cause global variable issues if not neatly contained.

Static Classes
  • Static classes cannot be instantiated, encompassing static members only, typically serving to group methods together.

Conclusions on Static Usage
  • Employ static methods and properties appropriately, avoid public static fields, and consolidate related methods under static classes for utility.

Thank You!