0% found this document useful (0 votes)
2 views

03 - Encapsulation

The document discusses encapsulation in programming, emphasizing its role in wrapping code and data together to reduce complexity and enhance flexibility. It covers key concepts such as access modifiers, validation, and the differences between mutable and immutable objects. Additionally, it provides examples of implementing encapsulation through class design and data validation techniques.

Uploaded by

KL M
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

03 - Encapsulation

The document discusses encapsulation in programming, emphasizing its role in wrapping code and data together to reduce complexity and enhance flexibility. It covers key concepts such as access modifiers, validation, and the differences between mutable and immutable objects. Additionally, it provides examples of implementing encapsulation through class design and data validation techniques.

Uploaded by

KL M
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Lecture 03: Encapsulation

Table of Contents

• What is Encapsulation?
• Keyword this
• Access Modifiers
• State Validation
• Mutable and Immutable Objects

2
Encapsulation
Hiding Implementation
Encapsulation
 Process of wrapping code and data together
into a single unit
 Flexibility and extensibility of the code
 Reduces complexity
 Structural changes remain local
 Allows validation and data binding

4
Encapsulation – Example
 Fields should be private
Person
-name: string
- == private
-age: int
+Person(string name, int age)
+Name: string + == public
+Age: int

 Properties should be public


5
Keyword This
 Reference to the current object
 Refers to the current instance of the class
 Can be passed as a parameter to other methods
 Can be returned from method
 Can invoke current class methods

6
Visibility of Class Members
Access Modifiers
Private Access Modifier
 It's the main way to perform encapsulation and hide
data from the outside world
private string name;
Person (string name) {
this.name = name;
}

 The default field and method modifier is private


 Avoid declaring private classes and interfaces
 accessible only within the declared class itself
8
Public Access Modifier
 The most permissive access level
 There are no restrictions on
accessing public members
public class Person {
public string Name { get; set; }
public int Age { get; set; }
}

 To access class directly from a namespace


use the using keyword to include the namespace
9
Internal Access Modifier
 internal is the default class access modifier
class Person {
internal string Name { get;
set; }
internal int Age { get; set; }
}
 Accessible to any other class in the same project
Team rm = new
Team("Real");
rm.Name = "Real Madrid";

10
Problem: Sort Persons by Name and Age
 Create a class Person

Person
+FirstName():string
+Age():int
+toString():string

11
Solution: Sort Persons by Name and Age

public class Person {


// TODO: Add a constructor
public string FirstName { get; private set; }
public string LastName { get; private set; }
public int Age { get; private set; }
public override string ToString() {
return $"{FirstName} {LastName} is {Age} years
old.";
}
}
12
Solution: Sort Persons by Name and Age (2)

var lines = int.Parse(Console.ReadLine());


var people = new List<Person>();
for (int i = 0; i < lines; i++) {
var cmdArgs = Console.ReadLine().Split();
// Create variables for constructor parame-
ters
// Initialize a Person
// Add it to the list
}

13
Solution: Sort Persons by Name and Age (3)

var sorted = people.OrderBy(p => p.FirstName)


.ThenBy(p => p.Age).ToList();

Console.WriteLine(string.Join(
Environment.NewLine, sorted));

14
Problem: Salary Increase
 Expand Person with salary
 Add getter for salary Person
 Add a method, which updates +FirstName: string

salary with a given percent +Age: int


+Salary: decimal
 Persons younger than 30 get
+IncreaseSalary(decimal):
half of the normal increase void
+ToString(): string

15
Solution: Salary Increase

public decimal Salary { get; private set; }


public void IncreaseSalary(decimal percentage)
{
if (this.Age > 30)
this.Salary += this.Salary * percentage / 100;
else
this.Salary += this.Salary * percentage / 200;
}

16
Validation
Validation
 Setters are a good place for simple data validation
public decimal Salary {
get { return this.salary }
set {
if (value < 460) Throw exceptions
throw new ArgumentException("...");
this.salary = value; }
}

 Callers of your methods should take care of handling exceptions


18
Validation (2)
 Constructors use private setters with validation logic
public Person(string firstName, string last-
Name,
int age, decimal salary) {
this.FirstName = firstName; Validation happens
inside the setter
this.LastName = lastName;
this.Age = age;
this.Salary = salary;
}
 Guarantee valid state of the object after its creation
19
Problem: Validate Data
 Expand Person with Person
validation for every field -firstName: string
 Names must be -lastName: string
-age: int
at least 3 symbols -salary: decimal

 Age cannot be zero or negative +Person()


+FirstName(string
 Salary cannot be less than 460 fname)
+LastName(string
lname)
+Age(int age)
+Salary(decimal
salary) 20
Solution: Validate Data

public int Age


{
get => this.age;
private set {
if (age < 1)
throw new ArgumentException("...");
this.age = value; }
}
// TODO: Add validation for the rest

21
Mutable vs Immutable Objects
 Mutable Objects  Immutable Objects
 Mutable ==  Immutable ==
changeable unchangeable
 Use the same memory  Create new memory
location every time they're
 StringBuilder modified
 string

22
Mutable Fields
 Private mutable fields are still not encapsulated
class Team
{
private List<Person> players;
public List<Person> Players {
get { return this.players; } }
}

 In this case you can access the field methods


through the getter
23
Mutable Fields (2)
 You can use IReadOnlyCollection to
encapsulate collections
public class Team
{
private List<Person> players;
public IReadOnlyCollection<Person> Players
{
get { return
this.players.AsReadOnly(); } }
public void AddPlayer(Person player)
=> this.players.Add(player);
24
Problem: Team
 Team have two squads Team

 First team & Reserve team -name : string


-firstTeam: List<Person>
 Read persons from console -reserveTeam: List<Person>

and add them to team +Team(String name)


+Name(): string
 If they are younger than 40, +FirstTeam():
ReadOnlyList<Person>
they go to first squad +ReserveTeam:
 Print both squad sizes ReadOnlyList<Person>
+addPlayer(Person person)

25
Solution: Team

private string name;


private List<Person> firstTeam;
private List<Person> reserveTeam;

public Team(string name) {


this.name = name;
this.firstTeam = new List<Person>();
this.reserveTeam = new List<Person>();
}
// continues on the next slide
26
Solution: Team(2)
public IReadOnlyCollection<Person> FirstTeam {
get { return this.firstTeam.AsReadOnly(); }
}
// TODO: Implement reserve team getter
public void AddPlayer(Person player) {
if (player.Age < 40)
firstTeam.Add(player);
else
reserveTeam.Add(player); }

27
Summary

 Encapsulation:

  …Hides implementation
  …Reduces complexity
 Ensures that structural changes
remain local
 Mutable and Immutable objects

28
Exercises

• Time to practices

You might also like