Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

base in C#

The base keyword in C# allows a subclass to access base (superclass) members.

All credit to Suresh Dasari of Tutlane (reference below) on explaining this so effectively in just a few steps of code.

What is shown here is the Details subclass overriding the Users base class' "GetInfo()" method and including the base behavior (Console.WriteLine("Name: {0}", name); ... Console.WriteLine("Location: {0}", location); - along with- some new behavior (Console.WriteLine("Age: {0}", base.age);). In this way members can be shared between subtypes and the type they inherit from- in constructors as well as elsewhere in the subclass.

 using System;  
 namespace Tutlane  
 {  
   // Base Class  
   public class Users  
   {  
     public string name = "Suresh Dasari";  
     public string location = "Hyderabad";  
     public int age = 32;  
     public virtual void GetInfo()  
     {  
       Console.WriteLine("Name: {0}", name);  
       Console.WriteLine("Location: {0}", location);  
     }  
   }  
   // Derived Class  
   public class Details : Users  
   {  
     public override void GetInfo()  
     {  
       base.GetInfo();  
       Console.WriteLine("Age: {0}", base.age);  
     }  
   }  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       Details d = new Details();  
       d.GetInfo();  
       Console.WriteLine("\nPress Enter Key to Exit..");  
       Console.ReadLine();  
     }  
   }  
 }  


Result

Reference: https://www.tutlane.com/tutorial/csharp/csharp-base-keyword

Regular Expressions

Regular expressions are a strings of (regex) code and matching (character) references used for finding patterns of characters within some defined contiguous string of characters (ie. forms validation, an IDE identifying opening and closing tags in markup code or a terminating semicolon in Java/C#). A more official definition describes regex as:
"In computing, regular expressions provide a concise and flexible means for identifying strings of text of interest, such as particular characters, words, or patterns of characters. Regular expressions (abbreviated as regex or regexp, with plural forms regexes, regexps, or regexen) are written in a formal language that can be interpreted by a regular expression processor, a program that either serves as a parser generator or examines text and identifies parts that match the provided specification."

 This diagram breaks down the gist of how an expression works- see the reference below for full list of matching modifiers and syntax

Having more than a passing familiarity with regex can be a tremendous help when doing any kind of development related to the identification of patterns in character/symbol data. When you understand how each component works you can very easily begin to build your own expressions to suit your particular application's pattern matching needs.

Below are some common regular expressions:

Alphanumeric Strings and Chars
^\w+$

Username (16 characters)
/^[a-z0-9_-]{3,16}$/

Hexadecimal ID
/^#?([a-f0-9]{6}|[a-f0-9]{3})$/

Email
/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/

URL
/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/

ipV4 Address
/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/

HTML Tag
/^<([a-z]+)([^<]+)*(?:>(.*)<\/\1>|\s+\/>)$/

XML Tags
Don't use Regex, use something like XPath


Just remember that the brackets are regex matching patterns, the curly braces are index positioners, the parens surround regex "capture groups" and the other syntax denotes flags for how much to match and other special conditions to be applied to the match/regex expression. Go here to practice and learn more: https://regexr.com/


The above illustrates Regex in 2 Capture Groups, One for alpha chars and the other for numeric chars


Reference: https://code.tutsplus.com/tutorials/8-regular-expressions-you-should-know--net-6149

The GOF Software Design Patterns at a Glance

If you are serious about developing software, read this book. It contains timeless concepts you should know well.

I. Creational Patterns
1. Abstract Factory - facilitates the creation of similar objects that share interface
2. Builder - dynamic SQL statements and other dynamically constructed code
3. Factory Method - custom way to construct an object (vs. normal/default class constructor)
4. Prototype create new instances by copying existing instances
5. Singleton - assurance of 1 and only 1 instance of an entity in an application

II. Structural Patterns
1. Adapter - a means of making an object compatible with another object via a common interface
2. Bridge - the decoupling of the adaptor/interface and the incompatible items (light switch w/fans)
3. Composite a group of objects treated the same way as a single instance of the same type of object
4. Decorator - adding new functionality to a class via subclass with new methods, props, etc.
5. Façade - simplified interface to a complicated backend
6. Flyweight - reuse of an object instance to create more instances of the same type
7. Proxy - entity serving as a stand-in for the real thing. Often a wrapper for a more complex class.

III. Behavioral Patterns
1. Chain of Responsibility - source command is served by multiple processes with distinct linear roles.
2. Command - encapsulate a request as an object, works great with HttpRequest and user actions
3. Interpreter - dynamic culture and localization settings to display appropriate UI text
4. Iterator - centralize communication among objects that have a common interface (ie. TV remote)
5. Mediator - centralize complex communication and control among related objects
6. Memento - persist and recall object state
7. Observer - a central watcher picks up picks up broadcast messages from everywhere it observes (Twitter)
8. State - persists object state and can react in different ways according to attributes of its current state
9. Strategy - enabling an object to change/choose algorithm(s) at runtime
10. Template Method - great for interfaces; design skeleton w/base needs; allow concretes to implement details
11. Visitor - code execution varies according to visiting object (ie. keyboard keys, mice clicks, WiFi Routers, etc.)


References:

https://softwareengineering.stackexchange.com/questions/234942/differentiating-between-factory-method-and-abstract-factory

https://www.cs.cmu.edu/~charlie/courses/15-214/2016-spring/slides/24%20-%20All%20the%20GoF%20Patterns.pdf

https://quizlet.com/129434321/design-patterns-gof-in-1-sentence-flash-cards/

SOLID

"These principles, when combined together, make it easy for a programmer to develop software that are easy to maintain and extend." -Robert 'Uncle Bob' Martin

S Single-Responsibility - objects should only serve one purpose

O Open-Closed - types should be open to extending capabilities, closed to base changes

L Liskov Substitution - subtypes of base types should produce objects compatible with base

I Interface Segregation - client types do not have to depend on unused interface methods

DDependency Inversion - rely on abstract templates, not prescriptive/restrictive concretes



Reference: https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design

Serialization and Deserialization in .NET

Definition: "Serialization is the process of going from in-memory representation of an object to a disk-based format which can be in any form like binary, JSON, BSON, XML, etc. Deserialization is the reverse process, in which you recreate an object from disk storage and store it in RAM"

Purpose: "This is mainly used in document store, ORM style databases, storing config files etc. The main benefit is the speed in populating an object as opposed to querying multiple tables in the case of database storage."

Serialization saves object state so that the object can be persisted and recreated without the need for inserting/updating one or more records across several tables in an RDBMS.

.NET Example: The following is an example of serialization of a simple C# object to XML, and deserialization from the XML back into the same C# object:

 using System;  
 using System.IO;  
 using System.Xml;  
 using System.Xml.Serialization;  
 namespace SerializationDeserializationSimpl  
 {  
   class Program  
   {  
     static void Main(string[] args)  
     {  
       Album album = new Album(){ AlbumId = 1, AlbumName = "James Vincent McMorrow", ArtistName="Post Tropical", CurrentBillboardRank=1045, HighestBillboardRank=102, SoundScanUnits=207000};  
       Console.WriteLine("Original object in memory:");  
       album.WriteSummary();  
       Console.WriteLine("Press Enter to Serialize this object to XML");  
       Console.ReadLine();  
       //Serialize it to XML file (disk) form  
       var serializer = new XmlSerializer(album.GetType());  
       using (var writer = XmlWriter.Create("album.xml"))  
       {  
         serializer.Serialize(writer, album); //serializes to XmlWriter for later deserialization back into Album obj  
         var sWriter = new StringWriter();  
         serializer.Serialize(sWriter, album); //serializes to StringWriter for display in the Console via WriteLine  
         Console.WriteLine(sWriter.ToString());  
         Console.WriteLine("------------------------------------");  
         Console.WriteLine("------------------------------------");  
         Console.WriteLine("------------------------------------");  
       }  
       Console.WriteLine("Serialization to XML sucessfull!");  
       Console.WriteLine("------------------------------------");  
       album.WriteSummary();  
       Console.WriteLine("------------------------------------");  
       Console.WriteLine("Press Enter to Deserialize from the XML");  
       Console.ReadLine();  
       //Deserialize from that XML back into object (RAM) form  
       using (var reader = XmlReader.Create("album.xml"))  
       {  
         var albumDeserialized = (Album)serializer.Deserialize(reader);  
         Console.WriteLine("Deserialization from XML sucessfull!");  
         Console.WriteLine("------------------------------------");  
         albumDeserialized.WriteSummary();  
         Console.WriteLine("------------------------------------");  
         Console.WriteLine("Press any key to exit");  
         Console.ReadLine();  
       }  
     }  
   }  
   public class Album  
   {  
     public int AlbumId;  
     public string AlbumName;  
     public string ArtistName;  
     public int SoundScanUnits;  
     public int CurrentBillboardRank;  
     public int HighestBillboardRank;  
     public void WriteSummary()  
     {  
       Console.WriteLine("AlbumId: " + AlbumId);  
       Console.WriteLine("Album: " + AlbumName);  
       Console.WriteLine("Artist: " + ArtistName);  
       Console.WriteLine("SoundScanUnits: " + SoundScanUnits);  
       Console.WriteLine("CurrentBillboardRank: " + CurrentBillboardRank);  
       Console.WriteLine("HighestBillboardRank: " + HighestBillboardRank);  
     }  
   }  
 }  
Program.cs

Console Output

GitHub: https://github.com/Radagast27/SerializationDeserializationSimpl

Quote Attribution: Mehdi Gholam

References:

https://stackoverflow.com/questions/11447529/convert-an-object-to-an-xml-string?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

https://www.codeproject.com/Questions/277995/What-is-serialization-and-deserialization-in-cshar

https://stackoverflow.com/questions/3356976/how-to-serialize-deserialize-simple-classes-to-xml-and-back

Patterns Simpl: Facade

Simplified interface to the overall functionality of a complex subsystem.

For example, a mortgage application is the facade to the subsystem of more complex entities: credit, bank and loan. The .NET Framework is an interface to the more complicated subsystems that lie beneath System.IO, System.Data, etc.



Reference: http://www.dofactory.com/net/facade-design-pattern

Patterns Simpl: State Machine

State Machine is simply an object design that keeps track of the various states that an object can assume. For example:


Patterns Simpl: Template Method

This pattern simply descibes the design of an interface or base class (if implementation details common to all child objects). The base interface or abstract/virtual class is the "Template". 




Patterns Simpl: Abstract Factory

This pattern describes the creation of new objects through the assembly of various interchangeable parts defined by interfaces.





Patterns Simpl: Proxy

Provide a surrogate or placeholder for another object to control access to it.



The above example illustrates how a paper check is proxy for a transaction on your bank account. Another example is thumbnail images of videos on Fb or Twitter which, when you click on them, open up the more resource-hungry actual video content.

Reference: https://sourcemaking.com/design_patterns/proxy

Patterns Simpl: Iterator

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

The essence of this pattern is that when implemented correctly, you can easily iterate through a collection of complex objects in a uniform manner (ie. IEnumerator, IEnumerable in .NET) without having to know the details of the type of object in the collection.





Reference: https://www.google.com/searchq=iterator+pattern+defined&oq=iterator+pattern+defined

Patterns Simpl: Observer

The Observer defines a one-to-many relationship so that when one object changes state, the others are notified and updated automatically.



Referencehttps://sourcemaking.com/design_patterns/observer

Patterns Simpl: Adapter


Adapter pattern works as a bridge between two incompatible interfaces.




Patterns Simpl: Singleton

It is imperative to ensure atomicity (indivisible-ness) for certain "master" objects in your applications.

Singleton ensures the existence of 1 and only 1 object instance (or version/representation) of an application entity- at all times.


Some examples of Singleton:

If your program somehow winds up with 2 globally-scoped objects of a class that handles bank deposits, let's hope our account gets updated by the one with a larger dollar amount!

In Java, there is a single instance of java.lang.Runtime. If there were more than 1 language instance to interface with the Java application environment, you can see how problems would unfold.

In .NET applications, an application .config file serves as a single source of configuration values.

Log Managers should have 1 and only 1 instance, lest our log files become far too complex to sift through when we are tracking down an application issue.




Reference: https://stackoverflow.com/questions/3192095/where-exactly-the-singleton-pattern-is-used-in-real-application

Patterns Simpl: Dependency Injection

"In software engineering, dependency injection is a technique whereby one object supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it."

A better quote for the initiated to DI/IoC would be:

"Dependency Injection was originally called Inversion of Control (IoC) because the normal control sequence would be the object finds the objects it depends on by itself and then calls them. Here, this is reversed: The dependencies are handed to the object when it's created. This also illustrates the Hollywood Principle at work: Don't call around for your dependencies, we'll give them to you when we need you." -javaworld.com

In .NET, .resx resource files that contain different inputs based on the culture settings of the client is an example of DI.

Another simple and clear example of Dependency Injection in action is in ASP.NET Core Authentication.

The built-in Authentication Controller and the Startup.cs Configure() method are designed to work with an interface and not one specific/concrete class of authentication provider. It uses IAuthenticationSchemeProvider which provides a generic and flexible structure that leaves the specific type of authentication up to the developer(s) (Google, Microsoft, Twitter, GitHub, Instagram, Facebook, etc.).

These different authentication types/providers are what the IAuthenticationSchemeProvider depends on to handle the authentication process for ASP.NET Core applications.

The developer injects the dependency(s) of his or her choice.

A common form of Dependency Injection is Localization of display text in applications

Loose coupling is key for interoperability with other apps and services, if your dependencies are more generic, your system is more extensible