<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[ALPHA Codes]]></title><description><![CDATA[ALPHA Codes]]></description><link>https://alphac0des.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 07 Nov 2026 20:33:19 GMT</lastBuildDate><atom:link href="https://alphac0des.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Cookie, Session & Tokens- What are they?]]></title><description><![CDATA[Cookie*- Maintain the active state of the browser by storing a bit of data between the **server and the client** with every request.* Session*- Record the…]]></description><link>https://alphac0des.hashnode.dev/cookie-session-tokens-what-are-they</link><guid isPermaLink="true">https://alphac0des.hashnode.dev/cookie-session-tokens-what-are-they</guid><category><![CDATA[Programming Blogs]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[React]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Mukul Attavania]]></dc:creator><pubDate>Tue, 06 Dec 2022 19:31:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1670354824028/st3_hOg8F.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<hr />
<p><strong>C<em>ookie*</em></strong>- Maintain the active state of the browser by storing a bit of data between the<em> **</em>server<strong><em> </em>and the<em> </em></strong>client<em>** </em>with every request.*</p>
<p><strong>S<em>ession*</em></strong>- Record the<em> **</em>server<strong><em> </em>and<em> </em></strong>client<strong><em> </em></strong>session state<em>**</em>.*</p>
<p><strong>T<em>oken-</em></strong> <em>A random</em> <strong><em>string</em></strong> <em>generated by the</em> <strong><em>server*</em></strong>.*</p>
<p><em>This article is tailored for those who are looking for a basic understanding of what sessions, tokens, and cookies are, how they work, and why they exist.</em></p>
<p>When you log into a website, you declare who you are (<strong>identification</strong>). Your identity is verified (<strong>authentication</strong>), and you are granted the necessary permissions (<strong>authorization</strong>). Many solutions have been proposed in the past, and the <strong>list keeps growing</strong>.</p>
<hr />
<h3 id="heading-authentication"><strong>Authentication</strong></h3>
<p>Authentication is the act of <strong>verifying</strong> user <strong>credentials</strong> in terms of either <strong>correctness</strong> or <strong>time</strong>.</p>
<ul>
<li><p><strong>Correctness</strong>: The user credentials are verified based on <strong>existing details</strong>. At the sign-in request, an authentication token is assigned to the user. It will be used to authorize the user and authenticate subsequent interactions with the application.</p>
</li>
<li><p><strong>Time</strong>: The authentication token assigned to the user is only valid for a specific period of time. If the token becomes invalid, the user needs to be re-authenticated before access can be granted.</p>
</li>
</ul>
<blockquote>
<p>The term “<strong>authentication token</strong>” is used here to describe any form of authentication credential that might be implemented by the application, not explicitly an access token.</p>
</blockquote>
<h3 id="heading-why-use-authentication"><strong>Why use authentication</strong></h3>
<p>There are two reasons why authentication is necessary to allow full access to an application:</p>
<ul>
<li><p>Authentication establishes the identity of the user and verifies that the user is who (or what) it says it is. Authentication protects your resources by denying access to unauthenticated users.</p>
</li>
<li><p>Authentication gives each user a distinct identity, protecting your data and theirs. Applications that require users to create an account give each user a unique profile, which is what determines the data shown to the user.</p>
</li>
</ul>
<p>For example, PayPal or any payment portal requires users to sign in before displaying their account balance and transactions.</p>
<p>Generally, the process works like this:</p>
<ul>
<li><p>You sign in.</p>
</li>
<li><p>The server verifies your sign-in details and assigns you an authentication token.</p>
</li>
<li><p>The authentication token is used to make a request to your homepage that displays your unique dashboard.</p>
</li>
</ul>
<blockquote>
<p>Both <strong>session cookies</strong> and <strong>access tokens</strong> allow users to make requests to the <strong>server</strong> <strong>without</strong> needing to <strong>re-authenticate at each request</strong>.</p>
</blockquote>
<hr />
<h3 id="heading-sessions"><strong>Sessions</strong></h3>
<p>When thinking of building out a website, a session is all interactions made by a user within a timeframe. This time could be set to be a certain period before the session expires, or even until the user closes out the webpage. A session could include a variety of activities, such as searches, scrolling, clicking through links, or even filling out web forms. It can be anything if it represents the time a visitor spends on the website. Any activity on that website is recorded through the session ID.</p>
<p>A session ID is used to store the data server-side. However, session IDs are also used for users’ privacy, as the ID can be passed instead of login or other sensitive information. By gathering information, data on how the website is used can be viewed. This information aids in creating better user experiences, which may even be personalised and tailored to the users. That session ID is still tied to a timeframe, however, so at some specified point, it will expire.</p>
<p>When we think about a session expiring, this means that the user has exceeded the duration that the developer-defined in their code. Sessions can be brief periods, such as how a bank will timeout if you are inactive for more than a few minutes, or they could be set as a longer period, such as an entire day. Inside the session, information from the first arrival until the session ends is recorded. Because a session refers to a certain duration of time, a single user can have multiple sessions within a short period. For example, if we think of the banking example, after a period of inactivity the page times out and logs you out. But if it does log you out, you could log back in almost right away, which would create a new session. Another example is that a computer can open multiple tabs. This means you could be looking at a series of different websites, all of which are considered sessions for the different websites. But what if you decide to open a page on the same website in a new tab or new window? Would that generate a new session ID? Not exactly. That’s where <strong>cookies</strong> come in.</p>
<hr />
<h3 id="heading-cookies"><strong>Cookies</strong></h3>
<p>If information about your session is going to be stored, something must temporarily retain that data. A cookie is a small file that stores pieces of data gathered in a session. For example, when segments, addresses, or passwords are automatically filled in, it is because there is a cookie holding that information. It is also what can be gathered from a session to let the website see where you clicked or what you did during your session. Cookies allow you to stay logged in even if you exit the page.</p>
<p>As you’ve likely seen a thousand times when visiting a website, you can choose to “allow cookies” for a website or to ignore them when prompted. This means you can choose to not allow those cookies. But that does not mean something will not collect data. If you check your browser, it collects cookies as well as makes a cache of your visited websites. You can choose to clear those, but you may find yourself having to fill out your usernames that are otherwise usually saved. The cookies found on <strong>websites</strong> are <strong>first-party cookies</strong>, which are used to track just your session on the website to tailor/personalise your visit.</p>
<p>If your Facebook ads are looking suspiciously close to your Google searches, you may have found third-party ads. <strong>Third-party ads</strong> are typically <strong>stored</strong> inside <strong>cookies</strong>, and sometimes they can be enabled without even clicking on the ad. These are the types of cookies that draw privacy concerns. They can track not only the activity on the website you got them from, but they can track your browsing history in general.</p>
<p>One even more difficult third-party cookie is a <strong>zombie cookie</strong>. They are more difficult because they are often <strong>invisible</strong>, and even after being <strong>deleted</strong>, they can <strong>reappear</strong>.</p>
<p><strong>Stateful cookies</strong></p>
<p>Stateful cookies contain a <strong>pointer</strong> to a <strong>database</strong> <strong>record</strong> that <strong>stores</strong> the <strong>session</strong> <strong>information</strong>.</p>
<p><strong>Pros</strong>:</p>
<ul>
<li><p>Have no limitations on the amount of session information stored.</p>
</li>
<li><p>Can easily clear a user’s session -just remove the record from the database.</p>
</li>
</ul>
<p><strong>Cons</strong>:</p>
<ul>
<li><p>Requires a database to store the session data (but most web applications already have this).</p>
</li>
<li><p>Increases latency because you have to make database calls to read the session (and sometimes write it) for each HTTP request a user makes.</p>
</li>
</ul>
<p><strong>Stateless cookies</strong></p>
<p>Stateless cookies are self-contained; they include all session information that you need (for authenticated users, the user ID) and reside on the client. To prevent external tampering, stateless cookies should be encrypted (or at least signed).</p>
<p><strong>Pros</strong>:</p>
<ul>
<li><p>Reduces latency because you don’t have to call a database.</p>
</li>
<li><p>They require little storage</p>
</li>
<li><p>They reduce manipulation by client-side JavaScript</p>
</li>
<li><p>Cookies use the same session across subdomains</p>
</li>
</ul>
<p><strong>Cons</strong>:</p>
<ul>
<li><p>Makes it difficult to revoke a session, because there is no record in a database you can delete, you’ll need to find other methods to forcefully clear a session.</p>
</li>
<li><p>If using multiple web servers, must make sure all servers have the key to encrypt/decrypt or sign the cookie.</p>
</li>
<li><p>Not good for API authentication</p>
</li>
<li><p>Cross-site request forgery attacks (XSRF or CSRF)</p>
</li>
</ul>
<p>Cookies aren’t the only way to store session IDs; other options include URLs and form fields. Cookies are more secure than those two, but how secure are cookies?</p>
<ul>
<li>Cookies are only secure in an HTTPS connection. Enforcing the Secure flag ensures that cookies are only sent via an encrypted HTTPS connection. The use of HTTPS prevents disclosure of session ID in person-in-the-middle (MITM) attacks.</li>
</ul>
<p>While cookies can be made secure by setting the appropriate attributes and following best practices, they can also be made insecure by neglecting these steps.</p>
<p>Because of these other types of cookies and the chance for security breaches, many people opt out of all cookies. <strong>Privacy can be more important than the ease of login</strong>. But what if you’re designing a website and all this cookie talk has you nervous? What’s the solution to have “<strong>sessions</strong>” without the need for “<strong>cookies</strong>”? That’s where <strong>tokens</strong> come in.</p>
<hr />
<h3 id="heading-tokens"><strong>Tokens</strong></h3>
<p>Tokens are a self-contained and compact way to securely transfer sensitive information between two parties. The composition of a token includes the header, which defines the type and algorithm used, the payload, which carries the metadata from the user much like a cookie would gather, and a signature, which is used to verify the identity of the sender. In this transmission type, the algorithm is used to secure the information by encoding it. It also does not require the use of cookies, because a token can be stored in Web Storage instead. This is either local storage or session storage. If a token is tampered with, it can be either revoked or blacklisted, which furthers its security.</p>
<p>In a session, a server must store the state, for example, if it is still active and ongoing. With tokens, the state is not stored. It is self-contained and therefore contains all the required information for authentication.</p>
<p>An example of a popular token system is JSON Web Tokens (JWT). A JSON Web Token is encoded using Base64, but this does not mean they are encrypted. The message is available for viewing, but only if they have the secret. There is a secret to decode the message, and without the secret or with the incorrect secret the message would be useless.</p>
<p><strong>Process:</strong></p>
<ol>
<li><p>The server generates a token value by using a hashing algorithm and then returns the token value to the client when the user logs in successfully for the first time.</p>
</li>
<li><p>After the client gets the token value, it stores it locally</p>
</li>
<li><p>When the client requests again, it attaches the token value to the request and sends it to the server</p>
</li>
<li><p>After the server receives the client’s request, it will extract the token value and compare it with the token value stored locally on the server</p>
</li>
<li><p>Token value from client = Token value from the server-The user is logged in successfully</p>
</li>
<li><p>Token value =/ token value from the server — The original login information has expired, and the user is required to log in again</p>
</li>
<li><p>No such token value — the login is not successful</p>
</li>
</ol>
<p><strong>Tokens Are Signed, Not Encrypted</strong></p>
<p>A JSON Web Token is comprised of three parts: the header, payload, and signature. The format of a JWT is <strong>header.payload.signature</strong>.</p>
<ul>
<li><p>JWTs are cryptographically signed and base64-encoded. They’re only secure when they aren’t exposed, so they should be treated like passwords.</p>
</li>
<li><p>A JWT can be viewed but not manipulated on the client side. You can take your token to <a target="_blank" href="http://jwt.io">jwt.io</a>, choose the algorithm you used to sign, and see the data. You just can’t tamper with it because it’s issued on the server.</p>
</li>
<li><p>The lifespan of a JWT should be kept short to limit the risk caused by a leaked token.</p>
</li>
</ul>
<pre><code class="lang-plaintext">{
  "sub": "67554887",
  "name": "Alpha",
  "admin": true
}
</code></pre>
<pre><code class="lang-plaintext">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwi
bmFtZSI6IkFkbyBLdWtpYyIsImFkbWluIjp0cnVlLCJpYXQiOjE0NjQyOTc4ODV9.
Y47kJvnHzU9qeJIN48_bVna6O0EDFiMiQ9LpNVDFymM
</code></pre>
<hr />
<h3 id="heading-what-is-sso">What is SSO?</h3>
<p><strong>Single sign-on (SSO)</strong> is a centralized session and user authentication service in which one set of login credentials can be used to access multiple applications. Its beauty is in its simplicity; the service authenticates you on one designated platform, enabling you to then use a variety of services without having to log in and out each time.</p>
<p>In the most common arrangement, the identity provider and service provider establishes a trust relationship by exchanging digital certificates and metadata and communicating with one another via open standards such as Security Assertion Markup Language (SAML), OAuth, or OpenID.</p>
<h3 id="heading-single-sign-on-example">Single sign-on example</h3>
<p>Imagine you’re the user in an environment with a single sign-on and you’re trying to get access to some resource on a server. The sequence of events for how SSO works go like this:</p>
<ol>
<li><p>You attempt to access the service provider- again, this generally is an application or website you want to access.</p>
</li>
<li><p>As part of a request to authenticate the user, the service provider sends a token that contains some information about you, like your email address, to the identity provider, a role played by your SSO system.</p>
</li>
<li><p>The identity provider first checks to see whether you’ve already been authenticated, in which case it will grant you access to the service provider application and skip to step 5.</p>
</li>
<li><p>If you haven’t logged in, you’ll be prompted to do so by providing whatever credentials the identity provider requests.</p>
</li>
<li><p>Once these credentials have been validated, the identity provider will send a token back to the service provider, confirming that it’s authenticated with you.</p>
</li>
<li><p>This token is passed through your browser to the service provider.</p>
</li>
<li><p>Once received, the token is validated according to the trust relationship that was set up between the service provider and the identity provider during the initial configuration.</p>
</li>
<li><p>The user is granted access to the service provider.</p>
</li>
</ol>
<h3 id="heading-some-common-sso-protocols-include">Some common SSO protocols include:</h3>
<ul>
<li><p><strong>Security access markup language (SAML)</strong>: SAML is an XML-based open standard for transmitting user information.</p>
</li>
<li><p><strong>Open Authorization (OAuth)</strong>: OAuth is an open standard to transmit user information without revealing the password.</p>
</li>
<li><p><strong>Kerberos</strong>: Kerberos issues a ticket-granting ticket (TGT) for every valid user authentication. Both the user and server identify each other with tickets issued by the TGT. This makes it the ideal standard for untrusted networks.</p>
</li>
<li><p><strong>OpenID Connect</strong>: OpenID Connect is built on top of OAuth 2.0. It is fast gaining traction for being easier to implement than SAML. Since it works with restful application programming interfaces (APIs), it is an ideal choice for mobile applications.</p>
</li>
<li><p><strong>Smart card authentication:</strong> This involves smart cards loaded with cryptographic keys. When plugged into a computer, pre-loaded software interacts with it and authenticates the user. It is expensive and is usually used in addition to other modes of authentication.</p>
</li>
</ul>
<hr />
<h3 id="heading-oauth">OAuth</h3>
<p>OAuth is an open-standard authorization protocol or framework that describes how unrelated servers and services can safely allow authenticated access to their assets without actually sharing the initial, related, single logon credential. In authentication parlance, this is known as secure, third-party, user-agent, delegated authorization.</p>
<p>It is also helpful to remember that OAuth is about authorization in particular and not directly about authentication. Authentication is the process of a user/subject proving its ownership of a presented identity, by providing a password or some other uniquely owned or presented factor. Authorization is the process of letting a subject access resources after successful authentication, oftentimes somewhere else. Many people think that OAuth stands for open authentication, but it’s more helpful to understand it by thinking about it as open Authorization.</p>
<p>Additionally, <strong>OAuth 2.0 is a framework, not a protocol (like version 1.0).</strong></p>
<h3 id="heading-how-oauth-works">How OAuth works</h3>
<p>Let’s assume a user has already signed into one website or service (OAuth only works using HTTPS). The user then initiates a feature/transaction that needs to access another unrelated site or service. The following happens (greatly simplified):</p>
<ol>
<li><p>The first website connects to the second website on behalf of the user, using OAuth, providing the user’s verified identity.</p>
</li>
<li><p>The second site generates a one-time token and a one-time secret unique to the transaction and parties involved.</p>
</li>
<li><p>The first site gives this token and secret to the initiating user’s client software.</p>
</li>
<li><p>The client’s software presents the request token and secret to their authorization provider (which may or may not be the second site).</p>
</li>
<li><p>If not already authenticated to the authorization provider, the client may be asked to authenticate. After authentication, the client is asked to approve the authorization transaction to the second website.</p>
</li>
<li><p>The user approves (or their software silently approves) a particular transaction type at the first website.</p>
</li>
<li><p>The user is given an approved access token (notice it’s no longer a request token).</p>
</li>
<li><p>The user gives the approved access token to the first website.</p>
</li>
<li><p>The first website gives the access token to the second website as proof of authentication on behalf of the user.</p>
</li>
<li><p>The second website lets the first website access its site on behalf of the user.</p>
</li>
<li><p>The user sees a completed transaction occurring.</p>
</li>
</ol>
<hr />
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>As we learned, sessions are durations of time that a user spends on a website and includes everything that they do in that timeframe such as clicking on different pages or filling out a form. Sessions give you the ability to track what the user is doing in their time on the website. You collect that information to personalize the user’s experience, or even to learn more about what the typical user is doing on your website and what may or may not be getting clicks. However, a session only tracks the user instead of storing the data. For this, you need cookies. Cookies are small files that hold all the information gathered about the user’s experiences during a session. They are what store the data to allow it to be used later. Cookies can be enabled automatically, but many websites choose to prompt the user to allow for cookies. However, browser and third-party cookies also exist which are not in control of the website and can be more harmful in terms of user privacy.</p>
<p>Instead of a session, tokens can be generated as a secure way to track user information and activities. Tokens can also use cookies, but they can avoid cookies with web storage. One way to store the data is with JSON Web Tokens (JWTs). These tokens are stored in a JSON file and are encoded using Base64, which means a secret is required to decode the message. Without that secret, the message is meaningless. It is an alternative to the session/cookie route, and tokens can even be signed by third parties.</p>
]]></content:encoded></item><item><title><![CDATA[A Solid Guide to S.O.L.I.D Principles. Foundation for modern software architecture .]]></title><description><![CDATA[As software developers, the natural tendency is to start developing applications based on your own hands-on experience and knowledge right away. However…]]></description><link>https://alphac0des.hashnode.dev/a-solid-guide-to-solid-principles-foundation-for-modern-software-architecture</link><guid isPermaLink="true">https://alphac0des.hashnode.dev/a-solid-guide-to-solid-principles-foundation-for-modern-software-architecture</guid><category><![CDATA[software development]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[Software Testing]]></category><category><![CDATA[Developer]]></category><category><![CDATA[development]]></category><dc:creator><![CDATA[Mukul Attavania]]></dc:creator><pubDate>Thu, 30 Dec 2021 12:17:52 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-why-you-should-use-solid-design-principles">Why you should use SOLID design principles</h2>
<p>As software developers, the natural tendency is to start developing applications based on your own hands-on experience and knowledge right away. However, overtime issues in the application arise, adaptations to changes, and new features happen. Since then, you gradually realize that you have put too much effort into one thing: modifying the application. Even when implementing a simple task, it also requires understanding the whole system. You can’t blame them for changes or new features since they are inevitable parts of software development. So, what is the main problem here?</p>
<p>The obvious answer could be derived from the application’s design. Keeping the system design as clean and scalable as possible is one of the critical things that any professional developer should dedicate their time to. And that’s where SOLID design principles come into play. It helps developers eliminate design smells and build the best designs for a set of features.</p>
<p>Although the SOLID design principles were first introduced by the famous Computer Scientist Robert C. Martin (a.k.a. Uncle Bob) in his paper in 2000, its acronym was introduced later by Michael Feathers. Uncle Bob is also the author of best-selling books Clean Code, Clean Architecture, Agile Software Development: Principles, Patterns, and Practices.</p>
<h2 id="heading-why-do-we-need-solid-design-principles">Why do we need SOLID Design Principles?</h2>
<p>As a developer, we start developing applications using our experience and knowledge. But over time, the applications might arise bugs. We need to alter the application design for every change request or for a new feature request. After some time we might need to put in a lot of effort, even for simple tasks, it might require the full working knowledge of the entire system. But we can’t blame change or new feature requests as they are part of the software development. We can’t stop them and refuse them either. So who is the culprit here? Obviously, it is the design of the application.</p>
<h2 id="heading-advantages-of-solid-design-principles-in-c">Advantages of SOLID design principles in C</h2>
<p>The SOLID are long-standing principles used to manage most of the software design problems you encounter in your daily programming process.</p>
<p>Whether you are designing or developing the application, you can leverage the following advantages of SOLID principles to write code in the right way.</p>
<p><strong>Maintainability</strong>: So far, maintenance is vital for any organization to keep high quality as a standard in developing software. As the business has been growing and the market requires more changes, the software design should be adapted to future modifications at ease.</p>
<p><strong>Testability</strong>: When you design and develop a large-scale application, it’s essential to build one that facilitates testing each functionality early and easily.</p>
<p><strong>Flexibility and scalability:</strong> Flexibility and scalability are the foremost crucial parts of enterprise applications. As a result, the system design should be adaptable to any later update and extensible for adding new features smoothly and efficiently.</p>
<p><strong>Parallel development:</strong> Parallel development is one of the most key factors for saving time and costs in software development. It could be challenging for all team members to work on the same module at the same time. That’s why the software needs to be broken down into various modules which allow different teams to work independently and simultaneously.</p>
<h2 id="heading-whats-a-stupid-codebase">What’s a STUPID codebase?</h2>
<blockquote>
<p>A STUPID codebase is that codebase which has flaws or faults, which affect the maintainability, readability or efficiency.</p>
</blockquote>
<p><strong>Anti-Pattern Code == STUPID Code</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1640798728526/jJtR3TClR.jpeg" alt="0_UpO6QjvLSnqQ3d-2.jfif" /></p>
<h3 id="heading-why-be-stupid-when-you-can-be-solid">Why be STUPID, when you can be SOLID</h3>
<p><strong>Singleton:</strong> Violation of Singleton basically decreases the flexibility and reusability of the existing code, which deals with the object creation mechanism. It is an anti-pattern, where we define a class and its object in the same script/file and export the object for reusability. This is pattern is not wrong, but using it everywhere inappropriately is an symptom sick codebase.</p>
<pre><code><span class="hljs-comment">/**
*
*  Creating class Singleton, which is an Anti Pattern 
*  definition.
* 
*  WHY?
*  Let us see.
*/</span>
class Singleton {
  <span class="hljs-keyword">private</span> static instance: Singleton;
  <span class="hljs-keyword">private</span> _value: number;
  <span class="hljs-comment">/**
  * To avoid creating objects directly using 'new' 
  * operator
  * 
  * Therefore, the constructor is accessible to class 
  * methods only
  */</span>
  <span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) </span>{ } 
  <span class="hljs-comment">/**
  * Defining a Static function, so to directly
  *  make it accessible without creating an Object
  */</span>
  static makeInstance() {
    <span class="hljs-keyword">if</span> (<span class="hljs-operator">!</span>Singleton.instance) {
      Singleton.instance <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Singleton();
      Singleton.instance._value <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    }
    <span class="hljs-keyword">return</span> Singleton.instance;
  }
  getValue (): number {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._value;
  }
  setValue(score) {
    <span class="hljs-built_in">this</span>._value <span class="hljs-operator">=</span> score;
  }
  incrementValueByOne(): number {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._value <span class="hljs-operator">+</span><span class="hljs-operator">=</span> <span class="hljs-number">1</span>;
  }
}
<span class="hljs-comment">/**
*  Since the Singleton class's constructor is private, we  
*  need to create an instance using the static method 
*  makeInstance()
*  
*  Let us see what anomalies does that cause.
*    
*  Creating an instance using 'new' throw an Error
*  Constructor of class 'Singleton' is private and 
*  only accessible within the class declaration
*  const myInstance = new Singleton(); 
*/</span>
const myInstance1 <span class="hljs-operator">=</span> Singleton.makeInstance();
const myInstance2 <span class="hljs-operator">=</span> Singleton.makeInstance();
console.log(myInstance1.getValue()); <span class="hljs-comment">// OUTPUT: 0</span>
console.log(myInstance2.getValue()); <span class="hljs-comment">// OUTPUT: 0</span>
myInstance1.incrementValueByOne(); <span class="hljs-comment">// value = 1</span>
myInstance2.incrementValueByOne(); <span class="hljs-comment">// value = 2</span>
console.log(myInstance1.getValue()); <span class="hljs-comment">// OUTPUT: 2</span>
console.log(myInstance2.getValue()); <span class="hljs-comment">// OUTPUT: 2</span>
<span class="hljs-comment">/**
* This is the issue Singleton Anti-Pattern
* causing Issue with Singleton Pattern
*/</span>
</code></pre><p><strong>Tight-Coupling:</strong> Excessive coupling/dependency between classes or different separate functionality is a code smell, we need to be very careful about while we are developing or programming. We can figure tight-coupling when a method accesses the data of another object more than its own data or some sort of functional chaining scenarios.</p>
<pre><code><span class="hljs-comment">/**
* A simple example for Tight-Coupling
*/</span>
<span class="hljs-keyword">class</span> Car {
  <span class="hljs-keyword">move</span>() {
    console.log("Car is Moving");
  }
}
<span class="hljs-keyword">class</span> Lorry {
   <span class="hljs-keyword">move</span>(){
      console.log("Lorry is Moving");
   }
}
<span class="hljs-keyword">class</span> Traveller1 {
  Car CarObj = <span class="hljs-built_in">new</span> Car();
  travellerStatus(){
     CarObj.<span class="hljs-keyword">move</span>();
  }    
}
<span class="hljs-keyword">class</span> Traveller2 {
  Lorry LorryObj = <span class="hljs-built_in">new</span> Lorry();
  travellerStatus(){
     CarObj.<span class="hljs-keyword">move</span>();
  }    
}
</code></pre><p><strong>Untestabiility:</strong> Unit Testing is a very important part of software development where you cross-check and test if the component you built is functioning exactly the way expected. It is always advised to ship a product only after writing test cases. Shipping an untested code/product is very much similar to deploying an application whose behavior you are not sure about.</p>
<p>Apart from Unit testing, we have other tests like Integration testing, E2E testing, and so on, which are done based on their use cases and necessity.</p>
<p><strong>Premature Optimizations:</strong> Avoid refactoring code if it doesn’t improve the readability or performance of the system for no reason.</p>
<p>Premature optimization can also be defined as trying to optimize the code, expecting it to improvise the performance or readability without having much data assuring it, and purely weighing upon intuitions.</p>
<p><strong>In-descriptive Naming: </strong>Descriptive Naming and Naming Conventions are two important criteria. Most of the time, naming becomes the most painful issue.</p>
<p>After some time when you or another developer visits the codebase, you would be asking the question ‘What does this variable do?’. We fail to decide what would be the best descriptive name that can be given to a variable, class, class object/instance, or function. It is very important to give a descriptive name, for better readability and understandability.</p>
<pre><code><span class="hljs-comment">/**
* Example for adding two numbers: Avoid this
*/</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">a</span>(<span class="hljs-params">a1,a2</span>) </span>{ <span class="hljs-comment">// It is less descriptive in nature</span>
  <span class="hljs-keyword">return</span> a1 <span class="hljs-operator">+</span> a2;
}
console.log(a(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>)); <span class="hljs-comment">// It is less descriptive in nature</span>
<span class="hljs-comment">/**
* Example for adding two numbers: Better Approach
*/</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">num1,num2</span>) </span>{  <span class="hljs-comment">// sum() is descriptive</span>
  <span class="hljs-keyword">return</span> num1 <span class="hljs-operator">+</span> num2;
}
console.log(sum(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>)); 
<span class="hljs-comment">// Statement is descriptive in nature</span>
</code></pre><p><strong>Duplication:</strong> Sometimes, duplication of code is resultant of copy and paste. Violation of the DRY principle causes code-duplication. Always advised not to replicate the code across the codebase, as in long run causes huge technical debt. Duplication makes code maintenance tedious on a larger scale and longer run.</p>
<p>These flaws were often overlooked knowingly or unknowingly, for which SOLID principles served as the best cure.</p>
<p>So, you wondering now what SOLID principles hold and how does it solve the issues caused due to STUPID postulates. These are programming standards that all developers must understand very well, to create a product/system with good architecture.</p>
<p><strong>SOLID principles can be considered as remedies to the problems caused due to any of the STUPID flaws in your codebase.</strong></p>
<h2 id="heading-what-do-you-mean-by-solid-design-principles-in-c">What do you mean by SOLID Design Principles in C#?</h2>
<p>The SOLID Design Principles in C# are the design principles that basically used to manage most of the software design problems that generally we encountered in our day-to-day programming. These design principles are provided with some mechanism that will make the software designs more understandable, flexible, and maintainable.</p>
<h3 id="heading-what-is-the-main-reason-behind-most-of-the-unsuccessful-applications">What is the main reason behind most of the unsuccessful applications?</h3>
<p>The following are the main reasons for most of the software failures.</p>
<p>1.Putting more functionalities on classes. (In the simple word a lot of functionalities we are putting into the class even though they are not related to the class.)</p>
<p>2.Implementing Tight coupling between the classes. If the classes are dependent on each other, then a change in one class will affect the other classes also.</p>
<h3 id="heading-how-to-overcome-the-unsuccessful-application-development-problem">How to overcome the unsuccessful application Development problem?</h3>
<p>1.We need to use the correct architecture (i.e. MVC, Layered, 3-tier, MVP, and so on) as per the project requirements.</p>
<p>2.As a developer, we need to follow the Design Principles (i.e. SOLID Principles).</p>
<p>3.Again we need to choose the correct Design Patterns as per the project requirements.</p>
<h3 id="heading-introduction-to-solid-design-principles-in-c">Introduction to SOLID Design principles in C</h3>
<p>The SOLID Design principles are basically used to manage most of the software design problems that generally as a developer we face in our day-to-day programming. SOLID principles represent five design principles that basically used to make the software designs more understandable, flexible, and maintainable.</p>
<h3 id="heading-solid-acronym">SOLID Acronym</h3>
<p><strong>S</strong> stands for the <strong>Single Responsibility Principle</strong> which is also known as SRP.
<strong>O</strong> stands for the <strong>Open-Closed Principle</strong> which is also known as OSP.
<strong>L </strong>stands for the<strong> Liskov Substitution Principle</strong> which is also known as LSP.
<strong>I</strong> stand for the <strong>Interface Segregation Principle</strong> which is also known as ISP.
<strong>D</strong> stands for <strong>Dependency Inversion Principle</strong> which is also known as DIP.</p>
<h3 id="heading-what-are-the-advantages-of-using-solid-design-principles-in-c">What are the Advantages of using SOLID Design Principles in C#?</h3>
<p>We will get the following advantages of using SOLID Design Principles in C#.</p>
<p>1.Achieve the reduction in complexity of the code</p>
<p>2.Increase readability, extensibility, and maintenance</p>
<p>3.Reduce error and implement Reusability</p>
<p>4.Achieve Better testability</p>
<p>5.Reduce tight coupling</p>
<h2 id="heading-single-responsibility">Single Responsibility</h2>
<blockquote>
<p>Each class should should have RESPONSIBILITY over a single part of the functionality provided by the program.</p>
</blockquote>
<p>What does this mean practically though? As a beginner programmer, this isn’t very helpful. Let’s expand on the concept.</p>
<p>Examples of single responsibilities :</p>
<ul>
<li><p>Validating inputs.</p>
</li>
<li><p>Performing business logic.</p>
</li>
<li><p>Saving and retrieving information to/from a database.</p>
</li>
<li><p>Formatting a document.</p>
</li>
<li><p>Performing calculations for the document.</p>
</li>
</ul>
<p>So if you see a class that is validating inputs, logging events, reading and writing information to the database, and performing business logic, you have a class with A LOT of responsibilities; violating the Single Responsibility Principle.</p>
<p>How can you spot a class that may be violating the Single Responsibility Principle?</p>
<p>The class may have:</p>
<ul>
<li><p>Tight coupling</p>
</li>
<li><p>Low cohesion</p>
</li>
<li><p>No separation of concerns.</p>
</li>
</ul>
<p><strong>Tight coupling</strong></p>
<p>Changing one class results in having to change a lot of other classes to get the program working again. Sound familiar?</p>
<p><strong>Low Cohesion</strong></p>
<p>The class contains fields and methods/functions that are unrelated to each other in any meaningful way.</p>
<p>A good way to spot this is if methods in a class don’t reuse the same fields. Each method is using different fields from the class.</p>
<p><strong>No Separation Of Concerns</strong></p>
<p>Should my class that deals with validating an input be performing business logic and saving the data to the database? Not likely. Separate the program out into sections that deal with each concern.</p>
<p>A classic real-world example of something having too many responsibilities is the multi-function knives. They try to do too much and end up doing nothing well.</p>
<p><strong>Implementation</strong></p>
<p>Let’s take a scenario of Garage service station functionality. It has 3 main functions; open gate, close gate, and performing service. The below example violates the SRP principle. The code below violates the SRP principle as it mixes open gate and close gate responsibilities with the main function of servicing of the vehicle.</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GarageStation</span>
{</span>
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DoOpenGate</span><span class="hljs-params">()</span>
 </span>{
 <span class="hljs-comment">//Open the gate functinality</span>
 }

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">PerformService</span><span class="hljs-params">(Vehicle vehicle)</span>
 </span>{
 <span class="hljs-comment">//Check if garage is opened</span>
 <span class="hljs-comment">//finish the vehicle service</span>
 }

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DoCloseGate</span><span class="hljs-params">()</span>
 </span>{
 <span class="hljs-comment">//Close the gate functinality</span>
 }
}
</code></pre><p>We can correctly apply SRP by refactoring of above code by introducing an interface. A new interface called IGarageUtility is created and gate-related methods are moved to a different class called GarageStationUtility.</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">GarageStation</span>
{
 IGarageUtility _garageUtil;

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">GarageStation</span>(<span class="hljs-params">IGarageUtility garageUtil</span>)</span>
 {
 <span class="hljs-keyword">this</span>._garageUtil = garageUtil;
 }
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OpenForService</span>(<span class="hljs-params"></span>)</span>
 {
 _garageUtil.OpenGate();
 }
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">DoService</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-comment">//Check if service station is opened and then</span>
 <span class="hljs-comment">//finish the vehicle service</span>
 }
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">CloseGarage</span>(<span class="hljs-params"></span>)</span>
 {
 _garageUtil.CloseGate();
 }
}
 <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">GarageStationUtility</span> : <span class="hljs-title">IGarageUtility</span>
{
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">OpenGate</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-comment">//Open the Garage for service</span>
 }

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">CloseGate</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-comment">//Close the Garage functionlity</span>
 }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IGarageUtility</span>
{
 <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">OpenGate</span>(<span class="hljs-params"></span>)</span>;
 <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">CloseGate</span>(<span class="hljs-params"></span>)</span>;
}
</code></pre><p><strong>Goal</strong></p>
<p>This principle aims to separate behaviors so that if bugs arise as a result of your change, it won’t affect other unrelated behaviors.</p>
<h2 id="heading-open-closed-principle-ocp">Open-Closed Principle (OCP)</h2>
<blockquote>
<p>Software entities (classes, methods, modules) should be open for extension but closed for modification</p>
</blockquote>
<h3 id="heading-what-does-this-mean-in-a-practical-sense">What does this mean in a practical sense?</h3>
<p>You should be able to change the behavior of a method without changing its source code.</p>
<p>For simple methods, adding/changing the logic in the method is perfectly reasonable. If you have to revisit this method 3+ times (not a hard number) due to requirements changing, you should start to think about the Open/Closed Principle.</p>
<h3 id="heading-closing-code-to-modification-why-would-you-want-to-do-this">Closing code to modification, why would you want to do this?</h3>
<p>Code that we don’t alter is less likely to create bugs due to unforeseen side effects.</p>
<p>This principle suggests that the class should be easily extended but there is no need to change its core implementations.</p>
<p>The application or software should be flexible to change. How change management is implemented in a system has a significant impact on the success of that application/ software. The OCP states that the behaviors of the system can be extended without having to modify its existing implementation.</p>
<p>i.e. New features should be implemented using the new code, but not by changing existing code. The main benefit of adhering to OCP is that it potentially streamlines code maintenance and reduces the risk of breaking the existing implementation.</p>
<h3 id="heading-implementation">Implementation</h3>
<p>Let’s take an example of bank accounts like regular savings, salary savings, corporate, etc. for different customers. As for each customer type, there are different rules and different interest rates. The code below violates the OCP principle if the bank introduces a new Account type. Said code modifies this method for adding a new account type.</p>
<pre><code><span class="hljs-keyword">public</span> class Account
{
 <span class="hljs-keyword">public</span> decimal Interest { get; set; }
 <span class="hljs-keyword">public</span> decimal Balance { get; set; }
 <span class="hljs-comment">// members and function declaration</span>
 <span class="hljs-keyword">public</span> decimal CalcInterest(<span class="hljs-keyword">string</span> accType)
 {
 <span class="hljs-keyword">if</span> (accType <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-string">"Regular"</span>) <span class="hljs-comment">// savings</span>
 {
 Interest <span class="hljs-operator">=</span> (Balance <span class="hljs-operator">*</span> <span class="hljs-number">4</span>) <span class="hljs-operator">/</span> <span class="hljs-number">100</span>;
 <span class="hljs-keyword">if</span> (Balance <span class="hljs-operator">&lt;</span> <span class="hljs-number">1000</span>) Interest <span class="hljs-operator">-</span><span class="hljs-operator">=</span> (Balance <span class="hljs-operator">*</span> <span class="hljs-number">2</span>) <span class="hljs-operator">/</span> <span class="hljs-number">100</span>;
 <span class="hljs-keyword">if</span> (Balance <span class="hljs-operator">&lt;</span> <span class="hljs-number">50000</span>) Interest <span class="hljs-operator">+</span><span class="hljs-operator">=</span> (Balance <span class="hljs-operator">*</span> <span class="hljs-number">4</span>) <span class="hljs-operator">/</span> <span class="hljs-number">100</span>;
 }
 <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (accType <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-string">"Salary"</span>) <span class="hljs-comment">// salary savings</span>
 {
 Interest <span class="hljs-operator">=</span> (Balance <span class="hljs-operator">*</span> <span class="hljs-number">5</span>) <span class="hljs-operator">/</span> <span class="hljs-number">100</span>;
 }
 <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (accType <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-string">"Corporate"</span>) <span class="hljs-comment">// Corporate</span>
 {
 Interest <span class="hljs-operator">=</span> (Balance <span class="hljs-operator">*</span> <span class="hljs-number">3</span>) <span class="hljs-operator">/</span> <span class="hljs-number">100</span>;
 }
 <span class="hljs-keyword">return</span> Interest;
 }
}
</code></pre><p>We can apply OCP by using the interface, abstract class, abstract methods, and virtual methods when you want to extend functionality. Here I have used interface for example only but you can go as per your requirement.</p>
<pre><code><span class="hljs-keyword">interface</span> <span class="hljs-title">IAccount</span>
{
 <span class="hljs-comment">// members and function declaration, properties</span>
 <span class="hljs-keyword">decimal</span> Balance { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
 <span class="hljs-function"><span class="hljs-keyword">decimal</span> <span class="hljs-title">CalcInterest</span>(<span class="hljs-params"></span>)</span>;
}

<span class="hljs-comment">//regular savings account </span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">RegularSavingAccount</span> : <span class="hljs-title">IAccount</span>
{
 <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Balance { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-number">0</span>;
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> <span class="hljs-title">CalcInterest</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-keyword">decimal</span> Interest = (Balance * <span class="hljs-number">4</span>) / <span class="hljs-number">100</span>;
 <span class="hljs-keyword">if</span> (Balance &lt; <span class="hljs-number">1000</span>) Interest -= (Balance * <span class="hljs-number">2</span>) / <span class="hljs-number">100</span>;
 <span class="hljs-keyword">if</span> (Balance &lt; <span class="hljs-number">50000</span>) Interest += (Balance * <span class="hljs-number">4</span>) / <span class="hljs-number">100</span>;

 <span class="hljs-keyword">return</span> Interest;
 }
}

<span class="hljs-comment">//Salary savings account </span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">SalarySavingAccount</span> : <span class="hljs-title">IAccount</span>
{
 <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Balance { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-number">0</span>;
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> <span class="hljs-title">CalcInterest</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-keyword">decimal</span> Interest = (Balance * <span class="hljs-number">5</span>) / <span class="hljs-number">100</span>;
 <span class="hljs-keyword">return</span> Interest;
 }
}

<span class="hljs-comment">//Corporate Account</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CorporateAccount</span> : <span class="hljs-title">IAccount</span>
{
 <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Balance { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-number">0</span>;
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> <span class="hljs-title">CalcInterest</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-keyword">decimal</span> Interest = (Balance * <span class="hljs-number">3</span>) / <span class="hljs-number">100</span>;
 <span class="hljs-keyword">return</span> Interest;
 }
}
</code></pre><p>In the above code three new classes are created; regular saving account, SalarySavingAccount, and CorporateAccount, by extending them from IAccount.
This solves the problem of modification of class and by extending the interface, we can extend functionality.</p>
<p>The above code is implementing both OCP and SRP principles, as each class has single is doing a single task and we are not modifying the class and only doing an extension.</p>
<p><strong>Goal</strong></p>
<p>This principle aims to extend a Class’s behavior without changing the existing behavior of that Class. This is to avoid causing bugs wherever the Class is being used.</p>
<h2 id="heading-liskov-substitution">Liskov Substitution</h2>
<blockquote>
<p>If S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program.</p>
</blockquote>
<p>LSP states that the child class should be perfectly substitutable for their parent class. If class C is derived from P then C should be substitutable for P.</p>
<p>We can check using LSP whether inheritance is applied correctly or not in our code.</p>
<p>LSP is a fundamental principle of SOLID Principles and states that if a program or module is using base class then derived class should be able to extend their base class without changing their original implementation.</p>
<h3 id="heading-implementation">Implementation</h3>
<p>Let’s consider the code below where LSP is violated. We cannot simply substitute a Triangle, which results in the printing shape of a triangle, with a Circle.</p>
<pre><code><span class="hljs-keyword">namespace</span> <span class="hljs-title">Demo</span>
{
 <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
 {
 Triangle triangle = <span class="hljs-keyword">new</span> Circle();
 Console.WriteLine(triangle.GetColor());
 }
 }

 <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Triangle</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">virtual</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetShape</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-keyword">return</span> <span class="hljs-string">"Triangle"</span>;
 }
 }

 <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span>: <span class="hljs-title">Triangle</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetShape</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-keyword">return</span> <span class="hljs-string">"Circle"</span>;
 }
 }
}
</code></pre><p>To correct the above implementation, we need to refactor this code by introducing an interface with a method called GetShape.</p>
<pre><code><span class="hljs-keyword">namespace</span> <span class="hljs-title">Demo</span>
{
 <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
 {
 Shape shape = <span class="hljs-keyword">new</span> Circle();
 Console.WriteLine(shape.GetShape());
 shape = <span class="hljs-keyword">new</span> Triangle ();
 Console.WriteLine(shape.GetShape());
 }
 }

 <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Shape</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetShape</span>(<span class="hljs-params"></span>)</span>;
 }

 <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Triangle</span>: <span class="hljs-title">Shape</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetShape</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-keyword">return</span> <span class="hljs-string">"Triangle"</span>;
 }
 }

 <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span>: <span class="hljs-title">Triangle</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetShape</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-keyword">return</span> <span class="hljs-string">"Circle"</span>;
 }
 }
}
</code></pre><p><strong>Goal</strong></p>
<p>This principle aims to enforce consistency so that the parent Class or its child Class can be used in the same way without any errors.</p>
<h2 id="heading-interface-segregation">Interface Segregation</h2>
<blockquote>
<p>Clients should not be forced to depend on methods that they do not use.</p>
</blockquote>
<p>The <strong>interface segregation principle (ISP)</strong> requires that classes only be able to perform behaviors that are useful to achieve its end functionality. In other words, classes do not include behaviors they do not use.</p>
<p>This relates to our first SOLID principle in that together these two principles strip a class of all variables, methods, or behaviors that do not directly contribute to their role. Methods must contribute to the end goal in their entirety.</p>
<p>The advantage of ISP is that it splits large methods into smaller, more specific methods. This makes the program easier to debug for three reasons:</p>
<ol>
<li><p>There is less code carried between classes. Less code means fewer bugs.</p>
</li>
<li><p>A single method is responsible for a smaller variety of behaviors. If there is a problem with a behavior, you only need to look over the smaller methods.</p>
</li>
<li><p>If a general method with multiple behaviors is passed to a class that doesn’t support all behaviors (such as calling for a property that the class doesn’t have), there will be a bug if the class tries to use the unsupported behavior.</p>
</li>
</ol>
<h3 id="heading-implementation">Implementation</h3>
<p>In the below code, ISP is broken as the process method is not required by OfflineOrder class but is forced to implement.</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IOrder</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">AddToCart</span>(<span class="hljs-params"></span>)</span>;
 <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">CCProcess</span>(<span class="hljs-params"></span>)</span>;
 }

 <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">OnlineOrder</span> : <span class="hljs-title">IOrder</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AddToCart</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-comment">//Do Add to Cart</span>
 }

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">CCProcess</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-comment">//process through credit card</span>
 }
 }

 <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">OfflineOrder</span> : <span class="hljs-title">IOrder</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AddToCart</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-comment">//Do Add to Cart</span>
 }

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">CCProcess</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-comment">//Not required for Cash/ offline Order</span>
 <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotImplementedException();
 }
 }
</code></pre><p>We can resolve this violation by dividing IOrder Interface.</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IOrder</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">AddToCart</span>(<span class="hljs-params"></span>)</span>;
 }

 <span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IOnlineOrder</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">CCProcess</span>(<span class="hljs-params"></span>)</span>;
 }

 <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">OnlineOrder</span> : <span class="hljs-title">IOrder</span>, <span class="hljs-title">IOnlineOrder</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AddToCart</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-comment">//Do Add to Cart</span>
 }

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">CCProcess</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-comment">//process through credit card</span>
 }
 }

 <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">OfflineOrder</span> : <span class="hljs-title">IOrder</span>
 {
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">AddToCart</span>(<span class="hljs-params"></span>)</span>
 {
 <span class="hljs-comment">//Do Add to Cart</span>
 }
 }
</code></pre><p><strong>Goal</strong></p>
<p>This principle aims at splitting a set of actions into smaller sets so that a Class executes ONLY the set of actions it requires.</p>
<h2 id="heading-dependency-inversion">Dependency Inversion</h2>
<blockquote>
<p>High-level modules should not depend on low-level modules. Both should depend on the abstraction.</p>
<p>Abstractions should not depend on details. Details should depend on abstractions.</p>
</blockquote>
<p>The d<strong>ependency inversion principle (DIP)</strong> has two parts:</p>
<p>High-level modules should not depend on low-level modules. Instead, both should depend on abstractions (interfaces)</p>
<p>Abstractions should not depend on details. Details (like concrete implementations) should depend on abstractions.</p>
<p>The first part of this principle <strong>reverses traditional OOP software design</strong>. Without DIP, programmers often construct programs to have high-level (less detail, more abstract) components explicitly connected with low-level (specific) components to complete tasks.</p>
<p>DIP decouples high and low-level components and instead connects both to abstractions. High and low-level components can still benefit from each other, but a change in one should not directly break the other.</p>
<p>The advantage of this part of DIP is that decoupled programs require less work to change. Webs of dependencies across your program mean that a single change can affect many separate parts.</p>
<blockquote>
<p>If you minimize dependencies, changes will be more localized and require less work to find all affected components.</p>
</blockquote>
<p>The second part can be thought of as “the abstraction is not affected if the details are changed”. The abstraction is the user-facing part of the program.</p>
<p>The details are the specific behind-the-scenes implementations that cause program behavior visible to the user. In a DIP program, we could fully overhaul the behind-the-scenes implementation of how the program achieves its behavior without the user’s knowledge.</p>
<blockquote>
<p>his process is known as refactoring.</p>
</blockquote>
<h3 id="heading-implementation">Implementation</h3>
<p>In below code, we have implemented DIP using IoC using injection constructor. There are different ways to implement Dependency injection. Here, I have use injection thru constructor but you inject the dependency into class’s constructor (Constructor Injection), set property (Setter Injection), method (Method Injection), events, index properties, fields and basically any members of the class which are public.</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">IAutomobile</span>
{
 <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Ignition</span>(<span class="hljs-params"></span>)</span>;
 <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">Stop</span>(<span class="hljs-params"></span>)</span>;
}
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Jeep</span> : <span class="hljs-title">IAutomobile</span>
{
 <span class="hljs-meta">#<span class="hljs-meta-keyword">region</span> IAutomobile Members</span>
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Ignition</span>(<span class="hljs-params"></span>)</span>
 {
 Console.WriteLine(<span class="hljs-string">"Jeep start"</span>);
 }

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Stop</span>(<span class="hljs-params"></span>)</span>
 {
 Console.WriteLine(<span class="hljs-string">"Jeep stopped."</span>);
 }
 <span class="hljs-meta">#<span class="hljs-meta-keyword">endregion</span></span>
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">SUV</span> : <span class="hljs-title">IAutomobile</span>
{
 <span class="hljs-meta">#<span class="hljs-meta-keyword">region</span> IAutomobile Members</span>
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Ignition</span>(<span class="hljs-params"></span>)</span>
 {
 Console.WriteLine(<span class="hljs-string">"SUV start"</span>);
 }

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Stop</span>(<span class="hljs-params"></span>)</span>
 {
 Console.WriteLine(<span class="hljs-string">"SUV stopped."</span>);
 }
 <span class="hljs-meta">#<span class="hljs-meta-keyword">endregion</span></span>
}
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AutomobileController</span>
{
 IAutomobile m_Automobile;

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AutomobileController</span>(<span class="hljs-params">IAutomobile automobile</span>)</span>
 {
 <span class="hljs-keyword">this</span>.m_Automobile = automobile;
 }

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Ignition</span>(<span class="hljs-params"></span>)</span>
 {
 m_Automobile.Ignition();
 }

 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Stop</span>(<span class="hljs-params"></span>)</span>
 {
 m_Automobile.Stop();
 }
}

<span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
{
 <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
 {
 IAutomobile automobile = <span class="hljs-keyword">new</span> Jeep();
 <span class="hljs-comment">//IAutomobile automobile = new SUV();</span>
 AutomobileController automobileController = <span class="hljs-keyword">new</span> AutomobileController(automobile);
 automobile.Ignition();
 automobile.Stop();

 Console.Read();
 }
}
</code></pre><p>In the above code, IAutomobile interface is in an abstraction layer and AutomobileController as the higher-level module. Here, we have integrated all in a single code but in real-world, each abstraction layer is a separate class with additional functionality. Here products are completely decoupled from the consumer using IAutomobile interface. The object is injected into the constructor of the AutomobileController class in reference to the interface IAutomobile. The constructor where the object gets injected is called injection constructor.</p>
<p>DI is a software design pattern that allows us to develop loosely coupled code. Using DI, we can reduce tight coupling between software components. DI also allows us to better accomplish future changes and other difficulties in our software. The purpose of DI is to make code sustainable.</p>
<p><strong>Goal</strong></p>
<p>This principle aims at reducing the dependency of a high-level Class on the low-level Class by introducing an interface.</p>
<p>Conclusion
In this article, we’ve taken a <strong>deep dive into the SOLID principles of object-oriented design.</strong>
We <strong>started with a quick bit of SOLID history and the reasons these principles exist.</strong></p>
<p>Letter by letter, we’ve <strong>broken down the meaning of each principle with a quick code example that violates it. We then saw how to fix our code </strong>and make it adhere to the SOLID principles.</p>
]]></content:encoded></item><item><title><![CDATA[What are the ACID properties in Database Systems?]]></title><description><![CDATA[ACID is an acronym of the following words: 1. Atomicity 2. Consistency 3. Isolation 4. Durability. If we have a certain operation in a database that…]]></description><link>https://alphac0des.hashnode.dev/what-are-the-acid-properties-in-database-systems</link><guid isPermaLink="true">https://alphac0des.hashnode.dev/what-are-the-acid-properties-in-database-systems</guid><category><![CDATA[Databases]]></category><category><![CDATA[software development]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[Docker]]></category><category><![CDATA[Kubernetes]]></category><dc:creator><![CDATA[Mukul Attavania]]></dc:creator><pubDate>Wed, 29 Dec 2021 14:36:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1640788475430/83spq0WOX.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-what-is-acid">What is ACID?</h3>
<p>ACID is an acronym of the following words:</p>
<p><strong>1. Atomicity</strong></p>
<p><strong>2. Consistency</strong></p>
<p><strong>3. Isolation</strong></p>
<p><strong>4. Durability.</strong></p>
<p>If we have a certain operation in a database that satisfies these properties, we can call this operation “<strong>transaction</strong>”.</p>
<p>Ok, that’s nice, but these words are just words without an explanation. Let’s dig deeper into each of them!</p>
<h3 id="heading-transactions">Transactions</h3>
<p>A quick note about transactions. A transaction is a collection of instructions. All transactions must follow ACID properties in order to guarantee database validity. I’ll use banking transactions between customers below to illustrate the 4 properties.</p>
<h3 id="heading-atomicity">Atomicity</h3>
<p><strong>Atomicity ensures that each transaction is treated as a single unit that follows the “all or nothing” rule; a transaction either happens completely or not at all.</strong> If any part of the transaction fails, the entire transaction will fail.</p>
<p>For example, customer A wants to withdraw $100 from their account and then deposit it into customer B’s account. If any of the instructions fail (insufficient funds or server crashes, etc.), the transaction will fail and any changes will be rolled back.</p>
<h3 id="heading-consistency">Consistency</h3>
<p><strong>Consistency guarantees that a transaction must be valid before it gets written to the database. </strong>A transaction is valid when it follows all of the defined rules, including constraints, cascades, triggers, and any combination of these. Inconsistent transactions will result in the database being rolled back to a previous state that complies with the given database rules.</p>
<p>If customer A wants to withdraw $100 from their account but only has $50 in their account, consistency prevents them from withdrawing the funds and the transaction will be aborted.</p>
<h3 id="heading-isolation">Isolation</h3>
<p>As transactions are typically executed at the same time (i.e. multiple transactions that read and write to a table at the same time),<strong> isolation sees that each transaction acts as an individual transaction and would receive the same state if the transactions were executed sequentially.</strong> Isolation is important for concurrency control.</p>
<p>If customer C has an account balance of $1000 that both customers A and B can make withdrawals from (say $50 and $100, respectively), one of the customers will have to wait until the other customer transaction is finished, in order to avoid inconsistent data.</p>
<h3 id="heading-durability">Durability</h3>
<p><strong>Durability ensures that once a transaction has been completed and committed, it will remain committed even in the event of a system failure (crash or power failure)</strong>. These completed transactions are stored in non-volatile memory.</p>
<p>If customer A successfully deposited $500 in their account, this transaction should not disappear if any system failure occurs.</p>
<p>As I mentioned above, a majority of SQL/relational databases are ACID compliant. NoSQL databases tend to sacrifice ACID compliance for faster performance. There is strong data reliability and a guarantee that the transactions are safe.</p>
<p>There may be clear-cut scenarios where an ACID-compliant database is the best solution, such as e-commerce, healthcare, financial services apps (when data integrity is of the utmost concern). Yet, there are other times where you may want to take other factors into consideration in deciding between a SQL or NoSQL database.</p>
<h2 id="heading-all-the-things-that-can-go-wrong-with-your-transactions">All the things that can go wrong with your transactions</h2>
<p>Data Scientists worry about long analytical queries and warehousing, but for developers, databases are all about transactions. A database transaction is a series of logically grouped database operations: insert a row here, update a record there, and more stuff like that. Your application code is constantly making transactions every time you sign up a new user or that user updates their account information.</p>
<p>The thing about transactions, though, is that they can go very wrong. Any number of things can happen when you’re trying to write to your database: you can lose connection to a remote instance, you can encounter value errors or anything else under the sun. You’ve seen it, you’ve dealt with it, and it can mean disaster for your underlying data. Let’s take a look at a quick example that a company like Amazon might run into:</p>
<pre><code><span class="hljs-keyword">User</span> updates <span class="hljs-keyword">order</span> quantity <span class="hljs-keyword">and</span> clicks “<span class="hljs-keyword">order</span> now” →
- <span class="hljs-keyword">Update</span> <span class="hljs-keyword">order</span> quantity <span class="hljs-keyword">in</span> the pending orders <span class="hljs-keyword">table</span>
- <span class="hljs-keyword">Add</span> <span class="hljs-keyword">row</span> <span class="hljs-keyword">to</span> orders <span class="hljs-keyword">table</span>
- Apply the purchase <span class="hljs-keyword">to</span> <span class="hljs-keyword">user</span>’s balance / charge credit card
</code></pre><p>If something goes wrong in the middle of this group of operations but the system continues executing them, the user will get charged the wrong amount. And if the charge doesn’t work, they’ll get their order for free. It turns out that these kinds of data errors have names, and there are a bunch of them. A few examples:</p>
<h3 id="heading-dirty-reads">Dirty Reads</h3>
<p>If a transaction is in the middle of updating some data and hasn’t committed yet, and another transaction is allowed to read that uncommitted data, that’s dirty, and could lead to your app showing incorrect data that got rolled back.</p>
<p>An example of a dirty read could be a transaction that invalidates login tokens when a user changes their password. If as the first transaction loads the token, a second one reads that token before the first invalidates it, you’d have yourself a dirty read.</p>
<p>In terms of actual SQL, here’s what a dirty read might look like:</p>
<pre><code>### <span class="hljs-keyword">Transaction</span> <span class="hljs-number">1</span> ###
<span class="hljs-keyword">SELECT</span> user_login_token_id
<span class="hljs-keyword">FROM</span> tokens
<span class="hljs-keyword">UPDATE</span> tokens
<span class="hljs-keyword">SET</span> token_status = "INVALID"
<span class="hljs-keyword">WHERE</span> token_id = user_login_token_id
### <span class="hljs-keyword">Transaction</span> <span class="hljs-number">2</span> ###
<span class="hljs-keyword">SELECT</span> user_login_token_id
<span class="hljs-keyword">FROM</span> tokens
</code></pre><p>Non-Repeatable Reads
If you’ve got two consecutive reads in one transaction with a concurrent update in between, those reads are going to show different results even though they’re part of the same transaction.</p>
<p>An example might be two writers working on a blog. Our first user starts a transaction that reads a post’s title, writes to the post, and then reads that post’s title again. If a second user changes that post’s title in the middle of the first user’s transaction, the first user is going to see different values for the title across the two reads; or in other words, a non-repeatable read.</p>
<p>Here’s what a non-repeatable read might look like in SQL:</p>
<pre><code>### <span class="hljs-keyword">Transaction</span> <span class="hljs-number">1</span> ###
<span class="hljs-keyword">SELECT</span> post_title
<span class="hljs-keyword">FROM</span> posts
<span class="hljs-keyword">SELECT</span>
    post_title,
    post_content
<span class="hljs-keyword">FROM</span> posts
### <span class="hljs-keyword">Transaction</span> <span class="hljs-number">2</span> ###
<span class="hljs-keyword">UPDATE</span> posts
<span class="hljs-keyword">SET</span> post_title = "something_new"
<span class="hljs-keyword">WHERE</span> post_title = post_title
</code></pre><h3 id="heading-phantom-reads">Phantom Reads</h3>
<p>If a transaction reads data and then a concurrent transaction inserts data that would have been read in the original transaction, that’s a phantom read.</p>
<p>Let’s use the same example as a non-repeatable read: if our second user adds content in between our first user’s two reads, the first read will be missing data that appears in the second read (this is actually really similar to a non-repeatable read, which is why the same example works).</p>
<p>In SQL, a phantom read might look like this:</p>
<pre><code><span class="hljs-comment">### Transaction 1 ###</span>
<span class="hljs-keyword">SELECT</span> post_title
<span class="hljs-keyword">FROM</span> posts
<span class="hljs-keyword">SELECT</span>
    post_title,
    post_content
<span class="hljs-keyword">FROM</span> posts
<span class="hljs-comment">### Transaction 2 ###</span>
<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> posts
<span class="hljs-keyword">VALUES</span> <span class="hljs-string">"something_new"</span>, ...
</code></pre><p>These are the 3 transactional errors as defined by the SQL standard — the big three, you might say. A lot of these errors sound like one another and tend to overlap in practice, so don’t sweat the details.</p>
<h2 id="heading-acid-concepts-in-nosql-and-distributed-systems">ACID concepts in NoSQL and distributed systems</h2>
<p>ACID was a building block of the reliable relational DBs we’re familiar with today, but NoSQL has changed the game: many NoSQL DBs are built as distributed systems, and they can’t always ensure complete transactional consistency. There’s actually a theory that governs this — called CAP theorem — that in distributed systems, you can never have full consistency and full availability; you need to choose one. So what does ACID look like for something like MongoDB or Cassandra?</p>
<p>A new quasi-standard has emerged for NoSQL databases called BASE (a rare overlap between SQL and chemistry jokes), and it’s a weak or soft consistency model that relaxes some of the assumptions of ACID in order to achieve scalability:</p>
<p><strong>-Basic Availability:</strong> the database basically works most of the time, even though it’s not perfect</p>
<p><strong>-Soft-State:</strong> nodes of the database aren’t necessarily consistent with each other all the time</p>
<p><strong>-Eventual Consistency:</strong> data will be consistent across nodes eventually, like by reading time</p>
<p>In a lot of ways, this is the exact opposite of ACID, and prioritizes availability over perfect consistency; but that’s kind of the point of NoSQL in the first place. As NoSQL becomes a more established part of app development (more than 25% of developers are using MongoDB already), expect more advancements on this front.</p>
<p>Today, we’re dealing with more data than we ever have, and we’re building database systems that can scale and handle that load. ACID might not be the exact transactional standard for the future, but its building blocks will certainly make their way in there.</p>
]]></content:encoded></item><item><title><![CDATA[System Design 101-Everything to know about Distributed Systems…]]></title><description><![CDATA[In this Article, we are going to learn about Distributed Systems. Here we are focusing on these things, A distributed system in its most simplest…]]></description><link>https://alphac0des.hashnode.dev/system-design-101-everything-to-know-about-distributed-systems</link><guid isPermaLink="true">https://alphac0des.hashnode.dev/system-design-101-everything-to-know-about-distributed-systems</guid><category><![CDATA[distributed system]]></category><category><![CDATA[System Architecture]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Developer]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Mukul Attavania]]></dc:creator><pubDate>Thu, 07 Oct 2021 17:24:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1633627313674/yj5RYX7E3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this Article, we are going to learn about Distributed Systems. Here we are focusing on these things,</p>
<ul>
<li>What is Distributed Systems</li>
<li>How does Distributed Systems work</li>
<li>Why Distributed Systems</li>
<li>Characteristic of Distributed Systems</li>
<li>Challenges of Distributed Systems.</li>
<li>Risks using Distributed Systems</li>
<li>Distributed System Architecture &amp; Types</li>
<li>Distributed Data Stores(Cassandra)</li>
<li>CAP Theorem</li>
<li>Distributed Messaging</li>
<li>Data Copying</li>
<li>Decentralized vs Distributed Systems</li>
<li>Cloud vs Distributed Systems</li>
</ul>
<h3 id="what-is-a-distributed-system"><strong>What is a distributed system?</strong></h3>
<p>A distributed system in its most simplest definition is a group of computers working together as to appear as a single computer to the end-user.</p>
<p>These machines have a shared state, operate concurrently and can fail independently without affecting the whole system’s uptime.</p>
<p>A distributed system is any network structure that consists of autonomous computers that are connected using a distribution middleware. Distributed systems facilitate sharing different resources and capabilities, to provide users with a single and integrated coherent network.
The opposite of a distributed system is a centralized system. If all of the components of a computing system reside in one machine.</p>
<p>Unlike traditional databases, which are stored on a single machine, in a distributed system, a user must be able to communicate with any machine without knowing it is only one machine. Most applications today use some form of a distributed database and must account for their homogenous or heterogenous nature.</p>
<p>In a homogenous distributed database, each system shares a data model and database management system and data model. Generally, these are easier to manage by adding nodes. On the other hand, heterogeneous databases make it possible to have multiple data models or varied database management systems using gateways to translate data between nodes.</p>
<p><strong>Distributed Information Systems:</strong> distribute information across different servers via multiple communication models.</p>
<p><strong>Distributed Pervasive Systems:</strong> use embedded computer devices (i.e. ECG monitors, sensors, mobile devices).</p>
<p><strong>Distributed Computing Systems:</strong> computers in a network communicate via message passing.</p>
<p><em>Distributed systems must have a shared network to connect its components, which could be connected using an IP address or even physical cables.</em></p>
<h3 id="how-does-a-distributed-system-work"><strong>How does a distributed system work?</strong></h3>
<p>Distributed systems have evolved over time, but today’s most common implementations are largely designed to operate via the internet and, more specifically, the cloud. A distributed system begins with a task, such as rendering a video to create a finished product ready for release. The web application, or distributed applications, managing this task — like a video editor on a client computer — splits the job into pieces. In this simple example, the algorithm that gives one frame of the video to each of a dozen different computers (or nodes) to complete the rendering. Once the frame is complete, the managing application gives the node a new frame to work on. This process continues until the video is finished and all the pieces are put back together. A system like this doesn’t have to stop at just 12 nodes — the job may be distributed among hundreds or even thousands of nodes, turning a task that might have taken days for a single computer to complete into one that is finished in a matter of minutes.</p>
<p>There are many models and architectures of distributed systems in use today. Client-server systems, the most traditional and simple type of distributed system, involve a multitude of networked computers that interact with a central server for data storage, processing or other common goal. Cell phone networks are an advanced type of distributed system that share workloads among handsets, switching systems and internet-based devices. Peer-to-peer networks, in which workloads are distributed among hundreds or thousands of computers all running the same software, are another example of a distributed system architecture. The most common forms of distributed systems in the enterprise today are those that operate over the web, handing off workloads to dozens of cloud-based virtual server instances that are created as needed, then terminated when the task is complete.</p>
<h3 id="why-distribute-a-system"><strong>Why distribute a system?</strong></h3>
<p>Systems are always distributed by necessity. The truth of the matter is — managing distributed systems is a complex topic chock-full of pitfalls and landmines. It is a headache to deploy, maintain and debug distributed systems, so why go there at all?
What a distributed system enables you to do is scale horizontally. Going back to our previous example of the single database server, the only way to handle more traffic would be to upgrade the hardware the database is running on. This is called scaling vertically.</p>
<p>Scaling vertically is all well and good while you can, but after a certain point you will see that even the best hardware is not sufficient for enough traffic, not to mention impractical to host.</p>
<p>Scaling horizontally simply means adding more computers rather than upgrading the hardware of a single one.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633591714193/wsq9P7THo.png" alt="scale.png" /></p>
<p>It is significantly cheaper than vertical scaling after a certain threshold but that is not its main case for preference.</p>
<p>Vertical scaling can only bump your performance up to the latest hardware’s capabilities. These capabilities prove to be insufficient for technological companies with moderate to big workloads.
The best thing about horizontal scaling is that you have no cap on how much you can scale whenever performance degrades you simply add another machine, up to infinity potentially.
Easy scaling is not the only benefit you get from distributed systems. Fault tolerance and low latency are also equally as important.</p>
<p><strong>Fault Tolerance</strong> - a cluster of ten machines across two data centers is inherently more fault-tolerant than a single machine. Even if one data center catches on fire, your application would still work.</p>
<p><em>An important part of distributed systems is the CAP theorem, which states that a distributed data store cannot simultaneously be consistent, available, and partition tolerant</em>.</p>
<p><strong>Low Latency</strong> — The time for a network packet to travel the world is physically bounded by the speed of light. For example, the shortest possible time for a request‘s <strong>round-trip</strong> time (that is, go back and forth) in a fiber-optic cable between New York to Sydney is 160ms. Distributed systems allow you to have a node in both cities, allowing traffic to hit the node that is closest to it.</p>
<p>For a distributed system to work, though, you need the software running on those machines to be specifically designed for running on multiple computers at the same time and handling the problems that come along with it. This turns out to be no easy feat.</p>
<h2 id="key-characteristics-of-distributed-systems"><strong>Key Characteristics of Distributed Systems</strong></h2>
<h3 id="scalability"><strong>Scalability</strong></h3>
<p>Scalability is the capability of a system, process, or network to grow and manage increased demand. Any distributed system that can continuously evolve to support the growing amount of work is considered scalable.</p>
<p>A system may have to scale because of many reasons like increased data volume or increased work, e.g., number of transactions. A scalable system would like to achieve this scaling without performance loss.</p>
<p>Generally, although designed (or claimed) to be scalable, the performance of a system declines with the system size due to the management or environmental cost. For instance, network speed may become slower because machines tend to be far apart from one another. More generally, some tasks may not be distributed, either because of their inherent atomic nature or some flaw in the system design. At some point, such tasks would limit the speed-up obtained by distribution. A scalable architecture avoids this situation and attempts to balance the load on all the participating nodes evenly.</p>
<p><strong>Horizontal vs. Vertical Scaling</strong>
Horizontal scaling means that you scale by adding more servers into your pool of resources, whereas Vertical scaling means that you scale by adding more power (CPU, RAM, Storage, etc.) to an existing server.</p>
<p>With horizontal scaling, it is often easier to scale dynamically by adding more machines into the existing pool; Vertical-scaling is usually limited to the capacity of a single server. Scaling beyond that capacity often involves downtime and comes with an upper limit.
Good examples of horizontal scaling are <strong>Cassandra </strong>and <strong>MongoDB</strong>, as they both provide an easy way to scale horizontally by adding more machines to meet growing needs. Similarly, a good example of vertical scaling is MySQL, as it allows for an easy way to scale vertically by switching from small to bigger machines. However, this process often involves downtime.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633592128354/PF2VfEl7K.png" alt="ver vs horz.png" /></p>
<h3 id="reliability"><strong>Reliability</strong></h3>
<p>By definition, reliability is the probability a system will fail in a given period. In simple terms, a distributed system is considered reliable if it keeps delivering its services even when one or several of its software or hardware components fail. Thus, reliability represents one of the main characteristics of any distributed system. Any failing machine can always be replaced by another healthy one in such systems, ensuring the completion of the requested task.</p>
<p>Take the example of a large electronic commerce store (like Amazon), where one of the primary requirements is that any user transaction should never be canceled due to a failure of the machine running that transaction. For instance, if a user has added an item to their shopping cart, the system is expected not to lose it. A reliable distributed system achieves this through the redundancy of both the software components and data. If the server carrying the user’s shopping cart fails, another server with the replica of the shopping cart should replace it.
Redundancy has a cost, and a reliable system has to pay to achieve such resilience for services by eliminating every single point of failure.</p>
<h3 id="availability"><strong>Availability</strong></h3>
<p>By definition, availability is when a system remains operational to perform its required function in a specific period. It is a simple measure of the percentage of time that a system, service, or machine remains operational under normal conditions. For example, an aircraft that can be flown for many hours a month without much downtime has high availability. Availability takes into account maintainability, repair time, spares availability, and other logistics considerations. If an aircraft is down for maintenance, it is considered not available during that time.</p>
<p>Reliability is availability over time, considering the full range of possible real-world conditions that can occur. For example, an aircraft that can make it through any possible weather safely is more reliable than one that has vulnerabilities to possible conditions.</p>
<h3 id="reliability-vs-availability"><strong>Reliability Vs. Availability</strong></h3>
<p>If a system is reliable, it is available. However, if it is available, it is not necessarily reliable.
In other words, high reliability contributes to high availability. Still, it is possible to achieve a high availability even with an unreliable product by minimizing repair time and ensuring that spares are always available when they are needed.</p>
<p>Let’s take the example of an online retail store with 99.99% availability for the first two years after its launch. However, the system was launched without any information security testing. The customers were happy with the system, but they don’t realize that it isn’t very reliable as it is vulnerable to likely risks. In the third year, the system experiences a series of information security incidents that suddenly result in extremely low availability for extended periods. This results in reputational and financial damage to the customers.</p>
<h3 id="efficiency"><strong>Efficiency</strong></h3>
<p>To understand how to measure the efficiency of a distributed system, let’s assume an operation that runs in a distributed manner and delivers a set of items as a result.</p>
<p>Two standard measures of its efficiency are the response time (or latency) that denotes the delay to obtain the first item, and the throughput (or bandwidth), which denotes the number of items delivered in a given time unit (e.g., a second). The two measures correspond to the following unit costs:</p>
<ul>
<li><p>The number of messages globally sent by the nodes of the system, regardless of the message size.</p>
</li>
<li><p>Size of messages representing the volume of data exchanges.</p>
</li>
</ul>
<p>The complexity of operations supported by distributed data structures (e.g., searching for a specific key in a distributed index) can be characterized as a function of one of these cost units. Generally speaking, the analysis of a distributed structure in terms of the ‘number of messages’ is over-simplistic. It ignores the impact of many aspects, including the network topology, the network load, variation, the possible heterogeneity of the software and hardware components involved in data processing and routing, etc. However, it is quite difficult to develop a precise cost model that would accurately consider all these performance factors. Therefore, we’ve to live with rough but robust estimates of the system behavior.</p>
<h3 id="serviceability-or-manageability"><strong>Serviceability or Manageability</strong></h3>
<p>Another important consideration while designing a distributed system is how easy it is to operate and maintain. Serviceability or manageability is the simplicity and speed with which a system can be repaired or maintained</p>
<p>If the time to fix a failed system increases, then availability will decrease. Things to consider for manageability are the ease of diagnosing and understanding problems when they occur, ease of making updates or modifications, and how simple the system is to operate (i.e., does it routinely operate without failure or exceptions?).</p>
<p>Early detection of faults can decrease or avoid system downtime. For example, some enterprise systems can automatically call a service center (without human intervention) when the system experiences a system fault.</p>
<h3 id="challenges-of-distributed-systems"><strong>Challenges of distributed systems</strong></h3>
<p>Distributed systems are considerably more complex than monolithic computing environments, and raise a number of challenges around design, operations and maintenance. These include:</p>
<p><strong>Increased opportunities for failure:</strong> The more systems added to a computing environment, the more opportunity there is for failure. If a system is not carefully designed and a single node crashes, the entire system can go down. While distributed systems are designed to be fault tolerant, that fault tolerance isn’t automatic or foolproof.</p>
<p><strong>Synchronization process challenges:</strong> Distributed systems work without a global clock, requiring careful programming to ensure that processes are properly synchronized to avoid transmission delays that result in errors and data corruption. In a complex system — such as a multiplayer video game — synchronization can be challenging, especially on a public network that carries data traffic.</p>
<p><strong>Imperfect scalability:</strong> Doubling the number of nodes in a distributed system doesn’t necessarily double performance. Architecting an effective distributed system that maximizes scalability is a complex undertaking that needs to take into account load balancing, bandwidth management and other issues.</p>
<p><strong>More complex security:</strong> Managing a large number of nodes in a heterogeneous or globally distributed environment creates numerous security challenges. A single weak link in a file system or larger distributed system network can expose the entire system to attack.</p>
<p><strong>Increased complexity:</strong> Distributed systems are more complex to design, manage and understand than traditional computing environments.</p>
<h3 id="risks-of-distributed-systems"><strong>Risks of distributed systems</strong></h3>
<p>The challenges of distributed systems as outlined above create a number of correlating risks. These include:</p>
<p><strong>Security</strong>: Distributed systems are as vulnerable to attack as any other system, but their distributed nature creates a much larger attack surface that exposes organizations to threats.</p>
<p><strong>Risk of network failure:</strong> Distributed systems are beholden to public networks in order to transmit and receive data. If one segment of the internet becomes unavailable or overloaded, distributed system performance may decline.</p>
<p><strong>Governance and control issues:</strong> Distributed systems lack the governability of monolithic, single-server-based systems, creating auditing and adherence issues around global privacy laws such as GDPR. Globally distributed environments can impose barriers to providing certain levels of assurance and impair visibility into where data resides.</p>
<p><strong>Cost control:</strong> Unlike centralized systems, the scalability of distributed systems allows administrators to easily add additional capacity as needed, which can also increase costs. Pricing for cloud-based distributed computing systems are based on usage (such as the number of memory resources and CPU power consumed over time). If demand suddenly spikes, organizations.</p>
<h3 id="distributed-system-architecture"><strong>Distributed System Architecture</strong></h3>
<p><strong>Distributed systems must have a network that connects all components (machines, hardware, or software) together so they can transfer messages to communicate with each other.</strong></p>
<ul>
<li><p>That network could be connected with an IP address or use cables or even on a circuit board.</p>
</li>
<li><p>The messages passed between machines contain forms of data that the systems want to share like databases, objects, and files.</p>
</li>
<li><p>The way the messages are communicated reliably whether it’s sent, received, acknowledged or how a node retries on failure is an important feature of a distributed system.</p>
</li>
<li><p>Distributed systems were created out of necessity as services and applications needed to scale and new machines needed to be added and managed. In the design of distributed systems, the major trade-off to consider is complexity vs performance.</p>
</li>
</ul>
<h3 id="types-of-distributed-system-architectures"><strong>Types of Distributed System Architectures:</strong></h3>
<p>Distributed applications and processes typically use one of four architecture types below:</p>
<p><strong>Client-server:</strong>
In the early days, distributed systems architecture consisted of a server as a shared resource like a printer, database, or a web server. It had multiple clients (for example, users behind computers) that decide when to use the shared resource, how to use and display it, change data, and send it back to the server. Code repositories like git is a good example where the intelligence is placed on the developers committing the changes to the code.</p>
<p>Today, distributed systems architecture has evolved with web applications into:</p>
<p><strong>Three-tier:</strong> In this architecture, the clients no longer need to be intelligent and can rely on a middle tier to do the processing and decision making. Most of the first web applications fall under this category. The middle tier could be called an agent that receives requests from clients, that could be stateless, processes the data and then forwards it on to the servers.</p>
<p><strong>Multi-tier:</strong> Enterprise web services first created n-tier or multi-tier systems architectures. This popularized the application servers that contain the business logic and interacts both with the data tiers and presentation tiers.</p>
<p><strong>Peer-to-peer:</strong> There are no centralized or special machine that does the heavy lifting and intelligent work in this architecture. All the decision making and responsibilities are split up amongst the machines involved and each could take on client or server roles. Blockchain is a good example of this.</p>
<h3 id="distributed-data-stores"><strong>Distributed Data Stores</strong></h3>
<p>Distributed Data Stores are most widely used and recognized as Distributed Databases. Most distributed databases are <strong>NoSQL </strong>non-relational databases, limited to key-value semantics. They provide incredible performance and scalability at the cost of consistency or availability.</p>
<p>We cannot go into discussions of distributed data stores without first introducing the <strong>CAP Theorem.</strong></p>
<p><strong>CAP Theorem</strong>
The CAP theorem states that a distributed data store cannot simultaneously be consistent, available and partition tolerant.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633593042433/7ODRuqTB_.png" alt="captheorem.png" /></p>
<p><strong>Some quick definitions:</strong></p>
<ul>
<li><p>Consistency — What you read and write sequentially is what is expected</p>
</li>
<li><p>Availability — the whole system does not die — every non-failing node always returns a response.</p>
</li>
<li><p>Partition Tolerant — The system continues to function and uphold its consistency/availability guarantees in spite of network partitions</p>
</li>
</ul>
<p>In reality, partition tolerance must be a given for any distributed data store. As mentioned in many places, one of which this great article, you cannot have consistency and availability without partition tolerance.</p>
<p>Think about it: if you have two nodes which accept information and their connection dies — how are they both going to be available and simultaneously provide you with consistency? They have no way of knowing what the other node is doing and as such have can either become offline (unavailable) or work with stale information (inconsistent).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633620503172/1cH13n2d2.png" alt="cap2.png" /></p>
<p>In the end you’re left to choose if you want your system to be strongly consistent or highly available under a network partition.</p>
<p>Practice shows that most applications value availability more. You do not necessarily always need strong consistency. Even then, that trade-off is not necessarily made because you need the 100% availability guarantee, but rather because network latency can be an issue when having to synchronize machines to achieve strong consistency. These and more factors make applications typically opt for solutions which offer high availability.</p>
<p>Such databases settle with the weakest consistency model — eventual consistency (strong vs eventual consistency explanation). This model guarantees that if no new updates are made to a given item, eventually all accesses to that item will return the latest updated value.</p>
<p>Those systems provide BASE properties (as opposed to traditional databases’ ACID)</p>
<ul>
<li><strong>Basically Available</strong> — The system always returns a response</li>
</ul>
<ul>
<li><strong>Soft state</strong> — The system could change over time, even during times of no input (due to eventual consistency)</li>
</ul>
<ul>
<li><strong>Eventual consistency</strong> — In the absence of input, the data will spread to every node sooner or later — thus becoming consistent</li>
</ul>
<p>Examples of such available distributed databases — Cassandra, Riak, Voldemort</p>
<p>Of course, there are other data stores which prefer stronger consistency — HBase, Couchbase, Redis, Zookeeper</p>
<p>The CAP theorem is worthy of multiple articles on its own — some regarding how you can tweak a system’s CAP properties depending on how the client behaves and others on how it is not understood properly.</p>
<h3 id="cassandra"><strong>Cassandra</strong></h3>
<p>Cassandra, as mentioned above, is a distributed No-SQL database which prefers the AP properties out of the CAP, settling with eventual consistency. I must admit this may be a bit misleading, as Cassandra is highly configurable — you can make it provide strong consistency at the expense of availability as well, but that is not its common use case.</p>
<p>Cassandra uses consistent hashing to determine which nodes out of your cluster must manage the data you are passing in. You set a replication factor, which basically states to how many nodes you want to replicate your data.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633620691075/BbS74SXnE.png" alt="cassandra.png" /></p>
<p>When reading, you will read from those nodes only.</p>
<p>Cassandra is massively scalable, providing absurdly high write throughput.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633620718504/qn6LiiL9n9.png" alt="cassandra2.png" /></p>
<p>Even though this diagram might be biased and it looks like it compares Cassandra to databases set to provide strong consistency (otherwise I can’t see why MongoDB would drop performance when upgraded from 4 to 8 nodes), this should still show what a properly set up Cassandra cluster is capable of.</p>
<p>Regardless, in the distributed systems trade-off which enables horizontal scaling and incredibly high throughput, Cassandra does not provide some fundamental features of ACID databases — namely, transactions.</p>
<h3 id="distributed-messaging"><strong>Distributed Messaging</strong></h3>
<p>Messaging systems provide a central place for storage and propagation of messages/events inside your overall system. They allow you to decouple your application logic from directly talking with your other systems.</p>
<p>Known Scale — LinkedIn’s Kafka cluster processed 1 trillion messages a day with peaks of 4.5 millions messages a second.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1633620837561/onsnqypTg.png" alt="distributed massage.png" /></p>
<p>Simply put, a messaging platform works in the following way:
A message is broadcast from the application which potentially create it (called a producer), goes into the platform and is read by potentially multiple applications which are interested in it (called consumers).</p>
<p>If you need to save a certain event to a few places (e.g user creation to database, warehouse, email sending service and whatever else you can come up with) a messaging platform is the cleanest way to spread that message.</p>
<p>Consumers can either pull information out of the brokers (pull model) or have the brokers push information directly into the consumers (push model).</p>
<p>There are a couple of popular top-notch messaging platforms:
<strong>RabbitMQ </strong>— Message broker which allows you finer-grained control of message trajectories via routing rules and other easily configurable settings. Can be called a smart broker, as it has a lot of logic in it and tightly keeps track of messages that pass through it. Provides settings for both AP and CP from CAP. Uses a push model for notifying the consumers.</p>
<p><strong>Kafka </strong>— Message broker (and all out platform) which is a bit lower level, as in it does not keep track of which messages have been read and does not allow for complex routing logic. This helps it achieve amazing performance. In my opinion, this is the biggest prospect in this space with active development from the open-source community and support from the Confluent team. Kafka arguably has the most widespread use from top tech companies. I wrote a thorough introduction to this, where I go into detail about all of its goodness.</p>
<p><strong>Apache ActiveMQ</strong> — The oldest of the bunch, dating from 2004. Uses the JMS API, meaning it is geared towards Java EE applications. It got rewritten as ActiveMQ Artemis, which provides outstanding performance on par with Kafka.</p>
<p><strong>Amazon SQS</strong> — A messaging service provided by AWS. Lets you quickly integrate it with existing applications and eliminates the need to handle your own infrastructure, which might be a big benefit, as systems like Kafka are notoriously tricky to set up. Amazon also offers two similar services — SNS and MQ, the latter of which is basically ActiveMQ but managed by Amazon.</p>
<h3 id="data-copying"><strong>Data Copying</strong></h3>
<p>Copying is another foundational concept in computing. In software design we use the concept of taking data copies to achieve speed and resilience in several different ways.</p>
<p><strong>Replicas</strong>
A data replica is an exact copy of a database. Replicas are constantly, iteratively synced with one another so their contents are kept as identical as possible. They generally come in two flavours, active and passive. Active replicas support read and write access and play an (unsurprisingly) active role in serving clients. Active replicas can help with scale, resilience and location-base performance. Passive replicas are generally maintained for failover purposes; they don’t support read or write and are only synced in one direction (from the master data). The job of a passive replica is to be ready to take over from the main replica if it fails.</p>
<p><strong>Caches</strong>
Unlike a replica, a cache is a not-necessarily-identical, read-only, copy of your data, usually maintained as a way to serve read requests faster and more cheaply than querying your main database. Caches may take advantage of</p>
<ul>
<li><p>Location (keeping information physically close to the reading client).</p>
</li>
<li><p>Medium (keeping information in faster-to-access physical media like memory rather than disk).</p>
</li>
<li><p>Design (maintaining information in data structures optimised for fast read like key/value stores or graphs).</p>
</li>
</ul>
<p><strong>Backups</strong>
A backup is a copy of your data for emergency use in the case of catastrophic data loss. Usually a backup is written to a permanent storage medium like disk in multiple physical locations. Backups are slow to write to and restore from and usually they are not kept constantly in sync with the master data. Instead, they are periodically updated. They are useful but have severe limitations and can easily lull folk into a false sense of security. This false security becomes especially dangerous as the scale and complexity of a system increases.</p>
<p><strong>Denormalization for Decoupling</strong>
Data duplication goes in and out of fashion as an architectural technique. It is often frowned upon because it’s a common cause of bugs. On the other hand, it is very useful for performance. Basically, like everything in life it has pros and cons and we need to make a judgment on whether to use it based on the current circumstances.</p>
<p>A decade ago we spent ages “normalizing” our databases, or removing data duplication. However in a distributed system we really need to have data available in more than one location. Every service cannot be calling back to the same database all the time or we lose all the benefits of distribution. Microservices usually maintain local equivalents of certain pieces of data that they can write and read without worrying about anyone else.</p>
<p>BUT the potential bugs have not mysteriously gone away. We have to somehow keep all those data copies in alignment (that doesn’t necessarily mean identical). By using data duplication we have to accept that we’ve just included an architectural technique that can be very bug prone in our design. It’s a tradeoff. It just means that we have to use development techniques that help resolve those problems such as Domain Driven Design, or operational techniques like managed stateful services that handle some of these issues for us.</p>
<p><strong>Decentralized vs Distributed</strong>
Before we go any further I’d like to make a distinction between the two terms.</p>
<p>Even though the words sound similar and can be concluded to mean the same logically, their difference makes a significant technological and political impact.</p>
<p><strong>Decentralized </strong>is still <strong>distributed</strong> in the technical sense, but the whole decentralized systems is not owned by one actor. No one company can own a decentralized system, otherwise it wouldn’t be decentralized anymore.</p>
<p>This means that most systems we will go over today can be thought of as <strong>distributed centralized systems</strong> — and that is what they’re made to be.</p>
<p>Decentralized is essentially distributed on a technical level, but usually a decentralized system is not owned by a single source.</p>
<p>If you think about it — it is harder to create a decentralized system because then you need to handle the case where some of the participants are malicious. This is not the case with normal distributed systems, as you know you own all the nodes.</p>
<p><em>This has been debated a lot and can be confused with others (peer-to-peer, federated). In early literature, it’s been defined differently as well. Regardless, what I gave you as a definition is what I feel is the most widely used now that blockchain and cryptocurrencies popularized the term</em>.</p>
<p><strong>Cloud vs distributed systems</strong>
Cloud computing and distributed systems are different, but they use similar concepts. Distributed computing uses distributed systems by spreading tasks across many machines. Cloud computing, on the other hand, uses network hosted servers for storage, process, data management.</p>
<p>Distributed computing aims to create collaborative resource sharing and provide size and geographical scalability. Cloud computing is about delivering an on demand environment using transparency, monitoring, and security.</p>
<p>Compared to distributed systems, cloud computing offers the following advantages:</p>
<ul>
<li><p>Cost effective</p>
</li>
<li><p>Access to a global market</p>
</li>
<li><p>Encapsulated change management</p>
</li>
<li><p>Access storage, servers, and databases on the internet</p>
</li>
</ul>
<p>However, cloud computing is arguably less flexible than distributed computing, as you rely on other services and technologies to build a system. This gives you less control overall.</p>
<p>Priorities like load-balancing, replication, auto-scaling, and automated back-ups can be made easy with cloud computing. Cloud building tools like Docker, Amazon Web Services (AWS), Google Cloud Services, or Azure make it possible to create such systems quickly, and many teams opt to build distributed systems alongside these technologies.</p>
]]></content:encoded></item><item><title><![CDATA[Is C# really dying.? Future of C#.!]]></title><description><![CDATA[Future of c# should you learn it in 2021 c# can be used for web dev mobile development embedded system .net core and MVC is blazor future of web…]]></description><link>https://alphac0des.hashnode.dev/is-c-really-dying-future-of-c</link><guid isPermaLink="true">https://alphac0des.hashnode.dev/is-c-really-dying-future-of-c</guid><category><![CDATA[Developer]]></category><category><![CDATA[C#]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Mobile Development]]></category><category><![CDATA[Blazor ]]></category><dc:creator><![CDATA[Mukul Attavania]]></dc:creator><pubDate>Tue, 07 Sep 2021 19:18:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1631041956693/wVn4c2Pvh.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>C# is a general-purpose programming language. Technically speaking, you can use it for anything other than what has been developed. There are many coding styles suitable for the C# programming language (it can be used for both functional programming style and object-oriented programming style). It is compiled and strongly typed which means it is easier in doing development but if you are shipping your code into production , there’s little bit more to it.</p>
<p>C# was developed by Microsoft in 2000 in response to JAVA. They have some similarities, such as strongly typed,compiled, Object-Oriented ,working on a virtual machine and many more. C# provides support for Modern days functionalities for all kind of software development such as front-end ,back-end, mobile ,etc.</p>
<p>Lets talk about some pros and cons
PROS
Jobs- The question a person asks when choosing a programming language is “Can I use this to find a job?” No matter what career site you search , C# and .Net developers are most assault after programmers on the platform.There are a lot of jobs out there .</p>
<p>Tools- Visual studio is one of the best and most popular IDE in the market.</p>
<p>Frameworks- .NET Core is cross platform variant of .NET framework &amp; Xamarin used for cross platform Mobile ddevelopment</p>
<p>Cross Platform- It means it allows our C# programs to run on multiple platform instead of only windows machine.</p>
<p>Speed- C# is fast compared to same Modern day interpreted programming languages such as Python and Javascript.</p>
<p>CONS
Learning Curve- Compared to some modern programming languages such as Python or Javscript .C# is quite had to learn.</p>
<p>Is C# Dying..?Should you learn C# in 2021?</p>
<p>My answer would be NO, C# is not dying and YES you should learn it in 2021 because of such new and upcoming features for every programming need.</p>
<p>If you are building a web application, you will consider where it should be hosted, and .Net allows you to host it on a host of your choice. In the past, you had to host to Windows &amp; it would be more expensive compared to a linux host. For an enterprise this can be very important, because you can now host on AWS, Heroku, Windows, Azure, and Linux (in short, you can choose to host).</p>
<p>Let’s talk about some key points in C#
Web Application Development- There is a framework called ASP.Net, under this framework it brings MVC and Web assembly world using Blazor. Many Enterprise solutions are made using C# because of built in scaffolding ,OEM using entity framework ,security called Identity which allows you to build very fast, secure and scalable application.</p>
<p>Another approach to web development is Blazor, because Microsoft puts Blazor at the top of the MVC and Razor pages, because it is the future of web development. So, if u need to learn one thing it’ll be ASP.net but if you are already coding for a living and already doing things then take a look at Blazor because it has the best implementation so far in web Assembly till date &amp; Another approach to web development is Blazor, because Microsoft puts Blazor at the top of the MVC and Razor pages, because it is the future of web development.</p>
<p>Mobile Development- Writing a single code base that supports Android and IOS devices gives us cross-platform mobile development. There are basically three ways to do this: React Native, Google’s Dart / Flutter, and Microsoft’s Xamarin.</p>
<p>Xamarin allows us to create a user interface that supports IOS and Android natively, and it also allows us to share business layer logic code between multiple platforms. Applications developed by Xamarin can run on Android devices, IOS, and Windows / Mac OS desktops. Since it is now open source, the community can jump in and build things that can extend Xamarin to infinity</p>
<p>With C #, you can use ASP.net and the Web API to create microservices or service-based sites, allowing you to run these functions sometimes without using infrastructure in your traditional web hosting or service functions. You can create these microservice patterns and host them on Azure, AWS, or a host of your choice.</p>
<p>Game Development- Build a game inside of C# in Unity that will allow you be break into Game Development.</p>
<p>There’s Embeded, Machine Learning as well as Internet of things(IOT) which are being supported by C# &amp; Microsoft.</p>
<p>CLOUD- Microsoft provides you with one of the most powerful cloud platforms known on Azure. It provides you with cognitive services, enables you to perform speech recognition and text-to-speech services, and uses ML.Net for machine learning.</p>
<p>The great thing about C # and .Net is that it is now open source and the tools are free earlier it was not </p>
]]></content:encoded></item></channel></rss>