Monday, December 28, 2020

Interfaces vs Abstract Classes with C# 8

Now with C# 8, we can provide implementation into the interfaces too then what is the point of the Abstract class? what is the difference? 
Here is my analysis.


Concepts

  • An interface is a contract that tells the client the class has an implementation of the required methods that means ILogger tells the client ConsoleLogger has implemented all the methods. But derived class is the extension of the Abstract class like ConsoleLogger extending the BaseLogger.
  • With the parent class, the derived class has to have a "is a" relation while it's not required with the interfaces.

Programmatically 

Well, on the surface after the default implementation functionality abstract class and interface seem the same but they are a lot different if you look closely.

  • The default implementation in interfaces works when no implementation is provided but with an abstract class, functionality could be extended calling super method, encapsulated using private methods, and also overridden like interfaces too.
  • Multiple interfaces can be implemented for a single class but only one parent class can exist.

But why default implementations anyway?

  • It helps extend an interface which is been implemented by lots of classes already.
  • Interface function could be reused inside interface, then no need to copy same code in every implementation. Suppose ILogger has methods LogError and LogWrite. LogError under the hood is using LogWrite anyway to write anyway then why provide the same implementation everywhere for LogError? 

Let's tackle elephant in the room, the diamond problem. if class A is the parent of class B and C both have the same child D then which implementation will be called when using an object of class D? That is one of the problems multiple inheritances doesn't exist in modern language and it is a pitfall developers tend to fall into if program is not designed carefully.

But here are the rules C# has implemented to keep developers safe.

  • Default implementation belongs to interface not class. That means

  
    public interface IA
    {
        public void Write() => Console.WriteLine("IA Written");
    }
    public interface IB
    {
       public void Write() => Console.WriteLine("IB Written");
    }
    public interface IC : IA, IB
    {
        
    }
    public class C : IC
    {

    }



    class Program
    {
        static void Main(string[] args)
        {
            IA c = new C();
            c.Write();  // prints IA Written

            IB d = new C();
            d.Write(); // prints IB Written

            IC e = new C();
            e.Write(); // compile time exception
            Console.ReadKey();

            C f = new C();
            f.Write(); // compile time exception
        }
    }
 
 
 

Sunday, July 19, 2020

MongoDB - A Dotnet View (For Beginners)

Concepts

  • NoSql Database
  • Database - Like SqlServer Databases
  • Collection - Like SqlServer Tables
  • Document - Like Table Rows
  • You don't need to define schema, columns or relations in MongoDb, It'll just work whatever you try to insert inside a collection.
  • Documents/Rows don't have to be consistent in same collection. One document can have large json with lots of attribute and other can just have single property totally unrelated to the first document.
  • You can't define relations, that means data will be redundant and repetitive. But each document will have data in itself. That benefits in fast crud operations. Thats why NoSql is for.
  • Its trade for speed vs space and consistency.
  • Create a new object or class and insert into the collection. If collection or database doesn't exist; It will create for you on insert.
  • It uses BSON object as backend. its just Json with different name.

Installation

  • You can use mongodb atlas -  Cloud hosted MongoDB on multiple platforms
  • Or You can install locally via this link. It'll give you MongoDB Compass (like SqlServer Management Studio for mongo) and Mongo Db Database. You should put mongo folder, usually located at C:\Program Files\MongoDB\Server\<Your Version>\bin, to environment variables to use shell.
  • After installation it'll probably require a reboot.
  • First time your compass should look like this
  • Click Connect, Leave Default localhost settings. It should work.
Yeaaah!. MongoDB is working on your local now. Have fun!.


Connecting Your local

  • Create an emtpy console app
  • Install MongoDB.Driver from Nuget Package Manager
  • Put this code in your Program.cs Main Function

var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("BookstoreDb");
_books = database.GetCollection<Book>("Books");

  • Create the Model

  • Resolve Imports and Debug to check you should get empty books
  
   public class Book
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }

        [BsonElement("Name")]
        [JsonProperty("Name")]
        public string BookName { get; set; }

        public decimal Price { get; set; }

        public string Category { get; set; }

        public string Author { get; set; }
    }
  
  
 
    _books.InsertOne(new Book() { Author = "Whoevery", BookName = "Clean Code",
    Category = "Programming", Price = 12 });
      

  • Above code should insert a document and now get should return some value
  • Now you know how to create database, collection and a document 
  • Go to compass; if you have connected Hit refresh. You should see your data now.