Friday, November 18, 2016

Brain Teaser - Introduction

This is the Introductory post of the Brain Teaser Series, where I will be optimising the same code using different C# features

Problem Statement: Optimise below code


    class Program
    {
        static void Main(string[] args)
        {

            Audi a = new Audi();
            a.Drive();  
            Benz b = new Benz();
            b.Drive();
            Console.Read();
        }
    }

    public class Audi
    {

        // Same functionality in Benz car too
        protected void Start()
        {
            Console.WriteLine("Car Started");
        }

        //Audi specific functionality
        protected void Move()
        {
            Console.WriteLine("Moving with the power of a 2000 CC Petrol engine");
        }

        //Audi specific functionality
        protected void ApplyBreak()
        {
            Console.WriteLine("Applied Power break with sensors");
        }

        public void Drive()
        {
            Start();
            Move();
            ApplyBreak();
        }
    }

    public class Benz
    {
        // Same functionality in Audi car too
        protected void Start()
        {
            Console.WriteLine("Car Started");
        }

        //Benz specific functionality
        protected void Move()
        {
            Console.WriteLine("Moving with the power of a 3000 CC Diesel engine");
        }

        //Benz specific functionality
        protected void ApplyBreak()
        {
            Console.WriteLine("Applied Power break with ABS");
        }

        public void Drive()
        {
            Start();
            Move();
            ApplyBreak();
        }
    }

The next post is gonna cover how the above code can be optimised using Inheritance.

No comments:

Post a Comment