methods;
enumerables;
methods
some call them functions, or procedures.
what are methods
- methods should be simple
- methods should only do one thing
- simple methods allow us to build
re-usable parts - methods usually return a value
- methods can take arguments, as parameters
- should have minimal side effects
// Simple method
public static void PrintHello()
{
Console.WriteLine("Hello Nick!");
}
simple and do one thing
// Simple method
public static void PrintHello(string name)
{
Console.WriteLine($"Hello {name}!");
}
Take arguments and have parameters
// Simple method
public static int SquareANumber(int x)
{
return x * x;
}
Return a value
// Simple method
public static int SquareNumber(int x) => x * x;
Bonus: One-Liner!
// Simple method
public static int GetCardsTotal(List<Card> cards)
{
var total = 0;
for(var i = 0; i < cards.Count; i++)
{
total += cards[i].GetCardValue();
}
return total;
}
Practical Example
Let's refactor some code!
Functions are powerful
Problem
For loops can very useful, but very tedious to use, hard to keep track off and can easily let use create "spaghetti code".
Solution
Instead of a for loop, we use take the patterns that for loops create, and create simpler methods that emphasize simplicity, readability and reuse.
LINQ
In C#, these special methods
foreach
for (let i = 0; i < people.Count; i++){
Console.WriteLine(people[i]);
ShowGreatingToPerson(people[i]);
AddPersonToDOM(people[i]);
}
foreach
foreach(var person in people)
{
Console.WriteLine(person);
ShowGreatingToPerson(person);
AddPersonToDOM(person);
}
image credit of: https://www.wenovio.com/2017/04/11/javascript-manipuler-vos-donnees-mapfilterreduce/
public class Person {
public string Name {get;set;}
public DateTime Birthday {get;set;}
public string ShirtColor {get;set;}
public int NumberOfApples {get;set;}
}
problem
var birthdays = new List<string>();
for(var i = 0; i < people.Count; i++){
var birthdayAsString =
people[i].Birthday.Month
+ '/' + people[i].Birthday.Day;
birthdays.Add(birthdayAsString);
}
Select
var birthdays = people.Select(person => {
return person.birthday.month +
'/' +
person.birthday.day
});
problem
var orangeShirtedPeople = new List<Person>();
for(var i = 0; i < people.Count; i++){
if (people[i].Shirt == "orange"){
orangeShirtedPeople.Add(people[i]);
}
}
Where
var orangeShirtedPeople =
people.Where(person => person.Shirt == "orange");
problem
var totalApples = 0;
for(var i = 0; i < people.length; i++){
totalApples += people[i].apples
}
Aggregate
int totalApples =
people.Aggregate(
0,
(total, person) =>
total + person.NumberOfApples);
image credit of: https://www.wenovio.com/2017/04/11/javascript-manipuler-vos-donnees-mapfilterreduce/
Copy of foreach, map, filter, reduce
By Mark Dewey
Copy of foreach, map, filter, reduce
- 244