Press "Enter" to skip to content

Posts published in “solid”

When we look at the history of SOLID, we don’t have to go far. It was first proposed by Michael Feathers at the beginning of the 2000s and was later renamed as “SOLID” by Robert C. Martin. You will see solid principles with sample code in this category!

Interface Segregation Principle in C# – ISP

SOLID principles now ending with this article! Todays topic is Interface Segregation Principle with C# sample code.

Let’s start with the general definition of the ISP: “metot objects should not be forced to be connected to the Interface’s where the methods they do not need ’”. I think so clear, right?

Lets have an daily life example for this definition:

Nowadays, there is a concept that we call smart phones!. So, calling phone and chatting and sending SMS, devices that do a lot more work. You can take photos and videos, connect to social networks, and control your e-mails. But these abilities are completely isolated from each other, right? They certainly don’t interfere! So you’ve got a great picture of you walking down the road; Receive your smartphone to take pictures. But what is that! When you’re about to take photos, your smart device asks for the number that needs to be translated! It wouldn’t be a nice thing.

As you can see in this example, the current module of the phone (for example the camera) will only stay in communication with the corresponding Interface. In this way, you have created a more developed architecture.

Lets write some code:

Interface Segregation Principle with C# Sample Code

Let code like a social messaging platform. Members of this platform can send voice, video or just text messages to each other. You have decided that it is appropriate to design an interface in terms of architecture and you have created an interface as follows:

public interface IMessage
        {
            string From { get; set; }
            string To { get; set; }
            string MessageBody { get; set; }
            void AttachImage(byte[] stream);
            int ImageWidth { get; set; }
            int ImageHeight { get; set; }
            void AttachMovie(byte[] stream);
            int MovieDuration { get; set; }
        }

Then you created your Message class by implementing this Interface:

ISP Sample code in C#

Problem:

Again, everything seems to be fine. But will the message object always have a picture or video? So do you think I need to use features like ImageWidth, MovieDuration if this object, which is going to be in traffic between client-server, only contains text messages? Yeah, I don’t think so! I think we can solve this architectural problem by simplifying the IMessage interface a little more.

Solution:

IMessage doing lots of work. So we can seperate some of functionality.

  • All message must include from, To and MessageBody features.
  • You have to move the image-containing messages, the AttachImage method and the properties of ImageWidth, ImageHeight.
  • You have to include messages that contain videos, the AttachMovie method and the MovieDuration feature.
Interface Segregation Principle

Thus; I only have a chance to develop objects that depend on the interfaces needed.

ISP Article Image

Now you have a more developed design in your hand! Separate interfaces and cleaner architecture.

Thanks for reading. We’ve finished SOLID principles. I am going to start Design Patterns immediately!

See you soon.

Open Closed Principle in C# – OCP

Hi, everyone! Todays topic is Open closed principle! we’ll explain 2nd letter of SOLID principle. We gonna write some code in c#.

Now, let’s take a look at the technological products that we use today. All the products have changed so far as to reach the last version we are currently using? hmmm, this is not only the technological products, but all the existing systems apply to this. Everything changed!

As you know, the only thing that doesn’t change is change! 

Well; If the products we are producing will change over time, then we should make this change the lowest cost, right? To achieve this, we obtain a product by combining many parts.

For example, a car actually consists of thousands of parts. Wheels, crankshaft, engine, battery, storage and so on can be applied to an existing car, for example, when a new tire technology is developed. All you have to do is change your car’s tires. Imagine that you have to change the car completely to change a tire! Sounds bad right?

The objects you use in your project are just like parts of a machine. Therefore, the functions and numbers of these objects may vary. So you need to design such a structure that the development is ON but the source code must be switched OFF. That’s exactly the key phrase of the open-closed principle. But I still consider writing the sentence of Bertrand Meyer, the architect of this notion, as a debt: Software assets (classes, modules, functions, etc.) should be open to development, and CLOSED to code change.

Open Closed Principle with C# example Code

Lets write some code! I’ve just created a scenario! We have a e-commerce web application and we would like to discount according to customer’s membership type! We have premium & standard membership.

    public enum MemberShipType
    {
        Standard,
        Premium
    }

and, our customer class:

    public class Customer
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public MemberShipType MemberShip { get; set; }
    }

and now, Order class & calculating discount function:

    public class Order
    {
        public decimal CalculatePrice(decimal price, Customer customer)
        {
            decimal result = 0;
            switch (customer.MemberShip)
            {
                case MemberShipType.Standard:
                    result = price;
                    break;
                case MemberShipType.Premium:
                    result = price * (1 - 0.1M);
                    break;
                default:
                    break;
            }
            return result;
        }
    }

Everything looks good! But there is a problem. In the future, if one more member ship type added to system, what will we do? Hmmm…

Your project is not open to objective development. Because if you want to make a development as mentioned, you need to change your source code seriously. So after adding the value “Gold. In the MemberShipType, you need to add a new case blablabla..

This is not something we want. In Open-Closed Principle says that ‘Software assets
should be open to development, and CLOSED to code change. ‘

If we want this scenario to be available with the OCP, I need to design the Order class so that I never need to change it again. I also need to get rid of the enum type so that the structure can be improved!

Now my friends, here is our hero! Abstract class!

  public abstract class MemberShipType
    {
        public abstract decimal CalculatePrice(decimal price);
    }

public class StandardMemberShip : MemberShipType
    {
        public override decimal CalculatePrice(decimal price)
        {
            return price;
        }
    }

    public class PremiumMemberShip : MemberShipType
    {
        public override decimal CalculatePrice(decimal price)
        {
            return price * (1 - 0.1M);
        }
    }

   public class Order
    {
        public decimal CalculatePrice(decimal price, Customer customer)
        {
            return customer.MemberShip.CalculatePrice(price);
        }
    }

If you want to add Gold membership, all you have to do is to build a new class that derives from the MemberShipType class! Now it is available with OCP!

I am asking the main questions:

  • If new membership type added to project, will we change the source Order code? (NO!)
  • Can I improve the project by adding as many membership types as I want? (YES!)

This is Open Closed Principle my friends! We did wrote some code in C#! i hope you got learned. Share your ideas with me.

Thanks for reading, see you on next SOLID principle!

Eat, sleep & SOLID!

Single Responsibility Principle in C# – SRP

single responsibility principle in c#

Hi, my friends! we are going on SOLID principle as we promise! Todays topic is “single responsibility principle”. This principle is also first character of SOLID!

Now, move on to article!

Lets make a definition: Single Responsibility principle says that “There must be one reason to change an object!” Of course, we will examine this sentence with a little more examples. But before that, by reversing our key phrase, let’s find out how to identify the object that does not comply with this principle: I have an object with many methods for different purposes.

The main purpose of these principles is to ensure the flexibility of your code. So if you are writing a project that is likely to grow continuously, your long-term code maintenance and easy-to-develop architecture application will make your work easier.

This principle, which we call SRP in short, says that every object should be responsible for only one job. Now, please bring a restaurant’s kitchen in front of you. The employees in this kitchen were asked to prepare a tuna salad. There are people working side by side on a long bench. In the first row, he cuts the tomatoes, then the other slices the cucumber. After the third person has washed the greens beautifully, the fourth person prepares pickles. The fifth person adds the tuna to the salad, and the sixth conveys the salad to the waiter.

So each of the chefs here has only one responsibility, right? Now let’s take a look at our key sentence: There must be only one reason to change an object . How many people will you say when you want to change the chopping shape of tomatoes? Aha! That’s it!

The task of a developer is to solve problems. These problems can be very complex sometimes. At this point, with the SRP approach, you can break the big problem into small pieces. Thus, by focusing on these mini problems, you can solve the big problem much more comfortably.

So, the application you developed would be like a clock’s working mechanism. Every module has one responsibility!

First, take a look not SRP principle code:

	
public class Pizza
    {
        public string Name { get; set; }
        public string Size { get; set; }
        public double Price { get; set; }
 
        
        public void AddMaterial(string material)
        {
            //do stuff
        }
        public List<string> ShowMaterials()
        {
            //do stuff
        }
        public void RemoveMaterial(string material)
        {
            //do stuff
        }
        public void Cook(int minutes)
        {
            //cook...
        }
        public void Dough(int size)
        {
            //do stuff
        }
 
 
    }

This code doing theese items:

  • Keeps certain values of the pizza object.
  • doing stuff with materials
  • cooking pizzas

What we said, each class should have only one responsibility. So, I have to separate these three responsibilities into other types.

Lets code:

public class Pizza
{
   public string Name { get; set; }

   public string Size { get; set; }

   public double Price { get; set; }
}
public class MaterialFunction
    {
        public void AddMaterial(string material)
        {
            //adding materials
        }

        public void RemoveMaterial(string material)
        {
            //removing material
        }

        public List<string> ShowMaterials()
        {
            //showing materials
        }
    }
public class PizzaFunctions
    {
        public void Cook(int minutes)
        {
            //Cooking pizzas
        }
        public void Dough(int size)
        {
            //do stuff
        }

        public MaterialFunction Materials { get; set; }


    }

Here! Now each class is only responsible for one job! The pizza class is completely independent of the other classes and only features the object!

Now think about it: to develop & maintain this class is easier, right? But more important thing is, it is easy reading!

You did see how SRP implemented to C# with an example code! Share this article with your developer friends!

Thanks for reading! Go home to see what new programmers memes!

Dependency Inversion Principle in C# – DIP

Hi everyone, welcome to SOLID principles! Todays topic is Dependency inversion principle!

Here is the basic sentences of this principle:

  1. High-level modules should not be connected to low-level modules. Both must depend on abstract concepts.
  2. Abstract concepts should not depend on details. Details must be based on abstract concepts.

Of course, we will first apply these rules to daily life. I’ve always said that the design principles applied in the software architecture are inspired by life itself. Then let’s look at our life and let us see how easy these two substances are, which seem to be difficult to comprehend.

Now if I tell you that the furniture is a house fixed to the floor; Would you think this house was effective? How much sense can a house that you can’t even move? It’s obvious that there’s a design problem here, isn’t it?

Let’s continue with a similar example. Imagine changing the electrical installation when the bulb in your house exploded! So the large module (electrical wiring) should not be connected to the small module (bulb)! Both should be connected to the abstract grip (lamp veduy and bulb-). Moreover, how many watts of light bulb (detail), the lamp part of the lamp (abstract) is concerned? I do not think so.

Ok, these examples are enough i think:) Lets coding!

According to the scenario we will use in this example; You already have a web service, and this service uses the XML format for data sharing. Let’s first see a poorly designed structure and then discuss why this is bad.

Our code’s pretty good. It’s okay up here. However, after a day JSON (JavaScript Object Notation), a new data sharing format will be removed and you have to change the entire infrastructure. So do you think this architecture would be easy?

The high module in this architecture is the ProductService class. The low-level module is naturally the XMLConverter class. At this point, it is clear that the ProductService class is dependent on the XMLConverter class. Because when you decide to do data sharing in JSON format, the class you need to change will definitely be the ProductService. Yes, you will have to change the entire installation to replace the light bulb.

So how should we organize the architecture first? Here, I think you are aware that your large module’s Publish method is the main element. The Loosely Coupling approach will then combine the SRP principle and the ISP policy to incorporate the Convert method into a separate Interface.

And we must change our big module like this:

With this change, you can only get a new bulb when the bulb goes off. You can even wear fluorescent if you wish!

Well, if we want to work with this class (JSONConverter or XMLConverter) when we want ac what are we going to do? This is another article topic of Dependency Injection.

Yes my friends. Keep on reading this blog! We’ll meet you soon!

Do not forget to visit our programming memes pages! Click here!

PDF Creation Using Rotativa in ASP.NET MVC

In the .Net Framework, creating PDFs for reporting or other purposes often opens a business. However, Rotativa, which we can download from Nuget, makes our job very easy. It is great convenience that Rotativa can convert View or Partial Views to PDF.

Installing Rotativa in MVC

We can install with the “Install-Package Rotativa” command using the Package Manager console. The second way to install is Nuget. When the installation is complete, a folder called Rotativa is created in the root of your project.

Creating PDF with Rotativa

ViewAsPdf: The name of the class to create PDF based on View. Sample code is:

public ActionResult DownloadViewPDF()
{
    List<User> uList = GetUsers();    //get user list from db, json or etc.
    ViewAsPdf pdf = new ViewAsPdf("PdfView", uList);
    return pdf;
}

PdfView” is the name of View to be converted to PDF. uList is Model to be sent to View. So there is no difference from the return View () method. There are also ActionAsPdf, PartialViewAsPdf and UrlAsPdf classes available like ViewAsPdf. Their names explain all their functions.

In the example above, we can interfere with the many features of the PDF which will be created by the object named “pdf”. For example :

pdf.PageMargins.Left = 0;    //padding from left
pdf.FileName = "Deneme";     // name of the file
pdf.PageHeight = 200;    //height of page

Let me remind you that if there is a problem with PDF creation, the first permissions to be checked. An error can occur if the IIS user does not have access to the “Rotativa” directory in the root directory.

Do not forget to allow all users access to the folder in the root directory. Rotativa is really helpful for creating pdf files.

I think you should try!

Do not forget to visit our programming memes category! Click here