Object Oriented Programming

Hello Im Fabian Calsina, Im writing this post as a complement to the repository mentioned below.

All the theory describes here was implemented in the current repository https://github.com/Fabho/OOP_data_layer
I must mention that I am writing this entry after I finished the course: Object-Oriented Programming Fundamentals in C# from Deborah Kurata

If you want to follow the steps from the code you can run the test inside test project or attach debuggers.

Why should I learn OOP?
OOP is the foundation for many things clean code, api, design patterns, defensive coding, design apps in general.

Class
A class is like a template for objects.
A class provides a definition of the objects, it has properties and methods.



public class Cat
{

}

Object
Its an instance of a class. Objects are reference types, 2 objects will be equal if they reference the same object.



var smallCat = new Cat();

Entity
An entity is something significant and is or could be a class. As an example for a vet, some entities can be pets, clients.

OOP
Is an approach to design code and applications that are flexible, natural, testeables focusing in objects that interact with other objects.

We can define an small recipe to implement OOP in our projects.

  • Identify the involved entities.
  • Identify the classes
  • Separate responsibilities
  • Establish Relationships between classes
  • Leverage Reuse

Identify classes from requirements
You can follow these steps to identify and define the required classes


4 pillars of OOP

Abstraction
Process of simplify reality, ignore unnecessary details and focus on what's important for the problem and purpose.

Encapsulation
Technique to hide properties and implementation details in a class to hide complexity.

Some benefits:

  • Protects data.
  • Allow authentication before get data
  • Allow validation before set data
  • Manage complexity
  • Implementation can be done without impacting other modules and apps.
  • Only the class needs to understand the implementation

In .Net you have a layered structure within a solution. Each layer usually is a project. Some common layers are: user interface, business layer, data access.

To create a DL in .net we choose Visual c# Class Library project.

internal access refers to a level access related to the project.

We can have auto implemented properties.Behind scenes its saving the private value and a public property with the accessors.


private string _lastName;
public string LastName
{
    get
    {
        return _lastName;
    }
    set
    {
        _lastName = value;
    }
}

Basic Testing

For testing its a common pattern to define 3 areas:

  • Arrange. Get required data
  • Act. Set expected value
  • Assert. Do the test

It's a good idea to test with valid and invalid values.


        [TestMethod]
        public void ValidateValid()
        {
            //-- Arrange
            var customer = new Customer
            {
                LastName = "Bagginns",
                EmailAddress = "fbaggins@hobbiton.me"
            };

            var expected = true;

            //-- Act
            var actual = customer.Validate();
            //-- Assert
            Assert.AreEqual(expected, actual);
        }

Methods
Each method has a signature. The signature is the the name and the parameters

public Customer GetCustomer(int id)

We can overload methods using the same name but different parameters.
public Customer GetCustomer(int id, string name)

Constructor

Has the same name of the class and its executed each time that an object is created.

Default constructor does not have parameters.

We can define many constructors as we want. If we don't declare a constructor on is created implicitly 

If we define a constructor that's different from the default we need to define the default constructor too.

Constructors must ensure that all objects are initialized with valid values



        public Customer():this(0)
        {

        }

        public Customer(int customerId)
        {
            CustomerId = customerId;
            AddressList = new List<Address>();
        }

Nullable types
Nullable type is a value type that allow null or the assigned value.


public decimal? currentPrice {}

Separation of responsibilities
  • Minimize coupling
  • Maximize cohesión
  • Simplifies Maintenance
  • Improves testability

Coupling is the degree to which classes depend on external resources.
Cohesion. Is a measure how related everything is in a class for the purpose of the class.

Low coupling, high cohesion less chances to affect other classes

YAGNI you are not going to need it

Repository Pattern introduction
By convention the class assigned to communicate with the DB is called a Repository Class.

Establishing relationships
To define relationships its useful to check the classes without the properties and use arrows


Types of relationships in OOP
3 are defined collaboration, composition, inheritance.

Composition aggregation. Object composed of multiple objects that can exist outside the relationship


Order has a Customer, but Customer can exist without order
Object owns related objects. If the object is destroyed the related objects are destroyed too.
Id
Another way to use composition is use ids instead of the whole object.

Advantages
Reduce coupling. No direct reference.
More efficient. No more object loading.

Object interact providing services to each other. 

For testing purposes in uses a relationship some developer mock up the properties classes so they just test the current class.

Inheritance
With inheritance we can create more specialized classes (is a).
All classed in c# can have just one parent.
All classes inherit from Object.
Just use inheritance if its required unique code.


public class Customer : EntityBase
{

}

Polymorphism
Means many shapes. InOOP a method that can behave differently depending on the type of object that calls it implements polymorphism.

We have 2 options to build a base class, use an abstract class or a concrete class.

Abstract class
Is a class with at least one property or method not implemented. Cannot be instantiated.


public abstract class EntityBase
    {
        public bool IsNew { get; private set; }
        public bool HasChanges { get; set; }
        public bool IsValid => Validate();
        public EntityStateOption EntityState;

        public abstract bool Validate();
    }

Sealed Class

Cannot be extended through inheritance. Sealed class prevents extension and customization.

By default the properties in an abstract cñass are sealed so the base class should mark the them as virtual abstract or override

.
Abstract
Virtual
No implementation
Only use in abstract class
Must be overridden by derived class
Method with default implementation
Available in abstract or concrete classes.

Static class

Class that cannot be instantiated.
Access member using the class name
Members must also be static
Often used as a container for utility methods.

Extension methods
Add methods to an existing type without modifying the original type.
Extension methods appear in Intellisense

The method can be called as an extension method or as an static class method

Questions to decide between Static method or extension method:
  • Is the primary parameter an instance?
  • Does the method logically operate on that instance?
  • Is it desirable for the method to appear in intellisense for that type?

If yes use extension method.



        public static string InsertSpace(this string source)
        {
            string result = string.Empty;

            if (!string.IsNullOrWhiteSpace(source))
            {
                foreach(char letter in source)
                {
                    if (char.IsUpper(letter))
                    {
                        result = result.Trim();
                        result += " ";
                    }
                    result += letter;
                }
            }

            result = result.Trim();

            return result;
        }

Interfaces
Interfaces just provide the description of the methods.(No implementation).
Interfaces define roles and they are always public.
No access modifier are required on properties

To implement an interface add the interface to the class signature

Implement the interface member(public, non static)

    public interface ILoggable
    {
        string Log();
    }

    public class Customer : EntityBase, ILoggable
    {

        public string Log()
        {
            var logString = CustomerId + ": " +
                            FullName + " " + "Email: " + EmailAddress + " " +
                            "Status: " + EntityState;

            return logString;
        }
    }

Comentarios

Entradas populares de este blog

ASP.NET MVC 5 Fundamentals