OOP AND SOLID
What is OOP?
let's talk about abstract classes and interfaces
Abstract Classes
Classes that can have defined behavior but do can be used to create new instances.
public abstract class Pet
{
public int Id {get;set;}
public string Species {get;set;}
public string Name {get;set;}
public double Weight {get;set;}
}
public class Dog : Pet
{
public string ColarColor {get;set;}
public bool IsAGoodBoy {get;set;} = true;
}
public class Cat : Pet
{
public bool isOutdoor {get;sets;}
}
var myPets = new List<Pet>();
var poochie = new Dog();
var scratchy = new Cat();
myPets.add(poochie);
myPets.add(scratchY);
Interfaces
Interfaces are a way to define functionality without defined implementation
public interface ISpeak
{
string Speak();
}
public class Dog : Pet, ISpeak
{
...
public string Speak(){
Console.WriteLine("Bark")
}
}
public class Cat : Pet, ISpeak
{
...
public string Speak(){
Console.WriteLine("Meow")
}
}
public class Person : ISpeak
{
...
public string Speak(){
Console.WriteLine("Hello")
}
}
var choirOfAngels = new List<ISpeak>();
var flanders = new Person();
choirOfAngels.add(poochie);
choirOfAngels.add(scratchy);
choirOfAngels.add(flanders);
foreach(var speaker in choirOfAngels)
{
speaker.Speak();
}
What is SOLID?
Wait. Design principle?
S.O.L.I.D.
Single responsibility
Open - Closed Princple
Liskov subsition Prinicple
Interface Segregation
Dependency Inversion
Single Responsibility
A class some only do one thing and do it well. This means that a single responsibility class will only have 1 reason to change.
Open-Closed
Objects should be easily expanded, but hard to modify .
Liskov Substitution Principle
Derived classes must be substitutable for their base classes.
Pause.
Interface Segration Principle
When defining interfaces, many smaller specific interfaces are better than big interfaces
Dependency Injection
Objects should depend on agreed upon functionality, should be ignorant of implementation
public interface ISinger
{
void Sing()
}
public interface IConductor
{
void StartGroup();
}
public class Choir
{
private List<ISingers> _members = new List<ISingers>();
private IConductor _conductor;
public Choir(IConductor conductor)
{
this._conductor = conductor;
}
public void StartSinging() {
this._conductor.StartGroup();
foreach(var singer in this._members)
{
singer.Sing()
}
}
}
So what does this mean for us as web developers?
We can (and should) use dependency injection and interface design to better structure our code.
OOP-SOLID
By Mark Dewey
OOP-SOLID
- 287