0% found this document useful (0 votes)
16 views37 pages

02 - Working With Abstraction

The document discusses the principles of code abstraction, focusing on project architecture, methods, classes, and code refactoring. It emphasizes the importance of splitting code into logical parts for improved readability, easier debugging, and code reuse. Additionally, it covers enumerations, static classes, and namespaces as tools for organizing and structuring code effectively.

Uploaded by

KL M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views37 pages

02 - Working With Abstraction

The document discusses the principles of code abstraction, focusing on project architecture, methods, classes, and code refactoring. It emphasizes the importance of splitting code into logical parts for improved readability, easier debugging, and code reuse. Additionally, it covers enumerations, static classes, and namespaces as tools for organizing and structuring code effectively.

Uploaded by

KL M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Lecture 02: Abstraction

Table of Contents

• Project Architecture
– Methods
– Classes
– Projects
• Code Refactoring
• Enumerations
• Static Classes
• Namespaces

2
Splitting Code into Logical Parts

• Project Architecture
Splitting Code into Methods

• We use methods to split code into functional blocks


– Improves code readability
– Allows easier debugging
– Allows us to easily reuse code

position[0] = row – 1
position[0] = row + 1 ChangeRow(desiredRow
)
position[0] = row + 3

4
Example: Code Without Methods

foreach (char move in moves)


{
for (int r = 0; r < room.Length; r++)
for (int c = 0; c < room[r].Length; c+
+)
if (room[row][col] == 'b')

}

5
Example: Code with Methods

foreach (char m in
moves)
{
MoveEnemies();
KillerCheck();
MovePlayer(move);
}

6
Splitting Code into Methods (2)

• We change a method once and the change affects all


calls var bankAcc = new BankAccount();
bankAcc.Id = 1;
bankAcc.Deposit(20);
bankAcc.Withdraw(10);

Console.WriteLine($"Account {bankAcc.Id},
balance {bankAcc.Balance}");

Console.WriteLine
Override .ToString() to set (bankAcc.ToString())
a global printing format ; 7
Splitting Code into Methods (3)

• A single method should complete a single task


void DoMagic ( … )
void DepositOrWithdraw ( … )
decimal DepositAndGetBalance
( … )

void Withdraw ( … )
void Deposit ( … )
decimal GetBalance ( …
)
8
Problem: Rhombus of Stars

• Draw on the console a rhombus of stars with size n


n = 3 n = 2 n = 1

* * *
* * * *
* * *
*
* *
*
9
Solution: Rhombus of Stars

int size = int.Parse(Console.ReadLine());


for (int stCount = 1; stCount <= size; stCount++)
PrintRow(size, stCount);
for (int stCount = size - 1; stCount >= 1;
stCount--)
PrintRow(size, stCount);Reusing code

10
Solution: Rhombus of Stars (2)

static void PrintRow(int figureSize, int star-


Count)
{
for (int i = 0; i < figureSize - starCount; i++)
Console.Write(" ");
for (int col = 1; col < starCount; col++)
Console.Write("* ");
Console.WriteLine("*");
}

11
Splitting Code into Classes

• Just like methods, classes should not


know or do too much
GodMode master = new GodMode();
int[] numbers = master.ParseAny(args);
...
int[] numbers2 =
master.CopyAny(numbers);
master.PrintToConsole(master.GetDate())
;
master.PrintToConsole(numbers); 12
Splitting Code into Classes (2)

• We can also break our code up logically into classes


ArrayParser parser = new ArrayParser();Hides implementation
OuputWriter printer = new OuputWriter(); Allows us to change
output destination
int[] numbers = parser.IntegersParse(args);
int[] coordinates = Helps us avoid
repeating code
parser.IntegerParse(args1);
printer.PrintToConsole(numbers);

13
Problem: Point in Rectangle

• Create a Point class holding the horizontal and vertical


coordinates
• Create a Rectangle class
– Holds two points
• Top left and bottom right
• Add Contains method
– Takes a Point as an argument
– Rеturns it if it’s inside the current object
of the Rectangle class
14
Solution: Point in Rectangle

public class Rectangle


{
private Point topLeft;
private Point bottomRight;
// TODO: Public properties
public bool Contains(Point point)
// TODO: Implement the method
}

15
Solution: Point in Rectangle (2)

public class Point


{
private int x;
private int y;
// TODO: Add Public
properties
}

16
Solution: Point in Rectangle (3)

public bool Contains(Point point)


{
bool isInHorizontal =
this.TopLeft.X <= point.X && this.BottomRight.X >=
point.X;
bool isInVertical =
this.TopLeft.Y <= point.Y && this.BottomRight.Y >=
point.Y;
bool isInRectangle = isInHorizontal && isInVertical
return isInRectangle;
} 17
Restructuring and Organizing
Code

• Refactoring
Refactoring

• Restructures code without changing the behaviour


• Improves code readability
• Reduces complexity
class ProblemSolver
{ public static void DoMagic()
{ … } }
class DataModifier
{ public static T Execute(); … }
class OutputFormatter
{ public static void Print();
19
Refactoring Techniques
• Breaking code into reusable units
• Extracting parts of methods and classes into new ones
Deposit()
DepositOrWith-
draw() Withdraw(
)
 Improving names of variables, methods, classes, etc.
string string
str; name;
 Moving methods or fields to more appropriate classes
Car.Open() Door.Open()

20
Problem: Student System

• You are given a working Student System project to refactor


• Break it up into smaller functional units and make sure it works
• It supports the following commands:
– "Create {studentName}{studentAge}{studentGrade}"
• Creates a new student
– "Show {studentName}"
• Prints information about a student
– "Exit"
• Closes the program

21
Syntax and Usage

• Enumerations
Enumerations

• Represent a numeric value from a fixed set as a text


• We can use them to pass arguments to methods
without making code confusing
enum Day { Mon, Tue, Wed, Thu, Fri, Sat, Sun
}
GetDailySchedule( GetDailySchedule(Day.Mo
• By 0) enums start at 0
default n)

• Every next value is incremented by 1

23
Enumerations (2)

• We can customize enum values


enum Day { enum CoffeeSize
Mon = 1, {
Tue, // 2 Small = 100,
Wed, // 3 Normal = 150,
Thu, // 4 Double = 300
Fri, // 5 }
Sat, // 6
Sun // 7
}
24
Problem: Hotel Reservation

• Create a class PriceCalculator that calculates the total price


of a holiday, by given price per day, number of days, the season
and a discount type
• The discount type and season
should be enums
• The price multipliers will be:
– 1x for Autumn, 2x for Spring, etc.
• The discount types will be:
– None - 0%
– SecondVisit - 10%
– VIP - 20%

25
Solution: Hotel Reservation

public enum Sea-


public enum Dis-
son
count
{
{
Spring = 2,
None,
Summer = 4,
SecondVisit = 10,
Autumn = 1,
VIP = 20
Winter = 3
}
}

26
Solution: Hotel Reservation (2)

public class PriceCalculator {


public static decimal CalculatePrice(decimal pri-
cePerDay,
int numberOfDays, Season season, Discount discount)
{
int multiplier = (int)season;
decimal discountMultiplier = (decimal)discount /
100;

27
Solution: Hotel Reservation (3)

decimal priceBeforeDiscount =
numberOfDays * pricePerDay * multiplier;
decimal discountedAmount =
priceBeforeDiscount * discountMultiplier;
decimal finalPrice = priceBeforeDiscount - dis-
countedAmount;

return finalPrice; }
}

28
Static Class Members

• Static Classes
Static Class

• A static class is declared by the static keyword


• It cannot be instantiated
• You cannot declare variables from its type
• You access its members by using the its name
double roundedNumber =
Math.Round(num);
int absoluteValue = Math.Abs(num);
int pi = Math.PI;

30
Static Members

• Both static and non-static classes can contain


static members:
– Methods, fields, properties, etc.
• A static member is callable on a class even when
no instance of the class has been created
• Аccessed by the class' name, not the instance name
• Only one copy of a static member exists, regardless
of how many instances of the class are created

31
Static Members (2)

• Static methods can be overloaded but not overridden


• A const field is essentially static in its behavior and it
belongs to the type, not the instance
• Static members are initialized before the static member
is accessed for the first time and before the static
constructor
Bus.Drive();
int wheels = Human.NumberOfWheels;

32
Example: Static Members

public class Engine


{
public static void Run() {
Console.WriteLine("This is a static
method"); }
}
public static void Main() {
Engine.Run();
}
// Output: This is a static
method 33
Definition and Usage

• Namespaces
Namespaces

• Used to organize classes


• The using keyword allows us not to write
their names
• Declaring your own namespaces can help you
control the scope of class and method names
System.Console.WriteLine("Hello
world!");
var list = new

System.Collections.Generic.List<int>();
35
Summary

 Well
… organized code is easier to work with
 We
…can reduce complexity using
 Methods
… , Classes and Projects
 Enumerations define a fixed set of constants
 Static classes cannot be instantiated
 Namespaces organize classes

36
Exercises

• Time to practices

You might also like