Tuesday, December 22, 2020

Abstract, Virtual, Static in C#

Abstract Class
- Abstract classes are the way to achieve abstraction in C#.
- A class that is declared by using the keyword abstract is called an abstract class.
- An abstract class may or may not have abstract methods i.e. it can contain both abstract methods and non-abstract (concrete) methods. But if a class contains an abstract method then it must be declared as abstract.
- We can define all static and non-static members including properties, fields, indexes as well.
- The abstract class cannot be instantiated directly, we need to create the object for its child classes to consume an abstract class.
- Class containing abstract method cannot be instantiated. It can only be inherited.
- An abstract class can have a constructor. We would provide a constructor for an abstract class if we want to initialize certain fields of the abstract class before the instantiation of a child-class takes place. An abstract class constructor can also be used to execute code that is relevant for every child’s class. This prevents duplicate code.

Abstract method
- A method which is declared abstract and has no body or any implementation is called abstract methods.
- It can be only declared inside the abstract class only. Its implementation must be provided by derived classes or sub-classes. This is achieved by overriding that method and it is mandatory.

Virtual method
- Virtual methods are used for an implementation of the type-based polymorphism.
- Virtual keyword is used to distinguish it from other types of methods.
- The class containing virtual method can be instantiated.
- Virtual methods are not compulsory to be overridden.
- A virtual method has an implementation and its derived class does not have to implement it again (but can replace the original implementation).
- There is a restriction when using a virtual modifier. You cannot use this modifier along with static or abstract or override modifiers.

Static Class
- A class that is declared by using the keyword static is called an static class.
- In static class, you are not allowed to create objects.
- A static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.
- Because there is no instance variable, you can directly access the members of a static class by using the class name itself.
- It contains only static members.
- It cannot contain Instance Constructors, However, they can contain a static constructor.
- Static classes are sealed and therefore cannot be inherited.
- They cannot inherit from any class except Object.

Static Member
- A non-static class can contain static methods, fields, properties, or events.
- The static member is always accessed by the class name, not the instance name.
- Static methods can be overloaded but not overridden, because they belong to the class, and not to any instance of the class.
- Declare static class members by using the static keyword before the return type of the member.
- You use static methods when the method does not need to access any non-static class elements such as properties, events, or methods in order to do it's job.

Friday, May 15, 2020

Object Oriented Programming (OOP) in a Nutshell


Before understanding what is Object oriented programming (OOP), it is very important to know the difference between an object and a class. I will be using C# syntax's to show examples.

The two most important words in Object Oriented Programming are Object and Class. A class is a blueprint of an object. You can think of a class as a concept, and the object is the embodiment of that concept.Though they are often used interchangeably but they are not the same thing. You need to have a class before you can create an object.

Object is not similar to Class (Object != Class)
Class is a programming code that is created/defined using keyword class and has properties and methods. Properties and methods together are known as members of a class.

Fig: Person Class with properties : Name and Age

Objects are the basic units of object oriented programming. An Object is an instance of a class and it is created/defined using new keyword which is assigned/referenced to a variable. This variable references the resulting object , so, it is known an object variable (i.e person).

   var person = new Person();
   person.Name = 'Anup';

Object variable is used to get or set any of the properties identified in the class. As shown above, object variable (person) is being used to set a property(Name) is to 'Anup'. It holds the state of the object, i.e, it retains the values of its properties and use it to call the methods identified in the class.

Fig: Class vs. Object (Example using Car)

Example (Class vs Object)
So, let's say you want to use a person in your program. You want to be able to describe the person and have the person do something. A class called 'person' would provide a blueprint for what a person looks like and what a person can do. To actually use a person in your program, you need to create an object. You use the Person class to create an object of the type 'person.'  Logically, you would expect a person to have a name. This would be considered a property of the person. You could also expect a person to be able to do something, such as walking or driving. This would be considered a method of the person. Now you can describe this person and have it do something.

Once you have your objects, they can interact with each other to make something happen. Let's say you want to have a program where a person gets into a car and drives it from A to B. You would start by describing the objects, such as a person and car. That includes methods: a person knows how to drive a car, and a car knows what it is like to be driven. Once you have your objects, you bring them together so the person can get into the car and drive.

A single class is used repeatedly to create multiple object instances. Consider the example of where you don't want to use just one person but 100 people. Rather than describing each one in detail from scratch, you can use the same person class to create 100 objects of the type 'person.' You still have to give each one a name and other properties, but the basic structure of what a person looks like is the same.

Once you have created objects, you want them to be able to do something. This is where methods come in. A method in object-oriented programming is a procedure associated with a class. A method defines the behaviour of the objects that are created from the class. Another way to say this is that a method is an action that an object is able to perform. The association between method and class is called binding. Consider the example of an object of the type 'person,' created using the person class. Methods associated with this class could consist of things like walking and driving. Methods are sometimes confused with functions, but they are distinct.

function is a combination of instructions that are combined to achieve some result. A function typically requires some input (called arguments) and returns some results. For example, consider the example of driving a car. To determine the mileage, you need to perform a calculation using the distance driven and the amount of fuel used. You could write a function to do this calculation. The arguments going into the function would be distance and fuel consumption, and the result would be mileage. Anytime you want to determine the mileage, you simply call the function to perform the calculation.

How does function differ from a method?
function is independent and not associated with a class. You can use this function anywhere in your code, and you don't need to have an object to use it. 

Now, what if you were to associate the function with an object of the type 'car?' For example, you want to be able display the mileage of the car on the dashboard. In this case, the mileage calculation has become a method because it is a procedure associated with the car's class. Every time you create a new object of the type 'car' using the car class, this method will be part of the object. The action the car is now able to perform is to calculate mileage. It is the same calculation as performed by the stand-alone function but is now bound to the car.

Object Oriented Programming (OOP)
Now we know the difference between a class and an object, lets define Object oriented programming, also known as OOP.

OOP is an approach to designing and building applications that are flexible, natural, well-crafted, and testable by focusing on objects that interact cleanly with one another. To build an application using object oriented programming principles, use the following techniques:

- Identifying classes
- Separating responsibilities
- Establishing relationships
- Leveraging reuses

Identifying classes
When given a requirement for a new application or a feature, start by identifying the classes from the requirements or specification. OOP represents the entities and concepts of an application as a set of classes. Each class has properties that define the data each object will manage. Each class has methods, which are the actions and behaviours that each object can perform. In short,
  • - Represents Business Entities and set of classes
  • - Defines Properties (Data)
  • - Defines methods (actions/behaviour)
Separating responsibilities
Analyse the classes you identified and separate responsibilities as needed. Minimise coupling by ensuring each class has a single purpose. Maximise cohesion by reviewing the properties and methods of each class to confirm each one belongs to that class. Single-focus classes simplify maintenance and improve test-ability. In short,
  • - Minimises coupling 
  • - Maximises cohesion
  • - Simplifies maintenance
  • - Improves test-ability
 Establishing relationships
The relationships between the classes define how the objects created from those classes work together to perform the operations of the application. In short,
  • - Define how objects work together to perform the operations of the application
Leveraging reuses
The power of OOP lies in its promise of reuse. By extracting commonality among a set of classes into a separate class, you have more reusable code. There are several ways to achieve reuse, including extracting common functionality into a base class using inheritance.  Extensive reuse of existing classes not only shortens development time, it also leads to more robust applications. Reuse through a component library of general purpose classes and reuse through interfaces. In short
  • - Involves extracting commonality
  • - Building reusable classes and components 
  • - Defining Interfaces
Four Pillars of OOP
These four pillars are the foundation of OOP. In short,
  • Abstration : It describes an entity in simple terms, ignoring the irrelevant details. It reduces complexity by focusing only on what is important for the purpose of this specific application. 
  • Encapsulation :  It allows for hiding the data and the implementation within the class. The data is stored in backing fields and accessible to the rest of the application through property getters and setters. The code is only accessed through the class interface.
  • Inheritance: It allows derived, or child, classes to reuse all the code in the base or parent class. 
  • Polymorphism :  It means many forms. A base class can define a method and any derived class can override that method to provide its own definition and implementation, basically, providing its own shape for the method.

Wednesday, August 7, 2019

How To Hide iPhone or iPad Keyboard When Tapping On The Screen?

To hide or dismiss the keyboard on iPad or iPhone safari browser, you need to lose the focus on your input.
document.activeElement.blur();
With this line you remove the focus and the keyboard disappear.

To be able to hide or dismiss iPhone or iPad keyboard when tapping on the screen, you need to add event on your body. It is possible to recognize touch events on the iPad's Safari browser using jQuery. If you're using jQuery 1.7+ it's even simpler to fix the problem as follows:
$(document).ready(function () {
    $('body').on({
      touchstart: function() {
        if (document.activeElement) {
          document.activeElement.blur();
        }
      }
    });
 });
This detects when you tab the body and then blurs it, so the keyboard will disappear.

Friday, June 28, 2019

How To Scroll To The Top of The Page in React and Typescript?

Issue:
When navigating into another page, its position will remain same like the previous page but you want to scroll to the top of new routed/rendered page.

Solution
I usually put an empty div on top of that page, and gave it a ref, so that, later I can use the scrollIntoView() method to scroll the page into that div.

In TypeScript, you'll have more extra steps to do so, seems to be annoying, but it's actually very helpful because you can take advantages of the type system. First, define a ref like this:
class YourComponent extends React.Component {
  private scrollAnchorRef: any;

  //or private scrollAnchorRef: RefObject<HTMLElement>

  constructor(props) {
    super(props);
    this.scrollAnchorRef = React.createRef(); // Create a ref object 
  }

  render() {
    <div ref={this.scrollAnchorRef}>
      ...
    </div>
  }
}

I have used any type instead of a generic HTMLElement type (recommended) when defining a ref, because it will help the compiler narrow down the type so you'll have better suggestion in the next step.

Now, when you finish rendering/loading page and want to scroll to the top of element, you can do:
  this.scrollAnchorRef.current.scrollIntoView({ block: 'start', behavior: 'smooth' })
And you'll get an error message says: TS2531: Object is possibly 'null'

The reason is, RefObject.current has the type of T | null, because React will actually set an element's ref into null when it re-render, and if you're trying to scroll during re-render, you'll run into problems.

The solution is simple, add an existent check:
 const anchor = this.scrollAnchorRef;
 if (anchor) {
   anchor.current.scrollIntoView({ block: 'start', behavior: 'smooth' }); 
}
Here is the complete solution.

class YourComponent extends React.Component {
  private scrollAnchorRef: any;

  constructor(props) {
    super(props);
    this.scrollAnchorRef = React.createRef(); // Create a ref object 
  }

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      const anchor = this.scrollAnchorRef;
     if (anchor) {
        anchor.current.scrollIntoView({ block: 'start', behavior: 'smooth' }); 
     }
    }
  }

  render() {
   <div ref={this.scrollAnchorRef}>
      ...
   </div>
  }
}

This is how type saved your butt when you work with React and Typescript.

Reference: React, TypeScript and scrollInToView

Monday, May 13, 2019

What Is withRouter And How And When To Use It?

withRouter
You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

Usage of withRouter
If you want that your component will receive Router Props, but don't want to wrap it in <Route component={Some} />. You can just use withRouter function to connect component to the Router, without additional manipulations or jsx tags wrapping. You can just export default withRouter(component)

Explanation/Example
When you include a main page component in your app, it is often wrapped in a component like this:
 <Route path="/movies" component={MoviesIndex} />
By doing this, the MoviesIndex component has access to this.props.history so it can redirect the user with this.props.history.push

Some components (commonly a header component) appear on every page, so are not wrapped in a :
 render() {
   return (<Header />);
 }
This means the header cannot redirect the user.

To get around this problem, the Header component can be wrapped in a withRouter function when it is exported as below:
 export default withRouter(Header)
This gives the Header component access to this.props.history, which means the header can now redirect the user.

Refs: REACT TRAINING / REACT ROUTER / withRouter

Thursday, April 4, 2019

How To Sort Array By Name Or Date In Javascript?

Suppose you have an array users. You need to sort the array by name or date.
var users = [
  {id: 1, firstName: 'Anup', created_date: Mar 12 2012 10:00:00 AM}, 
  {id: 2, firstName: 'Tom', created_date: Mar 8 2012 08:00:00 AM}
];
To sort the array of objects by created_date
Turn your strings into dates, and then subtract them to get a value that is either negative, positive, or zero.
Example:
 users.sort((a, b) => new Date(b.created_date) - new Date(a.created_date));   
To sort the array of objects by firstName
Suppose you have an array users. You may use users.sort and pass a function that takes two arguments and compare them (comparator).
It should return
• something negative if first argument is less than second (should be placed before the second in resulting array)
• something positive if first argument is greater (should be placed after second one)
• 0 if those two elements are equal.

In our case if two elements are a and b, we want to compare a.firstname and b.firstname. When sorting strings toLowerCase() is very important - capital letters could affect your sort.
Example:
users.sort((a, b) => a.firstName.toLowerCase() !== b.firstName.toLowerCase() ? a.firstName.toLowerCase() < b.firstName.toLowerCase() ? -1 : 1 : 0);
If compared strings contain unicode characters you can use localeCompare function of String class like the following:
users.sort((a, b) => a.firstname.toLowerCase().localeCompare(b.firstname.toLowerCase()));

Monday, April 1, 2019

How To Solve Mongo - couldn't connect to server 127.0.0.1:27017 error?

Problem:
[js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:257:13
@(connect):1:6

Solution
Normally this caused because you didn't start mongod process before you try starting mongo shell.

Start mongod server
 mongod
Open another terminal window and start mongo shell
 mongo