<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Priyanka Masne on Medium]]></title>
        <description><![CDATA[Stories by Priyanka Masne on Medium]]></description>
        <link>https://medium.com/@masne?source=rss-60e3040958d7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*D_VeVvcn5xOmiwIozL7wkg.jpeg</url>
            <title>Stories by Priyanka Masne on Medium</title>
            <link>https://medium.com/@masne?source=rss-60e3040958d7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:33:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@masne/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Many Universes]]></title>
            <link>https://masne.medium.com/many-universes-78c5b6c2350a?source=rss-60e3040958d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/78c5b6c2350a</guid>
            <category><![CDATA[wave-function]]></category>
            <category><![CDATA[schrodingers-cat]]></category>
            <category><![CDATA[quantum-physics]]></category>
            <category><![CDATA[many-worlds-theory]]></category>
            <dc:creator><![CDATA[Priyanka Masne]]></dc:creator>
            <pubDate>Thu, 07 Oct 2021 19:59:02 GMT</pubDate>
            <atom:updated>2021-10-08T05:30:43.326Z</atom:updated>
            <content:encoded><![CDATA[<p>Sending love to your wave function! :)</p><p>I recently read a book called “What is Real?” by Adam Becker which left me questioning every damn phenomenon in life. This happens to be my first book on quantum physics and also the first book that gave me ideas to elicit a “you need to move out of my house” from my Mom! :P</p><p>The first quantum physics fact that amazed me from the book is that a single atom can appear in two places at once. When an atom wandering down a path finds a fork where it can go left or right, it travels down both the paths, thumbing its nose at the laws of logic. At any fork, the atom suffers a crisis of indecision over where to be and where not to be and end up taking both paths.</p><p>This troubles me because I am made of atoms but I still do not have the ability to appear in two places at once. Neither does my glasses which I end up searching for hours every morning! Duhh!</p><p>Schrödinger was also troubled by this and that’s where Schrödinger’s Cat came into picture. Wow! I never understood Schrödinger’s Cat ever before :D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RYqXOxH6AGTwx30AhdKOow.png" /><figcaption>Source: What is Real? by Adam Becker</figcaption></figure><p>Schrödinger imagined an experimental setup with a Cat in a box along with a sealed glass vine of cyanide, with a small hammer hanging over the vial. The hammer would be connected to a Geiger counter, which detects radioactivity. This Geiger counter, in turn, would be pointed at a tiny lump of slightly radioactive metal. This contraption would set off the moment the metal emitted radiation — the Geiger counter would register the radiation, which would release the hammer, smashing the vial and killing the cat.</p><p>The radiation from the radioactive metal is basically atoms flying off at great speeds. The atoms, following the laws of quantum physics, do not know whether they should stay or they should go. So, they do both. Hence, the radioactive metal will and won’t emit radiation. This means that hammer will and won’t smash the vial of cyanide — so the Cat will be both dead and alive.</p><p>This is a serious problem — a Cat certainly can’t be both dead and alive. The submicroscopic world of quantum does not line up with what we see in the world around us.</p><p>There are many theories that have attempted to find that connection between the quantum world and the universe but none of these seem to allay my questions. However one such theory which has left me in deep thoughts is Everett’s “many-worlds” interpretation of quantum physics.</p><p>Many-worlds interpretation states that the entire universe was a single wave function when it all started. Each experiment, each quantum event, spun off new branches of the universal wave function, creating a multitude of universes in which that one event had every possible outcome.</p><p>As interesting as it seemed, the many-worlds interpretation left me with many questions. Every event is essentially interaction of atoms and hence is a quantum event. If every damn event leads the universe to split, where are these other universes? How many such universes are there? Am I existing in multiple universes? A Masne in every such universe? 😯</p><p>Let’s look at how many-worlds interpretation explains the Schrödinger experiment’s result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1t1huU87j2WHqlRd8uUGQ.png" /><figcaption>Source: What is Real? by Adam Becker</figcaption></figure><p>The wave function of the radioactive metal is half “radiation was emitted” and half “no radiation was emitted”. That interacts with the wave function of the detector, which means they get entangled. Eventually the wave function of hammer entangles with the wave function of metal and detector; the wave function of the vial entangles with that of metal, detector and hammer, and so on, eventually including the cat itself. The whole system — cat, box, metal, poison and all — ultimately ends up sharing a single wave function and the wave function has two equal parts : one in which radiation was emitted and the cat is dead, and another one in which no radiation was emitted and the cat is alive.</p><p>But what happens when I open the box? Well, when I open the box, I interact with it — which means I get entangled to the wave function of the box and everything in it. There are still 2 wave functions that entangled separately with my wave function and now I am split into two!! Whaaaat? 😯</p><p>Each wave function carry on independently of the others, with hardly any interaction between the branches. Hence, I never get to meet the Masne from the next wave function/universe. Or may be I do? 😯</p><p>I dropped a glass jar today morning, which fell on my feet and then bounced and finally landed on the concrete floor. To my surprise, it did not break. Oh well, I think it just did not break in my wave function but I totally envision a Masne getting slapped by her Mom in the next universe! ;) #SorryMasne</p><p>This post has been inspired by a number of events in my universe —</p><ol><li>My Mom absolutely thinks I have lost it and she has served me a notice to move out sooner. So, medium felt like the platform where I can dump my interpretations that are also very inscrutable to myself. Anyone up for more of this? Hit me up!</li><li>I lost an acquaintance recently to an unfortunate accident and was regretting having not interacted much with. I think I happen to be in the wrong wave function/universe in this case and I am sure we do catch up on random coffee breaks in the happier wave function. :)</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78c5b6c2350a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Code]]></title>
            <link>https://masne.medium.com/clean-code-52ac0b9d5887?source=rss-60e3040958d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/52ac0b9d5887</guid>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Priyanka Masne]]></dc:creator>
            <pubDate>Mon, 19 Jul 2021 15:12:40 GMT</pubDate>
            <atom:updated>2022-06-25T23:07:06.992Z</atom:updated>
            <content:encoded><![CDATA[<p>Code is all about communication and communication is the professional developer’s first order of business</p><p>Functions should be as <strong>small</strong> as possible. The blocks within “if”, “else”, “while” statements should be one line long (probably a function call). The indent level of a function should not be greater than one or two.</p><pre>public static String renderPageWithSetupAndTeardowns(PageData pageData, boolean isSuite) throws Exception {<br>    if(isTestPage(pageData))<br>        includeSetupAndTeardownPages(pageData, isSuite);<br>    return pageData.getHtml();<br>}</pre><p>Functions should <strong>do one thing</strong> and do it well —</p><ol><li>If a function does some steps that is just 1 level below the stated name of function, then it is doing just one thing</li><li>Functions doing one thing cannot be reasonably divided into sections — declarations, initializations, implementation etc</li></ol><pre>public Money calculatePay(Employee e) throws InvalidEmployeeType {<br>    switch(e.type) {<br>        case COMMISIONED:<br>            return calculateCommissionedPay(e);<br>        case HOURLY:<br>            return calculateHourlyPay(e);<br>        case SALARIED:<br>            return calculateSalariedPay(e);<br>        default:<br>            throw new InvalidEmployeeType(e.type);<br>    }<br>}</pre><pre>public boolean isPayday(Employee e, Date date) throws InvalidEmployeeType {<br>    switch(e.type) {<br>        case COMMISSIONED:<br>            ....<br>    }<br>}</pre><pre>public boolean deliverPay(Employee e, Money pay) throws InvalidEmployeeType {<br>    switch(e.type) {<br>        case COMMISSIONED:<br>            ....<br>    }<br>}</pre><p>All the above functions will have to be changed every time a new type of Employee is added.</p><p><strong>Switch statement</strong> should only be tolerated if —</p><ol><li>They appear only once</li><li>are used to create polymorphic objects</li><li>are hidden behind an inheritance</li></ol><pre>public abstract class Employee {<br>    public abstract boolean isPayday(Date date);<br>    public abstract Money calculatePay();<br>    public abstract void deliverPay(Money pay);<br>}</pre><pre>public interface EmployeeFactory {<br>    public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType;<br>}</pre><pre>public class EmployeeFactoryImpl implements EmployeeFactory {<br>    public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType {<br>        switch(r.type) {<br>            case COMMISIONED:<br>                return CommissionedEmployee(r);<br>            case HOURLY:<br>                return HourlyEmployee(r);<br>            case SALARIED:<br>                return SalariedEmployee(r);<br>            default:<br>                throw new InvalidEmployeeType(r.type);<br>        }<br>    }<br>}</pre><p>The ideal <strong>no. of arguments</strong> for a function is zero, then one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) shouldn’t be used.</p><p>When a function needs 3 or more arguments, wrap it into a class of it’s own.</p><pre>Circle makeCircle(double x, double y, double radius); ❌ </pre><pre>Circle makeCircle(Point center, double radius); ✅ </pre><p>If your function must change the state of something, have it change the state of its owning object.</p><pre>public void appendFooter(String report) ❌ </pre><pre>report.appendFooter() ✅ </pre><p>Objects hide their data and expose functions that operate on them. Data structures expose their data and have no meaningful functions.</p><pre>// Data Structure<br>public class Circle {<br>    public point center;<br>    public double radius;<br>}</pre><pre>// Object<br>public class Circle {<br>    private point center;<br>    private double radius;</pre><pre>    public double area() {<br>        return PI*radius*radius;<br>    }<br>}</pre><p>Procedural vs OO programming —</p><pre><strong>// Procedural programming</strong></pre><pre>public class Square {<br>    public Point topLeft;<br>    public double side;<br>}</pre><pre>public class Rectangle {<br>    public Point topLeft;<br>    public double height;<br>    public double width;<br>}</pre><pre>public class Circle {<br>    public Point center;<br>    public double radius;<br>}</pre><pre>public class Geometry {<br>    public final double PI = 3.14;</pre><pre>    public double area(Object shape) throws NoSuchShapeException {<br>        if(shape instanceof Square) {<br>            Square s = (Square)shape;<br>            return s.side*s.side;<br>        }<br>        else if(shape instanceof Rectangle) {<br>            Rectangle r = (Rectangle)shape;<br>            return r.height*r.width;<br>        }<br>        else if(shape instanceof Circle) {<br>            Circle c = (Circle)shape;<br>            return PI * c.radius * c.radius;<br>        }<br>        throw new NoSuchShapeException();<br>    }</pre><pre>    public double perimeter(Object shape) throws NoSuchShapeException {<br>        .....<br>    }<br>}</pre><p>Now that if we add a new shape, we must change all the functions in Geometry class to deal with it. This violates <strong>Open-Close principle</strong>. The code should be Open for extension (new shapes can be added) but closed for modification (existing code should not change when new shape is added).</p><pre><strong>// Object Oriented</strong></pre><pre>public class Square implements Shape {<br>    private Point topLeft;<br>    private double side;</pre><pre>    public double area() {<br>        return side*side;<br>    }<br>}</pre><pre>public class Rectangle implements Shape {<br>    private Point topLeft;<br>    private double height;<br>    private double width;</pre><pre>    public double area() {<br>        return height * width;<br>    }<br>}</pre><pre>public class Circle implements Shape {<br>    private Point center;<br>    private double radius;<br>    private final double PI = 3.14;</pre><pre>    public double area() {<br>        return PI * radius * radius;<br>    }<br>}</pre><p>Note that in OO style, on adding a new Shape, the existing code does not change. Hence, it follows Open-Close principle.</p><p>A method <em>f</em> of a class <em>C </em>should only call the methods of —</p><ol><li><em>C</em></li><li>An object created by <em>f</em></li><li>An object passed as an argument to <em>f</em></li><li>An object held in an instance variable of <em>C</em></li></ol><p>The method <em>f </em>should not invoke methods on objects that are returned by any other method of the class <em>C.</em></p><p>Error Handling for third party APIs is a best done with wrappers around.</p><pre>ACMEPort port = new ACMEPort(12);</pre><pre>try {<br>    port.open();<br>} catch (DeviceResponseException e) {<br>    reportPortError(e);<br>    logger.log(&quot;Device response exception&quot;, e);<br>} catch (UnlockException e) {<br>    reportPortError(e);<br>    logger.log(&quot;Unlock exception&quot;, e);<br>} catch (XYZError e) {<br>    reportPortError(e);<br>    logger.log(&quot;XYZ exception&quot;, e);<br>} finally {<br>    ....<br>}</pre><p>We are roughly doing the same work regardless of the exceptions. We can simplify our code by wrapping the API —</p><pre>LocalPort port = new LocalPort(12);<br>try {<br>    port.open();<br>} catch (PortDeviceFailure e) {<br>    reportError(e);<br>    logger.log(e.getMessage(), e);<br>} finally {<br>    ....<br>}</pre><pre>public class LocalPort {<br>    private ACMEPort innerPort;</pre><pre>    public LocalPort(int portNumber) {<br>        innerPort = new ACMEPort(portNumber);<br>    }</pre><pre>    public void open() {<br>        try {<br>            innerPort.open();<br>        } catch (DeviceResponseException e) {<br>            reportPortError(e);<br>            logger.log(&quot;Device response exception&quot;, e);<br>        } catch (UnlockException e) {<br>            reportPortError(e);<br>            logger.log(&quot;Unlock exception&quot;, e);<br>        } catch (XYZError e) {<br>            reportPortError(e);<br>            logger.log(&quot;XYZ exception&quot;, e);<br>        }<br>    }<br>}</pre><p>Don’t return NULL. Don’t pass NULL into methods.</p><p>Test Driven Development (TDD) asks us to write Unit tests first, before we write production code. You may not write more production code than is sufficient to pass the currently failing test.</p><p>Classes should begin with a list of variables — public static constants, then private static variables, then private instance variables. We should avoid having public variables without a good reason.</p><p>In a class, identify all the responsibilities and then break each responsibility into a class of it’s own.</p><p>Dependency Injection. Software systems should separate the startup process — when objects are constructed and the dependencies are wired together — from the runtime logic that takes over after startup</p><pre>public Service getService() {<br>    if(service == null)<br>        service = new MyServiceImpl(...)<br>    return service;<br>}</pre><p>We have a hard-coded dependency on MyServiceImpl and everything its constructor requires. We can’t compile without resolving these dependencies, even if we never use an object of this type at runtime.</p><p>Also, testing is a problem since we cannot really mock MyServiceImpl.</p><p>DI lets us, move all the aspects of construction to a separate module and lets us design the rest of the system assuming that objects have been constructed and wired up appropriately.</p><p>In Spring, we can implement DI by creating Beans either explicitly or using annotations.</p><p><strong>Explicit creation :</strong></p><p><em>AppConfig.java</em>: A simple POJO which holds all the configuration to bootstrap your application.</p><pre>// Configuration annotation is used to indicate start <br>// of configuration for our application<br><strong>@Configuration<br>public class AppConfig {</strong><br><br>    // This method returns an instance of the Bean.<br>    // This Bean is now registered inside of the spring<br>    // and is available for us to use inside of our spring<br>    // application<br>    // All these beans are singleton by default and will only<br>    // execute this method the first time it&#39;s called<br>    <strong>@Bean(name = &quot;speakerService&quot;)<br>    public SpeakerService getSpeakerService() {<br>        return new SpeakerServiceImpl(getSpeakerRepository());<br>    }</strong><br><br>    <strong>@Bean(name = &quot;speakerRepository&quot;)<br>    public SpeakerRepository getSpeakerRepository() {<br>        return new HibernateSpeakerRepositoryImpl();<br>    }<br>}</strong></pre><p>Then, to use the AppConfig in our spring application,</p><pre><strong>public class Application {<br>    public static void main(String args[]) {</strong><br>        // We pass our AppConfig class in<br>        // AnnotationConfigApplicationContext.<br>        // This loads spring and loads configuration files into<br>        // our application context.<br>        // When this line executes, it&#39;s going to create a basic<br>        // registry with the beans defined in AppConfig.java file<br>        <strong>ApplicationContext appContext = new AnnotationConfigApplicationContext(AppConfig.class);</strong><br><br>        // Old way of calling it by creating an <br>        // instance of the class:<br>        // SpeakerService service = new SpeakerServiceImpl();<br>        // But with spring, we call the bean<br>        <strong>SpeakerService service = appContext.getBean(&quot;speakerService&quot;, SpeakerService.class);<br><br>        System.<em>out</em>.println(service.findAll().get(0).getFirstName());<br>    }<br>}</strong></pre><p>Now to inject the Bean into another class, we can use @Autowire on that class setter method —</p><pre>public class SpeakerServiceImpl implements SpeakerService {<br><br>    private SpeakerRepository repository;<br><br>    public SpeakerServiceImpl() {<br>        System.<em>out</em>.println(&quot;SpeakerServiceImpl no arg constructor&quot;);<br>    }<br><br>    @Override<br>    public List&lt;Speaker&gt; findAll() {<br>        return repository.findAll();<br>    }<br><br>    // This automatically injects the SpeakerRepository bean <br>    // into this class<br>    <strong>@Autowired</strong><br>    public void setRepository(SpeakerRepository repository) {<br>        this.repository = repository;<br>    }<br>}</pre><p><strong>Annotations :</strong></p><p>AppConfig.java —</p><pre>// Configuration annotation is used to indicate start<br>// of configuration for our application<br><strong>@Configuration</strong><br>// The text inside ComponentScan tells this is where<br>// I should begin looking for beans to autowire<br><strong>@ComponentScan({&quot;com.masne&quot;})<br>public class AppConfig {<br> </strong>   // Nothing to be defined here<strong><br>}</strong></pre><p>The service class —</p><pre><strong>// This creates a bean for SpeakerServiceImpl class without<br>// defining the actual Bean code in the AppConfig.java class</strong><br>@Service(&quot;speakerService&quot;)<br>public class SpeakerServiceImpl implements SpeakerService {<br><br>    private SpeakerRepository repository;<br><br>    public SpeakerServiceImpl() {<br>        System.<em>out</em>.println(&quot;SpeakerServiceImpl no arg constructor&quot;);<br>    }<br><br>    @Autowired<br>    public SpeakerServiceImpl(final SpeakerRepository speakerRepository) {<br>        this.repository = speakerRepository;<br>    }<br><br>    @Override<br>    public List&lt;Speaker&gt; findAll() {<br>        return repository.findAll();<br>    }<br>}</pre><p>The repository class —</p><pre><strong>// This sets up the Bean for HibernateSpeakerRepositoryImpl class<br>// without writing the Bean definition code in AppConfig.java class</strong><br>@Repository(&quot;speakerRepository&quot;)<br>public class HibernateSpeakerRepositoryImpl implements SpeakerRepository {<br><br>    @Override<br>    public List&lt;Speaker&gt; findAll() {<br>        List&lt;Speaker&gt; speakers = new ArrayList&lt;&gt;();<br><br>        Speaker speaker = new Speaker();<br>        speaker.setFirstName(&quot;Priyanka&quot;);<br>        speaker.setLastName(&quot;Masne&quot;);<br><br>        speakers.add(speaker);<br><br>        return speakers;<br>    }<br>}</pre><p>DRY Principal is commonly solved using the Template Method pattern.</p><pre>public class VacationPolicy {<br>    public void accrueUSDivisionVacation() {<br>        // code to calculate vacation based on hours worked to date<br>        // ...<br>        // code to ensure vacation meets <strong>US</strong> minimums<br>        // ...<br>        // code to apply vacation to payroll record<br>        // ...<br>    }</pre><pre>    public void accrueEUDivisionVacation() {<br>        // code to calculate vacation based on hours worked to date<br>        // ...<br>        // code to ensure vacation meets <strong>EU</strong> minimums<br>        // ...<br>        // code to apply vacation to payroll record<br>        // ...<br>    }<br>}</pre><p>The code in both the above methods is largely same except for calculation legal minimums. Avoid duplication using Template Method pattern —</p><pre>public abstract class VacationPolicy {<br>    public void accrueVacation() {<br>        calculateBaseVacationHours();<br>        alterForLegalMinimums();<br>        applyToPayroll();<br>    }</pre><pre>    private void calculateBaseVacationHours() { /* ... */ };<br>    protected abstract void alterForLegalMinimums();<br>    private void applyToPayroll() { /* ... */ };<br>}</pre><pre>public class USVacationPolicy extends VacationPolicy {<br>    @Override<br>    protected void alterForLegalMinimums() {<br>        // US specific logic<br>    }<br>}</pre><pre>public class EUVacationPolicy extends VacationPolicy {<br>    @Override<br>    protected void alterForLegalMinimums() {<br>        // EU specific logic<br>    }<br>}</pre><h3>Reference</h3><p>These are my learnings from the very famous book by Robert C Martin — Clean Code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52ac0b9d5887" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Security]]></title>
            <link>https://masne.medium.com/api-security-99aede6edfde?source=rss-60e3040958d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/99aede6edfde</guid>
            <dc:creator><![CDATA[Priyanka Masne]]></dc:creator>
            <pubDate>Sun, 11 Jul 2021 12:28:34 GMT</pubDate>
            <atom:updated>2021-07-11T12:28:34.434Z</atom:updated>
            <content:encoded><![CDATA[<p>To ensure an application is secure, developers tend to do —</p><ol><li>Input validation</li><li>Using Secure Sockets Layer (SSL) protocol</li><li>Validating content types</li><li>Maintaining audit logs</li><li>Protecting against cross-site request forgery (CSRF)</li><li>Protecting against cross-site scripting (XSS)</li></ol><p>Beyond these general web application security practices, there are additional techniques that apply specifically to web APIs that we expose to other developers or end users.</p><h4>Authentication and Authorization</h4><p>The process of verifying who you are is <strong>Authentication</strong>. Web applications usually accomplish this by asking you to log in with a username and password. This combination is checked against an existing username/password record to ensure the request is authentic.</p><p>The process of verifying that you’re permitted to do what you’re trying to do is <strong>Authorization</strong>. A web application might allow you to view a page, but not allow you to edit that page unless you are an administrator.</p><h4>Basic Authentication</h4><p>I’s the simplest technique used to enforce access control on the web. The clients send HTTP requests with an Authorization header which consists of the work “Basic” followed by a space and a string generated by combining username and password with colon (username:password) and encoding it with base64.</p><pre>Authorization: Basic dXNlcjpwYXNzd2yZA==</pre><p><strong>Disadvantages —</strong></p><ol><li>The password is sent over the wire in base64 encoding which can be easily converted into plaintext</li><li>SSL can solve #1 but once on the server side, the password may be routed in plaintext after SSL termination</li><li>Applications are required to store these credentials in plaintext or in a way that they can decrypt them</li><li>#3 can be solved using SALT and one-way hash techniques but is a security overhead</li><li>The password may be cached on the browser, if user permits. This can be stolen by the any user on the shared machine</li></ol><p>Famous companies like Facebook and Google use a more secure form of Basic authentication for login workflows. MFA adds a second layer of security. To understand more, refer <a href="https://quakkels.com/posts/what-happens-when-you-login/">https://quakkels.com/posts/what-happens-when-you-login/</a></p><h4>OAuth</h4><p>It is an open standard that allows users to grant access to applications without sharing passwords with them.</p><p><strong>Benefits of OAuth</strong></p><ol><li>The biggest benefit of OAuth is that users do not need to share passwords with the applications. For example, TripAdvisor wants to build an application that will use a user’s Facebook identity, profile, contact list and other FB data. With OAuth, tripAdvisor can redirect the user to Facebook, where they can authorize TripAdvisor to access their information. After the user authorizes the sharing of data, tripAdvisor can then call the Facebook API to fetch this information.</li><li>Second benefit is thet API providers’ users can grant selective permissions. Each application has different requirements of what data it needs from an API provider. For example, TripAdvisor would receive permission to read a user’s profile, contacts and more but it cannot post on Facebook on user’s behalf.</li><li>If at any point a user would like to revoke TripAdvisor’s access to their Facebook data, they can simply go to their Facebook settings and revoke it without changing their password.</li></ol><p><strong>Token Generation</strong></p><p>With OAuth, applications use an access token to call APIs on behalf of a user. The generation of this token happens in a multistep flow.</p><p>Before an application can start the OAuth flow, it needs to be registered with the API provider. During registration, developers provide a redirect URL to which the API provider can redirect the authorizing user. The API provider issues a client ID and client secret that are unique to the application. The client ID can be public, whereas the client secret should be kept confidential.</p><p>After the registration, the application can generate an access token by following the below steps —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/0*89fujXcqz_eU8XWk.png" /></figure><ol><li>Applications typically show users a button labeled “Continue with Facebook” or “Continue with Google”. When users click the button, they are redirected to the API provider’s authorization URL. While redirecting, the application sends client ID, the permissions requested in a parameter called <em>scope</em>, an optional unique state parameter and (optionally) a redirect URL.</li><li>The API provider should clearly indicate what permissions the application is requesting. If the user denies the authorization, they are redirected back to the application’s redirect URL with an <em>access_denied</em> error. If the user approves the request, they are redirected back to the application with an authorization code.</li><li>Upon successful authorization, the application sends the client ID, client secret, authorization code and redirect URL to the API provider to receive an access token. The authorization code provided can only be used once; this helps in preventing replay attacks. Applications can then use this access token to access resources on user’s behalf.</li></ol><p><strong>Scopes</strong></p><p>OAuth scopes are used to limit an application’s access to user’s data. For instance, an application might only need to identify a user. Rather than requesting access to all of the user’s data, the application can request access to only the user’s profile information by means of a granular OAuth scope.</p><p>Often, API providers open up their APIs without thinking too much about scopes. Only when the API begins to be widely adopted or is being abused do they start realizing the need for additional scopes and at that time, introducing new scopes becomes complicated.</p><p><strong>Token and Scope Validation</strong></p><p>After the application has received the access token, it can begin making API requests using this token by setting the HTTP <em>Authorization </em>header.</p><pre>POST /api/chat.postMessage<br>HOST slack.com<br>Content-Type: application/json<br>Authorization: Bearer xoxp-1504398475-a24afg879<br>{<br>    &quot;channel&quot;:&quot;C2J&amp;4RHT78&quot;,<br>    &quot;text&quot;:&quot;This is the message text&quot;,<br>    &quot;attachments&quot;:[{&quot;text&quot;:&quot;attachment text&quot;}]<br>}</pre><p>When receiving these requests, there are 2 things that the API provider needs to verify —</p><ol><li>Access token is valid by matching the given access token with the granted access token in your database</li><li>The access token has the required scope for the action that the request is supposed to perform</li></ol><p>If either check fails, the API should return an error like —</p><pre>{<br>    &quot;ok&quot;: false,<br>    &quot;error&quot;: &quot;missing_scope&quot;,<br>    &quot;needed&quot;: &quot;chat:write:user&quot;,<br>    &quot;provided&quot;: &quot;identify,bot,users:read&quot;<br>}</pre><p><strong>Token Expiry and Refresh Tokens</strong></p><p>OAuth protocol allows limiting the validity of the access token. Many APIs chose to issue tokens that expire in few hours or days, so that the impact of a compromise can be contained.</p><p>If an access token is issued with limited validity, there should be a way for applications to obtain a new token. One way to do this is by issuing <em>refresh tokens</em>.</p><p>A refresh token is a special token used to obtain a new access token when the current access token expires. Applications need to provide the client ID, client secret and the refresh token to generate a new access token.</p><p>Even if the access token does not expire, it can be a good idea to share refresh tokens. This way, in case of compromise, an app developer can rotate an existing access token and generate a new one.</p><p>Short lived access tokens are more secure because —</p><ol><li>If an access token is compromised, it will work only until it expires.</li><li>If a refresh token is compromised, it will be useless without the client secret, which is typically not stored with access tokens or refresh tokens.</li><li>If both the refresh token and the client secret are compromised and the attacker generates a new access token, the compromise can potentially be detected because typically refresh tokens are one-time use only.</li></ol><p><strong>Listing and Revoking Authorizations</strong></p><p>For various reasons, a user might want to know which applications can access their data and might want to revoke access to one or more of them. To support this use case, most API providers typically offer a page that lists the applications that a user has authorized along with the ability to revoke access.</p><p>A snapshot of how FB provides this feature to users—</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mnLiQ6a4fkDvpYjbKmFGsA.png" /></figure><p><strong>Best practice : </strong>Because access tokens are sent as part of every HTTP request, it’s important that your API endpoints require HTTPS. This prevents man-in-the-middle attacks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99aede6edfde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Paradigms]]></title>
            <link>https://masne.medium.com/api-paradigms-f300d01ee811?source=rss-60e3040958d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f300d01ee811</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[rpc]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Priyanka Masne]]></dc:creator>
            <pubDate>Mon, 28 Jun 2021 18:38:50 GMT</pubDate>
            <atom:updated>2021-07-10T17:43:04.922Z</atom:updated>
            <content:encoded><![CDATA[<p>Building blocks for interoperability of major business platforms</p><h3>Application Programming Interface</h3><p><strong>What? —</strong> An API is the interface that a software program presents to other programs, to humans and in case of web APIs, to the world via the internet.</p><p><strong>Why? — </strong>APIs have emerged out of a need to exchange information with providers of data who are equipped to solve a specific problem, so folks at other companies don’t have to spend time solving those problems themselves.</p><p><strong>For whom? — </strong>It depends on the use-case. It is important that we specify our API to our customers and validate it long before we start to implement it. The cost of switching from one API design to another is extremely high.</p><p><strong>API Paradigm? — </strong>It defines the interface exposing backend data of a service to other applications. There are many paradigms — REST, RPC, GraphQL, WebHooks, WebSockets etc.</p><h3>Request-Response APIs</h3><p>Request-Response APIs typically expose an interface through an HTTP-based web server. These APIs define a set of endpoints. Clients make HTTP requests for data to those endpoints and the server returns responses typically as JSON or XML.</p><p>Request-Response APIs are typically exposed by 3 common paradigms — REST, RPC and GraphQL.</p><h4>Hypertext Transfer Protocol</h4><p>HTTP is an application layer protocol designed to transfer data between networked devices. A typical flow over HTTP involves a client machine making a request to a server, which then sends a response back.</p><p>A typical <strong>HTTP request</strong> contains —</p><ol><li>HTTP version type</li><li>a URL</li><li>an HTTP method — GET, POST, PUT, PATCH, DELETE</li><li>HTTP request headers</li><li>HTTP body (optional)</li></ol><p>Just like Web pages, APIs have <strong>URLs and addresses</strong> too. Defining these URLs/Addresses comes under paradigms — REST, RPC, GraphQL etc.</p><p><strong>HTTP Request Headers </strong>contain text information stores in key-value pairs. These headers communicate core information such as browser the client is using, data that is being requested</p><pre><strong>:authority:</strong> <a href="http://www.google.com/">www.google.com</a><br><strong>:method:</strong> GET<br><strong>:path:</strong> /complete/search?q=hello%20world<br><strong>:scheme:</strong> https<br><strong>accept:</strong> */*<br><strong>accept-encoding:</strong> gzip, deflate, br<br><strong>accept-language:</strong> en-GB,en-US;q=0.9,en;q=0.8<br><strong>user-agent: </strong>Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36</pre><p>A typical <strong>HTTP response</strong> contains —</p><ol><li>an HTTP status code</li><li>HTTP response headers</li><li>HTTP body (optional)</li></ol><p>HTTP Status code are 3-digit codes most often used to indicate whether an HTTP request has been successful —</p><ol><li>1xx — Informational</li><li>2xx — Success</li><li>3xx — Redirection</li><li>4xx — Client Error</li><li>5xx — Server Error</li></ol><p>The “xx” refers to different numbers between 00 and 99.</p><p>Example <strong>HTTP Response Header </strong>—</p><pre><strong>cache-control: </strong>private, max-age=0<br><strong>content-encoding: </strong>br<br><strong>content-type: </strong>text/html; charset=UTF-8<br><strong>date: </strong>Sat, 26 Jun 2021 19:02:03 GMT<br><strong>status: </strong>200<br><strong>strict-transport-security: </strong>max-age=31536000</pre><h4>Representational State Transfer</h4><p>REST is all about resources. A resource is an entity that can be identified, named or addressed. REST APIs expose data as resources and use standard HTTP methods to represent CRUD transactions against those resources.</p><p>REST APIs general rules —</p><ol><li>Resources are part of URLs — /users</li><li>For each resource, 2 URLs are generally implemented — one for the collection like /users, and one for specific element like /users/U123</li><li>Nouns are used instead of verbs for resources — Not getUserInfo/U123 but /users/U123</li><li>HTTP methods like GET, POST, PUT, DELETE inform the server about the action to be performed. Different HTTP methods invoked on the same URL provide different functionality</li><li>REST APIs might return JSON or XML responses</li></ol><p>Example:</p><pre>GET /zipcode/456010<br>HOST weatherapp.com<br>Authorization: Bearer w4j6hyb78onjurt4</pre><pre>-----------------------------------------</pre><pre>POST /zipcode/456010<br>HOST weatherapp.com<br>Content-Type: application/x-www-form-urlencoded<br>Authorization: Bearer w4j6hyb78onjurt4</pre><pre>temperature=27C&amp;isRainy=true</pre><p>REST APIs might sometimes need to represent non-CRUD operations —</p><p><strong>1.</strong> Render an action as part of a field of a resource</p><pre>PATCH /repos/pmasne/Hacks<br>HOST api.github.com<br>Content-Tyep: application/json<br>Authorization: token OAUTH-TOKEN</pre><pre>{<br>    &quot;archived&quot;: true<br>}</pre><p><strong>2.</strong> Treat an action like a subresource. Github uses below pattern for locking and unlocking an issue</p><pre>PUT /repos/:owner/:repo/issues/:number/lock</pre><p><strong>3. </strong>Some operations like Search are difficult to fit in the REST paradigm. A typical practice is to use the action verb</p><pre>GET /search/code?q=:query:</pre><h4>Remote Procedural Call</h4><p>Where REST is about resources, RPC is about actions. Clients typically pass the method name and arguments to the server and receive back JSON or XML.</p><p>RPC style works great for APIs that expose a variety of actions that might have more nuances and complications than can be encapsulated with CRUD operations on resources. Slack’s conversations API allows several actions, like archive, join, kick, rename etc. Not all these actions would fit into REST pattern nicely.</p><p>Example:</p><pre>POST /api/conversations.archive<br>HOST slack.com<br>Content-Type: application/x-www-form-urlencoded<br>Authorization: Bearer ds234hjb45jb4353j45l</pre><pre>channel=C01234</pre><h4>GraphQL</h4><p>GraphQL is a query language for APIs that was developed internally by Facebook and then released publicly. It allows clients to define the structure of the data required and the server returns exactly that structure.</p><pre>GraphQL query - <br>{<br>    user(login: &quot;pmasne&quot;) {<br>        id<br>        name<br>        company<br>        createdAt<br>    }<br>}</pre><pre>GraphQL query response - <br>{<br>    &quot;data&quot;: {<br>        &quot;user&quot;: {<br>            &quot;id&quot;: &quot;pmasne&quot;,<br>            &quot;name&quot;: &quot;Priyanka Masne&quot;,<br>            &quot;company&quot;: &quot;Facebook&quot;,<br>            &quot;createdAt&quot;: &quot;2021-08-01T21:00:06Z&quot;<br>        }<br>    }<br>}</pre><p>Unlike REST and RPC APIs, GraphQL APIs need only a single URL endpoint. Similarly, we don’t need different HTTP verbs to describe the operation. Instead, we can indicate in the JSON body whether we are performing a query or mutation.</p><p><strong>Advantages (GraphQL vs REST/RPC) —</strong></p><ol><li>Saves multiple round trips<br>GraphQL enables clients to nest queries and fetch data across resources in a single request. Without GraphQL, this might require multiple HTTP calls to server. This means GraphQL can be quick, even on slow network connections.</li><li>Avoids versioning<br>You can add new fields and types to a graphQL API without affecting existing queries. Similarly deprecating existing fields is easier.</li><li>Smaller payload size<br>REST and RPC often end up responding with data that clients might not ever use. With GraphQL, because clients can exactly specify what they need, the payload sizes can be smaller.</li><li>Introspection<br>Although, REST APIs can be explored on solutions like Swagger or Postman, graphQL is natively discoverable. It comes with GraphiQL, an in-browser IDE.</li></ol><p><strong>Disadvantage — </strong>GraphQL adds complexity for the API provider. The server needs to do additional processing to parse complex queries and verify parameters. Depending on the complexity of the incoming requests, the performance and impact to infrastructure can be highly variable.</p><h3>Event-Driven APIs</h3><p>Sometimes the applications need to push the data to clients to keep it up-to-date as the polling can at a high frequency would lead to a huge waste of resources.</p><p>Three poplar paradigms to share data in real time — WebHooks, WebSockets and HTTP Streaming.</p><h4>WebHooks</h4><p>WebHook is just a URL hat accepts an HTTP POST (or GET, PUT, DELETE). An API provider implementing WebHook will simply POST a message to a configured URL when something happens.</p><p>From an app developer’s POV, it’s typically easy to implement WebHooks because it simply required creating a new HTTP endpoint to receive events.</p><p><strong>Complexities —</strong></p><ol><li>Failures and Retries<br>To ensure WebHooks are delivered successfully, it’s important to build retry mechanisms on error.</li><li>Security<br>Although there are standard ways of making REST APIs secure, security for WebHooks is still evolving.</li><li>Firewalls<br>Applications running behind firewalls can access APIs over HTTP but they cannot receive inbound traffic. For such applications, utilising WebHooks is often not possible.</li><li>Noise<br>Typically, each WebHook call represents one single event. When there are thousands of events happening, WebHook can be noisy since events can be sent in bulk.</li></ol><h4>WebSockets</h4><p>WebSocket is a protocol used to establish a two-way communication channel over a single TCP connection. It doesn’t use HTTP. It is supported by major browsers and often used by real-time applications.</p><p><strong>Advantages —</strong></p><ol><li>WebSockets are designed to work over port 80 or 443, enabling them to work well with firewalls that might block other ports.</li><li>WebSockets are great for fast, live streaming data and long-lied connections.</li></ol><p><strong>Disadvantages —</strong></p><ol><li>Clients need to reinitiate connection in case the connection is broken. In low network bandwidth regions, this can be spotty.</li><li>Developer needs to ensure scalability. If the app is installed on 1M devices, the developer would be responsible for maintaining 1M connections between backend servers and the app’s server.</li></ol><h4>HTTP Streaming</h4><p>With HTTP request-response APIs, clients send an HTTP request and the server returns an HTTP response of a finite length. Now it’s possible to make the length of this response indefinite. With HTTP streaming, the server can continue to push new data in a single long-lived connection opened by a client.</p><p>To transmit data over a persistent connection from server to client, there are 2 options —</p><ol><li>server can set Transfer-Encoding header to chunked. This indicates to clients that data will be arriving in chunks of newline-delimited strings.</li><li>Data can be streamed via server-sent events (SSE). This is great for clients consuming these events in a browser because they can use the standardized EventSource API.</li></ol><p><strong>Disadvantages —</strong></p><ol><li>Bi-directional communication is difficult.</li><li>Clients and proxies have buffer limits. They might not start rendering data to the application until a threshold is met.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f300d01ee811" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encoding and Evolution]]></title>
            <link>https://masne.medium.com/encoding-and-evolution-3a8496ec5ade?source=rss-60e3040958d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a8496ec5ade</guid>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[deserialize]]></category>
            <category><![CDATA[decode]]></category>
            <category><![CDATA[encode]]></category>
            <category><![CDATA[serialize]]></category>
            <dc:creator><![CDATA[Priyanka Masne]]></dc:creator>
            <pubDate>Sat, 26 Jun 2021 12:41:55 GMT</pubDate>
            <atom:updated>2021-06-26T12:41:55.444Z</atom:updated>
            <content:encoded><![CDATA[<p>0c|4d617274696e|f214 -&gt; Help me decode!!</p><p>Programs work with data in 2 different representations —</p><ol><li>In memory, data is kept in objects, structs, list, arrays, hash tables, trees etc. These data structures are optimised for efficient access and manipulation by the CPU (typically using pointers)</li><li>When we want to write data to a file or send it over the network, we have to encode it as some kind of self-contained sequence of bytes (eg. — JSON document). Since a pointer wouldn’t make sense to any other process, this sequence-of-bytes representation looks quite different from the data structures that are normally used in memory</li></ol><p>Thus, we need some kind of translation between the two representations. The translation from in-memory to a byte sequence is called <strong>encoding or serialization</strong>, and the reverse is called <strong>decoding or deserialization</strong>.</p><p>In most cases, a change in application’s features also requires a change to data it stores.</p><p>Relational databases generally assume all the data conforms to one schema and changing the schema is a tedious process. Schema-on-read databases don’t enforce a schema, so the database can contain a mixture of older and newer data formats.</p><p>With data format changes, a corresponding change to the application code needs to happen (application code starts to read and write that new field).</p><ol><li>With server-side applications, we may want to perform a rolling upgrade — deploying the new version to a few nodes at a time, checking whether the new version is running smoothly and gradually working our way through all the nodes.</li><li>With client-side applications, we’re at the mercy of the user who may or may not install the update for some time.</li></ol><p>This means that old and new version of the code, and old and new data formats may potentially all coexist in the system at the same time. So the system needs to maintain compatibility in both directions —</p><ol><li>Backward compatibility — Newer code can read data that was written by older code</li><li>Forward compatibility — Older code can read the data that was written by newer code</li></ol><p><strong>Language-specific encoding. </strong>Many programming languages come with a built-in support for encoding in-memory objects into byte sequences. For eg — Java has java.io.Serializable, Ruby has Marshal, Python has pickle.</p><p>These encoding libraries are very convenient because they allow in-memory objects to be saved and restored with minimal additional code. However, such encoding is often tied to a particular programming language and reading the data in another language is very difficult. If we store or transmit data in such an encoding, we are committing ourself to our current programming language for potentially a very long time and precluding integrating your systems with those of other organisations which may use a different languages.</p><p>Therefore, it’s generally a bad idea to use language’s built-in encoding for anything other than very transient purposes.</p><p>Standardised encodings like JSON and XML can be written and read by many programming languages. These are also human readable. Drawback is that both JSON and XML encodings use a lot of space compared to binary formats.</p><p>This drawback of JSON and XML has led to the development of profusion of binary encodings for JSON (MessagePack, BSON, BJSON, BISON) and for XML (WBXML, Fast Infoset) but these encoding do not provide significant size reduction.</p><p>There are other encoding libraries like Apache Thrift (originally developed at Facebook), Protocol Buffers (developed at Google) and Avro which are open source and have support for a fairly wide range of programming languages.</p><p>There are many ways data can flow from one process to another. These processes need to be compatible i.e. data encoded by one process should be decode-able by the other process which uses the same data.</p><p><strong>Dataflow through databases</strong></p><p>Consider that you add a field to a record schema, and the newer code writes a value for that new field to the database. Subsequently, an older version of the code (which doesn’t know the field yet) reads the record, updates it and writes it back. If you decode a database value into model objects in the application and later re-encode those model objects, the unknown field might be lost in that translation process.</p><p>So, we need to process data cautiously!</p><p><strong>Dataflow through services</strong></p><p>In case of APIs, client encodes a request, the server decodes the request and encodes a response, and the client finally decodes the response.</p><p>RESTful APIs most commonly use JSON for responses, and a JSON or URI-encoded/form-encoded request parameters for requests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a8496ec5ade" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stock Market — Avoid Loss and Earn Consistently]]></title>
            <link>https://masne.medium.com/stock-market-avoid-loss-and-earn-consistently-a553e7aa9580?source=rss-60e3040958d7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a553e7aa9580</guid>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[equity-trading-tips]]></category>
            <category><![CDATA[investment]]></category>
            <category><![CDATA[equity]]></category>
            <dc:creator><![CDATA[Priyanka Masne]]></dc:creator>
            <pubDate>Mon, 21 Jun 2021 17:53:15 GMT</pubDate>
            <atom:updated>2021-06-21T17:53:15.184Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stock Market — Avoid Loss and Earn Consistently</h3><p>An attempt to save hard-earned money in equity investing</p><p>Investing in high-quality businesses (stock) at the right price and holding them for a reasonable period is the key to create wealth. Stock picking is considered one of the most complex subjects in the world.</p><p>Almost all billionaires in the world have created their fortune through the stock market, either directly or indirectly. “Directly” refers to direct stock investing and “Indirectly” refers to listing their companies on the stock market. Some of the world’s billionaires such as Warren Buffet, Rakesh Jhunjhunwala, Vijay Kedia have earned their entire wealth from direct stock investing.</p><p><strong>Tip#1: </strong>Do not trust your broker blindly. Brokers earn money for every transaction you make, hence they encourage you to do frequent trading.</p><p><strong>Tip#2: </strong>Intraday trading is almost guaranteed way to accumulate losses. You can make money once, twice or thrice but you’re bound to lose after that.</p><p><strong>Tip#3: </strong>It is best to stay away from “loan against share” schemes. This loan can help increase gains during bullish markets but during bearish market, investors have to sell off their shares at loss to maintain the collateral against loan.</p><p><strong>Tip#4: </strong>Trading in “Futures and Options” is the worst decision any retail investor can make. You can lose your entire life’s savings in F&amp;O. F&amp;O is meant for hedging and not full fledged trading.</p><p>Bank deposits do not offer a positive return. It is because of inflation and taxes. Inflation is the increase in price you pay for the same amount of good. If 2kg of rice costs Rs.100 today, then after one year you won’t be able to purchase the same quantity at Rs.100.</p><p>Rs.100 in bank will give turn to about Rs.107–108 in a year, but it will also cost 107–108 for the same daily expenses. The situation worsens if you consider the taxes. the interest of Rs.7–8 is fully taxable.</p><p>Any investment that doesn’t give you a min of 12% return is actually depreciating your money. Bank deposits offer a negative return considering inflation and tax. Equity investment is required to beat inflation+taxes.</p><p>Never judge a stock by profit and sales growth numbers. A company may report millions of profit with negative cash flow in the books. Profitable growth might be fuelled by external debt.</p><p>Sales growth doesn’t ensure shareholders’ profit. You can’t be sure how much sales is translating into cash and how much margin is added. At the end of the day, how much cash you retain matters the most.</p><p>We should first look at <strong>Return on Equity (ROE)</strong>.</p><p>ROE tells how much profit a company generates from their shareholders’ money. <strong>ROE = Net Income/Shareholders’ Equity</strong>. Always prefer stocks with improving ROE or companies having an ROE of more than 20%.</p><p>Analyse debt position of a company. Debt is essential for a business to expand. But sometimes debt becomes disastrous. Consider a situation where you’re earning 10% profit margin but paying back 12% interest on the borrowed money. In such a case, higher sales will widen the loss because you are losing 2% on every sale.</p><p><strong>Debt to Equity = Total Liabilities/Equity</strong></p><p>DTE ratio tells how much of shareholders’ equity is used in debt.</p><p>Always check DTE ratio of previous 3 years. Stay away from companies that have 1+ (&amp; increasing) DTE ratio.</p><p>In summary, if you find that the stock has ROE of less than 12% &amp; DTE ratio or more than 1 (&amp; increasing), then discard it.</p><p>Before investing in a stock, always check management’s credibility by looking at —</p><ol><li>Shareholding Pattern</li><li>Dividend history &amp; Tax Rate</li><li>ROE</li></ol><p>Shareholding pattern of any listed company can be found on BSE website (www.bseindia.com).</p><p>ROE and tax rate are readily available on company’s financial statements and on many other financial websites.</p><p>Dividend history is readily available on BSE or NSE website.</p><p><strong>Shareholding pattern</strong> is divided into 2 groups —</p><ol><li>Promoters and promoter group, are the basic owners of the company</li><li>Public group, are shareholders other than promoters. FII, DII, banks, money managers, mutual funds, individuals all come under this group</li></ol><p>Nobody knows a company better than it’s owners. Without high conviction, an owner would not purchase the shares of his own company from open market. So, promoters increasing stake via open market purchase is a positive signal.</p><p>Lower stake of promoters means low confidence in the company i.e. promoters are not optimistic about the prospects. So, try to avoid companies where promoters have small shareholdings or where they are consistently reducing their stake by a huge percentage.</p><p>However, sometimes promoters reducing their stake can give positive outcomes. For example, a promoter can sell some of his holdings to a big institutional investor which is the first sign of good times.</p><p>Promoters of banking and finance companies often dilute their stake for fundraising which is a positive sign in the banking business. The more money banks can have, the more they can lend and thus more profit, even though in such cases promoters holdings are reduced.</p><p>Institutional Investors buy large quantities of shares leaving a high impact on the stock movements. They are usually knowledgeable and experienced, so their footprints are followed by many retail investors.</p><p>There are 2 types of institutional investors: Foreign Institutional Investors (FII) &amp; Domestic Institutional Investors (DII).</p><p>Higher FII stakes are considered positive. If FIIs offload massive quantities, then huge fall in stock price is witnessed.</p><p>You can create wonder if you can invest in a stock before it attracts investment from FIIs.</p><p>Pledging of shares is a process when the promoters keep the shares of the company that they own as collateral for the debt. Pledging of shares is done with banks or non-banking finance institutions.</p><p>Pledging is usually the last option for promoters to raise funds. It means that no one else is ready to provide a loan because wither the company’s future prospect is not bright.</p><p>Drop in share price leads to a decrease in collateral value. It means that the shares that were initially 100cr are now worth only 50cr. To protect the loan amount and limit the risk, the lender asks for more collateral, to which promoters are forced to pledge more shares. So, pledging can lead to promoters losing their stake in the company.</p><p>As an investor, always avoid companies where promoters pledge more than 30% of their holdings and are increasing their pledged shares.</p><p>Companies can either re-invest the entire profit into the business or it can distribute a portion of the profit to shareholders as dividend. If the dividend figure is increasing every year over the previous 5 years, then we can assume that the company is in “real” growth track.</p><p>If you purchase a quality product at an excessively high rate, do you find another buyer to take it at a even higher rate? Obviously, no! To become a successful investor, you have to buy a great company at an attractive price.</p><p>PE ratio = Current market price / Earnings per share (EPS)</p><p><strong>PE ratio</strong> compares the current market price of the stock with its earnings per share. PE ratio in isolation has no significance. Compare a stock’s PE with its last 3 years or 5 years historical PE. If you find a fundamentally strong stock trading much below its historical average, then it might be a worthy investment.</p><p>When buying a stock, make sure PE ratio is not more than 2 times the average of last 3 years EPS. PE ratio ≤ 2 * avg(3 years EPS)</p><p>In short,</p><ol><li>If current PE ratio is ≤ 3-5 years average and the current PE ratio is less than 2 times the last 3 years average EPS, then buying opportunity can be explored</li><li>If current PE ratio is in the highest band of previous 3–5 years average and PE ratio &gt; 2 times last 3 years avg EPS, then explore selling options.</li></ol><p>The above PE related valuation method only work when there is no change in the business prospects. If the prospects change drastically (like change of CEO), then past data hold no value anymore.</p><p>The valuation also doesn’t work for loss making companies, which should anyway be avoided by retail investors.</p><p>If you find a stock is trading at a much higher PE compared to its historical PE range with no drastic improvements in future prospects, then you can consider it as overvalued.</p><p>Immediately exit from a stock if your original purchase reason is no more valid. For eg., Deccan Chronicle Holdings was the owner of few popular newspapers and magazines. They were market leaders in their own niche. Later they spent 60cr to buy Odyssey, a retail bookstore. They also purchased the IPL team for $107m. At this juncture, anyone holding the stock just because of its market leadership in newspapers, should have immediately exited because the fundamentals changed and were no more intact.</p><p>Before investing, develop an exit strategy and strictly follow the same. Don’t put a second thought.</p><p>Suppose you bought a stock because of its 30% growth rate, you should sell it whenever the growth slows down.</p><p>In short, be clear about the purchase reason and write it down. Keep monitoring those purchase reasons and sell when the purchase reason alters.</p><p>Always diversify your portfolio across multiple sectors —</p><ol><li>Banking (Private)</li><li>Banking (Public)</li><li>Pharma</li><li>IT</li><li>Automobiles</li><li>FMCG</li><li>Telephone</li><li>Oil and Gas</li><li>Infrastructure</li><li>Cements</li></ol><p>Having stocks from different sectors ensure that your portfolio can affect less even in a downturn. It is unlikely that all ten sectors underperform at a single time.</p><p>Quality small cap and mid caps can offer more safety, better dividend yield and a better return than large caps.</p><p>Dangerous misconception — “Stocks that fall sharply must move sharply”. Avoid investing in stocks that suffered 60%+ correction from the recent peak.</p><p>In a minor stock market crash (when index falls 5%-30%) —</p><ol><li>Don’t sell off your entire holdings to re-enter at a lower level. None can predict short-term market movement correctly. So, it may happen that after you sell off, the market takes a U-turn and you’re not able to invest at a lower level ever again</li><li>Accumulate high-quality stocks during such a correction</li><li>During a market crash, you may not have enough cash to re-invest in quality stocks. In such a situation, the best solution is to HOLD your current position. Don’t try to predict the bottom for investment. You can’t buy at the bottom and sell at the top every time</li></ol><p>In a major market crash (index collapsing by 50% or more), it is impossible to earn a return as high as 20%–30%. The best swimmer in the world can’t survive during a Tsunami. The target in such times should be to generate at least a positive annualised return.</p><p>Last 30 year’s price trend suggests that gold and equity mostly move in the opposite direction. So, during a major market crash, shifting a portion of portfolio into Gold can be a prudent move.</p><p>Quick Formula First step —</p><ol><li>Last 3 years average Return on Equity (ROE) and Return on Capital Employed (ROCE) are both greater than 20% and not on a continuous decline</li><li>Debt to Equity ratio is less than 1 (or heavily reducing for the last few years)</li><li>Promoters pledge less than 10% of their total shareholdings, or there is a clear sign that it will fall below 10% soon</li></ol><p>Second step —</p><ol><li>Valuation — Explore buying opportunity while PE ratio remains lower than the historical average or hover around that range, provided there are no changes in the business prospects</li><li>Stock Price movement — As a final step, conduct a price movement test. If you find that the stock has generated a negative return over the last 3 years, then avoid it.</li></ol><h3>Post Script</h3><p>This book has been authored by Prasenjit Paul, a SEBI registered Research Analyst known for having a history of identifying several multi-bagger stocks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a553e7aa9580" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>