Sunday, 20 November 2016

Solid Part 3 - LSP (Liskov Substitution Principle)

The third part of SOLID is Liskov Substitution Principle (LSP), a scientific article created by Barbara Liskov in 1987.

The principle says "A base class can be replaced by the derived class". There are two questions to think  about when using the Liskov Principle:
1- Does the base class have useless behaviors for the derived class?
2- Is the external behavior changed when we replace the base class for the derived class?

If one of them is true, using Liskov Principle the relation of the base and derived classes is wrong.

When you are using inheritance if the derived class does not implement all the methods of the base class or part of the methods and attributes of the base class does not make sense for the derived class, according to LSP that inheritance is wrong and may bring future problems to the software. Imagine a software that you have to calculate discounts for new customers and for old customers:

Base CustomerClass
Derived PossibleCustomerClass
Let's see what happens when this code runs:

Console Application
When I run the code above in a Console Application I got the result:

Console Application Running

Oh it works fine, but if I replace Customer for PossibleCustomer?

Possible Customer 

The possible customers can not have a Register Date, when I run that code, I get this result:

PossibleCustomer Error
As we can see, the concept of inheritance can not be used only for reuse the code, the concept must be used only when makes sense the inheritance of characteristics and behaviors of the base class.
In general, when we use Open Closed Principle in our code, is easier to use LSP. 
When we will use inheritance, we must ask "Is the objectA an object of objectB?", for example "Is a dog an animal?" or "Is a chocolate a candy?" if the answer is true and the external behavior of the classes is the same, the derived class can use the behavior and characteristics of the base class.

In some cases, to use LSP we just have to implement the Interface Segregation Principle (ISP), but about that I will write next week!

Monday, 14 November 2016

Solid Part 2

Hello everybody, today I am going to continue the five parts about SOLID, and the part 2 is about Open/Closed Principle.

OCP - Open/Closed Principle

As the name suggests, a class must be open for extensions and closed for modifications, this can confuse you but it is very interesting! 
It means that the class can easily change their behavior without a change in their source code.That extension can be made by using inheritance, interface or composition.
This is very important when you are changing a class that works fine in production environment without the need of new unit tests, concern if the class will generate some bugs, unknown errors in stable parts of the code.
The concept of extension remember us the use o inheritance in OOP, the idea is when a class is working in production environment, the class changes only in a fix of development bugs or a change in model classes, for example, adding a new property but other changes  as new resources must be implemented as extension of that class, so this principle says that we should have so many abstractions among the software.

Let me exemplify for you, imagine that we have a class which calculates the interest for bank accounts, if we have two types of account the current account and the savings account our code will be that:

OCP Example
Ok, it works, but if we need to add another account type or make changes on the calculation? It is not cool to add a lot of IFs in our class, it will difficult some analisys and changes in our class and in a large class it can cause so many bugs. To put this class into the Open/Closed Principle we need to use that code:

Account class in OCP
With the code above we can implement new account types without a change in the Account class or the others account types, we just need create a new class inheriting from AccountOCP class and override the CalculateInterest method, so the class is Open for extensions and Closed for modifications and you do not need to change any code in any class when implement a new account type.


Sunday, 10 April 2016

SOLID Part 1

First of all I want to apologize for the last weeks without a text. Many things happened and I could not write.

Today I am going to start a series of posts about SOLID. SOLID is a group of 5 patterns, each one represented by a letter, starting by S.

But Raphael, what is SOLID?

Each SOLID's letter

  • Decreases your code's maintenance effort
  • Improves your code's understanding
  • Decreases the coupling between objects

SRP  - Single Responsibility Principle

As the name suggests, each class must have the behaviors within their responsability, here is an example of a class outside the SRP:

Class outside the SRP

In that class, beyond his responsibility, update the name and the address, it send e-mails as well, what is outside his responsibility. In this example I used a small class, but imagine a very large class with more than 1000 lines with many behaviors outside his responsibility like do some calculation, persist on the database, generate one or more reports, and more others behaviors, how hard it would be the maintenance of the code? And the class has a strong coupling with the reference System.Net.Mail, what is very wrong as well.

How to fix it?

To fix it you need to isolate the method SendMail in a class that have as responsibility manipulate e-mails. If exists other behaviors as the cited previously you need to isolate them as well.

Email class

Client class in SRP

This is the SOLID's most basic pattern, next week I will write about the next pattern, Open Closed Principle.

Tuesday, 23 February 2016

SQL Foreign Key and Joins

Hello everybody! As I promised I am going to write about Foreign Key and Joins in SQL.

Foreign  Key

Foreign Key are keys that references the primary key of another table. Let's create the table Salesman:

Create Table Salesman

And after I will create the Sale table that will references the Client and Salesman tables:

Create Table Sale

Take a look, I told the database the columns ClientID and SalesmanID are Foreign Key and after I used the keyword REFERENCES to reference the table and between parenthesis the column referenced.

Just remembering, you can not insert an ID for Client and Salesman in Sale table that not exists in Client and Salesman tables. Always a value of a Foreign Key should exists in the referenced table.


Joins


Now let's talk about the existing Joins in SQL:

Inner Join


Inner Join

Starting by INNER JOIN, as the image shows, returns all the data associated. I will select the client's name, salesman's name and the value of the sales using INNER JOIN:

Inner Join

Left Join


Left Join

LEFT JOIN, as the image shows, returns all data from the table on the left side of the JOIN and all the associated data from the right table. 

Left Join

Right Join


Right Join


RIGHT JOIN is like the LEFT JOIN, but inverted. I will change the LEFT JOIN in the previous query for a RIGHT JOIN

Right Join

In that case the client John Doe disappeared.

Outer Join


Outer Join

OUTER JOIN, known as FULL OUTER JOIN, returns all data from all tables.

Outer Join

Left Excluding Join


Left Excluding Join

The contrary of LEFT JOIN, returns all data of the left side table not associated with the right side table.

Left Excluding Join

Right Excluding Join



Right Excluding Join

Like the LEFT EXCLUING JOIN but with the right side.

Right Excluding Join

Outer Excluding Join



Outer Excluding Join

OUTER EXLUDING JOIN returns all data that are not associated.

Outer Excluding Join

You can also mix more than one join:


Mix of Joins

Image explaining all JOINS:

All Join

Alias

As you can see, I used some acronyms in my queries like "SM", "S", "C", "ClientName", "SalesmanName", this is called ALIAS, it is like a nickname for tables and columns. The first three are ALIAS for tables, I used to better identify the tables in my queries; take a look: I used only the alias on my JOINS. And the last two are ALIAS for columns to better identify them in the results. The use of alias is not required, you decide when to use, use if you think that ALIAS will facilitate your queries.

Saturday, 13 February 2016

SQL's Basic Operations

Hi everybody! Today I am going to write for you, my friends in the beginning of career, about the four basic operations of a database: Select, Insert, Update, Delete and also about Primary Key and how to create tables. In the next post I will write about Foreign Key and Joins.

Let's begin with the creation of the Client table, with the fields: ClientID, Name, BirthDate and Address.


Creating the Client table

Take a look at the ClientID, it has the properties: PRIMARY KEY, IDENTITY and NOT NULL.

Primary Key: It is the table's identifier field, unique, the value can not repeat in the table, never can be NULL, in this table the primary key is a simple primary key, but the key can be a composite key with the same rules of the primary key but with two or more fields. Let's see an example, the creation of the City table with composite key: City and State. You can insert the values: City: Santos and State: São Paulo just one time.


Composite Key

Not Null: As the name says, the field does not accepts NULL values.

Identity: It means the field is auto increment, each insert you do not need to pass the value of the field, the SQL will get the last value of the field and sum 1. You can configure the IDENTITY, in example, IDENTITY (1,2) the first value is the start value, the second value is how much will be incremented to the last value, in this example the value starts in 1 and in the next insert will be 3, 5, 7, 9... The default of IDENTITY is (1,1).


Insert


As the name says, you insert new values in database. Let's see the query:

Insert

Let's take a look in the syntax:
INSERT INTO table_name (FIELDS) values (VALUES)

INSERT INTO tells the database that you are doing an insert, after you tell the fields followed by the word VALUES and after you tell the values, in the same order of the fields. The fields are not required, but it is a good practice, if you will insert values for all the fields you just need to tell the values.


Select


Select is the command to recover data from database.I will do four selects. First of all, I am going to do a select for all fields without filter.

Select 1

Now as second example, I am going to select only the name of all clients.

Select only name

Third example, select everything from client that has ID = 1

Select with ID = 1

Fourth example, select only name and address of the client with ID = 1

Select name and Address with ID = 1


SELECT tells the database that you are going to do a select, followed by the fields name separated by comma, or * for all fields, after as you can see is the word FROM followed by the table_name and the clause WHERE with the conditions of the select. You can give an "alias" to the table and fields, as a nickname, I will show it for you in my next post. The clause WHERE has some operators:

Basic operators

These are the basic operators, but there are others as LIKE that checks if a field contains a string.

WHERE Name LIKE ‘RAPHAEL%’:  Returns all clients that the name starts with Raphael.

WHERE Name LIKE ‘%FERNANDES’:  Returns all the clients that the name ends with Fernandes.


WHERE Name LIKE ‘%LIMA%’: Returns all clients that the name contains Lima.

Also we have the IN operator that checks if a value is any of the values in the clause.

WHERE ClientID IN (1,3,5): Returns the clients with ClientID equals 1,3 and 5.

The operator BETWEEN checks if a value is between 2 values.

WHERE ClientID BETWEEN 1 AND 3: Returns the clients with ClientID equals 1,2 and 3.

The WHERE clause may have more than one condition, using the operators AND and OR.

AND: All the conditions should be true.

WHERE ClientID = 1 AND Name LIKE 'Raphael%': It returns all the clients with the ID =  1 and Name starts with Raphael.

OR: Only one condition should be true.

WHERE ClientID = 1 OR Name LIKE 'Raphael%': It returns all the clients with the ID =  1 OR the clients that the Name starts with Raphael.



Update


Update as the name says, updates one or more records, let's update the address of the client with ID = 1:

Updating a record



Select in the row updated


The syntax of update: UPDATE table_name SET field = value WHERE conditions



Delete


Delete, as the name says, is the command to delete a row.

Deleting a row

Select *  from Client

The syntax: DELETE FROM table_name WHERE conditions

So, this is the end of the first part about database.
I hope you liked.

Sunday, 7 February 2016

Minification and Bundle

Hello everybody! Today I am going to talk about Minification and Bundle.

Minification

When you do a request to server, a lot of bytes are transferred between client and server, but there is a way to reduce this transfers optimizing the requests.

This is possible with the use of Minification, Minification delete all useless spaces of the files to reduce file's size.

Normal Javascript File

Minified Javascrpt File


There are a lot of sites that does the minification in your files to get a better performance. Just take a look in internet to find these sites.

Bundle

Did you know, generally the Browsers can just download 6 Javascript or CSS files by time? But, did you know is possible put the files together in a single "package" for the browser download all of them in a single request? You can not mix Javascript files and CSS files in a single "package". 
What makes it possible is the use of Bundle.

It is very simple to configure a Bundle, you just need to open the folder App_Start of your project and then open the class BundleConfig.cs. Look the use of the namespace System.Web.Optimization, needed to optimize the files using Bundle.

Bundle Example

As you can see, the class has a single static method called RegisterBundles with a var of the BundleCollection type called bundles. In this var you will add all your file's "packages".When you call the Add method you need to use a parameter of the Bundle type, you can use ScriptBundle for Javascript files or StyleBundle for CSS files. After you do an instance of a new Bundle you need to use the virtual path of your bundle, like an ID, and after, you need to call the Include method, to include the files that will be in this "package".

We ca'n also look the existence of jquery-{version}.js and jquery.validade*. Jquery-{version} means all files starting with jquery- and having a version in name will be in the Bundle, like jquery-1.8.2.js. The jquery.validate means all files starting with jquery.validate will be in the Bundle.

Bundles are registered in Global.asax.cs file, this class executes every time your application is started.

Global.asax.cs

Look at the end of file, there is a line BundleTable.EnableOptimizations = true;
This line configure the load of the bundles, and tell the application to load minified files. This option is by default equals false, if you want to use this optimization, you need to set the property to true.

The use of bundles in Views, is possible with the helpers @Styles.Render for CSS files and @Scripts.Render() for Javascript files, both needs a parameter with the virtual path of the Bundle.

Bundles in View

Let's take a look in the Bundles loaded by the Browser:

Bundles in Browser
The bundles are loaded in a single request.

Friday, 29 January 2016

What is MVC?

What is ASP.NET MVC?

Do you know what is ASP.NET MVC?

Hi everyone, first of all, I am starting this blog to talk about .NET and things related  for developers and everybody who wants to know more about this universe.

I am going to explain for you what is MVC today, MVC is nothing more than a Design Pattern.

The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller.The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc assembly.

Model: Nothing more than a class. Yes, it is just a class, but a class that stores the attributes needed for the application, model has all the business, all the data manipulation. Summing up, model is a class with everything you need to manipulate data.


Simple Mvc Model

View: View is the HTML that users will see, Views uses the Razor Engine, implementing the use of Helpers  (I will write about Helpers soon). You can also use Models to bind the data.



Simple View Code

View in Browser


Controller: Is the middle between Model and View. Receive all the requests from user.


Controller

Let's see a chat with Model, View and Controller:

Controller: Hey Model, user wants to login in LinkedIn, please take these data and validate if is this ok!

Model: This is right, user can login.

Controller: Thanks Model. View, the data are right, I am going to send you user's data, and you, please, load the profile page.

View: Thanks, I am loading.


MVC'S Advantages

  • It makes it easier to manage complexity by dividing an application into the model, the view, and the controller.
  • It does not use view state or server-based forms. This makes the MVC framework ideal for developers who want full control over the behavior of an application.
  • It uses a Front Controller pattern that processes Web application requests through a single controller. This enables you to design an application that supports a rich routing infrastructure.
  • It provides better support for test-driven development (TDD).
  • It works well for Web applications that are supported by large teams of developers and for Web designers who need a high degree of control over the application behavior.

When do I use  ASP.NET MVC?

There is no rule to know when you should use MVC or Web Forms, Asp.Net  MVC did not come to replace Web Forms, but to be one more option in Web Development.