Blog

iOS – Is SOLID Valuable Design Principles Applicable For Swift ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, We will learn about most popular design principles SOLID in Swift. We will see that how SOLID is applicable for Swift. Now a days , a Maintainable and Reusable component is just a dream. Maybe not. SOLID principles, may be the way.

A famous quote about learning is :

Change is the end result of all true learning.

So Let’s begin.

Origin of the acronym SOLID

SOLID is an acronym named by Robert C. Martin (Uncle Bob). It represents 5 principles of object-oriented programming :

  • Single responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle

If we apply these five principles:

  • We will have flexible code, which we can easily change and that will be both reusable and maintainable.
  • The software developed will be robust, stable and scalable (we can easily add new features).
  • Together with the use of the Design Patterns, it will allow us to create software that is highly cohesive (that is, the elements of the system are closely related) and loosely coupled (the degree of dependence between elements is low).

So, SOLID can solve the main problems of a bad architecture:

  • Fragility: A change may break unexpected parts—it is very difficult to detect if you don’t have a good test coverage.
  • Immobility: A component is difficult to reuse in another project—or in multiple places of the same project—because it has too many coupled dependencies.
  • Rigidity: A change requires a lot of efforts because affects several parts of the project.

Of course, as Uncle Bob pointed out in a his article, these are not strict rules, but just guidelines to improve the quality of your architecture.

Principles will not turn a bad programmer into a good programmer. Principles have to be applied with judgement. If they are applied by rote it is just as bad as if they are not applied at all.

Principles

The Single Responsibility Principle (SRP)

According to this principle, a class should have a reason, and only one, to change. That is, a class should only have one responsibility.

Now let’s describe Single Responsibility Principle says :

THERE SHOULD NEVER BE MORE THAN ONE REASON FOR A CLASS TO CHANGE.

Every time you create/change a class, you should ask yourself: How many responsibilities does this class have?

Let’s take a look into Swifty communication program.

import Foundation

class InterPlanetMessageReceiver {

    func receiveMessage() {
        print("Received the Message!")
    }

    func displayMessageOnGUI() {
      print("Displaying Message on Screen!")
    }
}

Now let’s understand what is Single Responsibility Principle (SRP) and how the above program doesn’t obey it.

SRP says, “Just because you can implement all the features in a single device, you shouldn’t”.

In Object Oriented terms it means: There should never be more than one reason for a class to change. It doesn’t mean you can’t have multiple methods but the only condition is that they should have one single purpose.

Why? Because it adds a lot of manageability problems for you in the long run.

Here, the InterPlanetMessageReceiver class does the following:

  • It receives the message.
  • It renders it on UI.

And, two applications are using this InterPlanetMessageReceiver class:

  • A messaging application uses this class to receive the message
  • A graphical application uses this class to draw the message on the UI

Do you think it is violating the SRP?

YES, The InterPlanetMessageReceiver class is actually performing two different things. First, it handles the messaging, and second, displaying the message on GUI. This causes some interesting problems:

  • Swifty must include the GUI into the messaging application and also while deploying the messaging application, we must include the GUI library.
  • A change to the InterPlanetMessageReceiver class for the graphical application may lead to a change, build, and test for the messaging application, and vice-versa.

Swifty got frustrated with the amount of changes it required. He thought it would be a minute job but now he has already spent hours on it. So he decided do make a change into his program and fix this dependency.

This is what Swifty came up with

import Foundation

// Handles received message
class InterPlanetMessageReceiver {

    func receive() {
        print("Received the Message!")
    }
}

// Handles the display part
class InterPlanetMessageDisplay {

    func displayMessageOnGUI() {
      print("Displaying Message on Screen!")
    }
}

Here’s how Swifty explained this:

InterPlanetMessageReceiver class will be used by the messaging application, and the InterPlanetMessageDisplay class will be used by the graphical application. We could even separate the classes into two separate files, and that will allow us not to touch the other in case a change is needed to be implemented in one.

Finally, Swifty noted down :Why we need SRP?

  • Each responsibility is an agent of change.
  • Code becomes coupled if classes have more than one responsibility.

Open/Closed Principle

According to this principle, we must be able to extend the a class without changing its behaviour. This is achieved by abstraction.

Now let’s describe Open/Closed Principle says :

SOFTWARE ENTITIES (CLASSES, MODULES, FUNCTIONS, ETC.) SHOULD BE OPEN FOR EXTENSION, BUT CLOSED FOR MODIFICATION.

If you want to create a class easy to maintain, it must have two important characteristics:

  • Open for extension: You should be able to extend or change the behaviours of a class without efforts.
  • Closed for modification: You must extend a class without changing the implementation.

Let’s see our swifty example. Swifty was quite happy with these change and later he celebrated it with a drink in Swiftzen’s best pub and there his eyes fell upon an artifact hanging on the front wall and he found all the symbols he received in the message. Quickly, he opened his diary and completed deciphering all those shapes.

Next day when he returned back, he thought why not fix the DrawGraphic class which draws only circle shape, to include the rest of the shapes and display the message correctly.

// This is the DrawGraphic
class DrawGraphic {

  func drawShape() {
     print("Circle is drawn!")
  }
}

// Updated Class code

enum Shape {
  case circle
  case rectangle
  case square
  case triangle
  case pentagon
  case semicircle
}
class circle {

}

// This is the DrawGraphic
class DrawGraphic {

  func drawShape(shape: Shape) {
     switch shape {
        case .circle:
          print("Circle is drawn")
        case .rectangle:
          print("Rectangle is drawn")
        case square:
          print("Square is drawn")
        case triangle:
          print("Triangle is drawn")
        case pentagon:
          print("Pentagon is drawn")
        case semicircle:
          print("Semicircle is drawn")
        default:
          print("Shape not provided")
     }
  }
}

Swifty was not happy with these changes, what if in future a new shape shows up, after all he saw in the artifacts that there were around 123 shapes. This class will become one fat class. Also, DrawGraphics class is used by other applications and so they also have to adapt to this change. it was nightmare for Swifty.

Open Closed Principle solves nightmare for Swifty. At the most basic level, this means, you should be able to extend a class behavior without modifying it. It’s just like I should be able to put on a dress without doing any change to my body. Imagine what would happen if for every dress I have to change my body.

After hours of thinking, Swifty came up with below implementation of DrawGraphic class.

protocol Draw {
    func draw()
}

class Circle: Draw {
    func draw() {
        print("Circle is drawn!")
    }
}

class Rectangle: Draw {
    func draw() {
        print("Rectangle is drawn!")
    }
}

class DrawGraphic {
    func drawShape(shape: Draw) {
        shape.draw()
    }
}

let circle = Circle()
let rectangle = Rectangle()
let drawGraphic = DrawGraphic()

drawGraphic.drawShape(shape: circle)  // Circle is drawn!
drawGraphic.drawShape(shape: rectangle) // Rectangle is drawn!

Since the DrawGraphic is responsible for drawing all the shapes, and because the shape design is unique to each individual shape, it seems only logical to move the drawing for each shape into its respective class.

That means the DrawGraphic still have to know about all the shapes, right? Because how does it know that the object it’s iterating over has a draw method? Sure, this could be solved with having each of the shape classes inherit from a protocol: the Draw protocol (this can be an abstract class too).

Circle and Rectangle classes holds a reference to the protocol, and the concrete DrawGraphic class implements the protocol Draw class. So, if for any reason the DrawGraphic implementation is changed, the Circle and Rectangle classes are not likely to require any change or vice-versa.

Liskov Subsitution Principle

This principle, introduced by Barbara Liskov in 1987, states that in a program any class should be able to be replaced by one of its subclasses without affecting its functioning.

Now let’s describe Liskov Substitution Principle says :

FUNCTIONS THAT USE POINTERS OR REFERENCES TO BASE CLASSES MUST BE ABLE TO USE OBJECTS OF DERIVED CLASSES WITHOUT KNOWING IT.

Inheritance may be dangerous and you should use composition over inheritance to avoid a messy codebase. Even more if you use inheritance in an improper way.

This principle can help you to use inheritance without messing it up.

Let’s see our swifty example. Swifty was implementing the SenderOrigin class to know whether the sender is from a Planet or not.

The Sender class looked something like this

Class Planet {
  func orbitAroundSun() {
  }
}

class Earth: Planet {
  func description() {
    print("It is Earth!")
  }
}

class Pluto: Planet {
  func description() {
    print("It is Pluto!")
  }
}

class Sender {
  func senderOrigin(planet: Planet) {
    planet.description()
  }
}

In the class design, Pluto should not inherit the Planet class because it is a dwarf planet, and there should be a separate class for Planet that has not cleared the neighborhood around its orbit and Pluto should inherit that.

So the principle says that Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

Swifty whispered it is the polymorphism. Yes it is. “Inheritance” is usually described as an “is a” relationship. If a “Planet” is a “Dwarf”, then the “Planet” class should inherit the “Dwarf” class. Such “Is a” relationships are very important in class designs, but it’s easy to get carried away and end up with a wrong design and a bad inheritance.

The “Liskov’s Substitution Principle” is just a way of ensuring that inheritance is used correctly.

In the above case, both Earth and Pluto can orbit around the Sun but Pluto is not a planet. It has not cleared the neighborhood around its orbit. Swifty understood this and changed the program.

class Planet {
    func oribitAroundSun() {
        print("This planet Orbit around Sun!")
    }
}

class Earth: Planet {
    func description() {
        print("Earth")
    }
}

class DwarfPlanet: Planet {
    func notClearedNeighbourhoodOrbit() {

    }
}

class Pluto: DwarfPlanet {
  func description() {
        print("Pluto")
    }
}

class Sender {
    func senderOrigin(from: Planet) {
        from.description()
    }
}

let pluto = Pluto()
let earth = Earth()

let sender = Sender()
sender.senderOrigin(from: pluto) // Pluto
sender.senderOrigin(from: earth) // Earth

Here, Pluto inherited the planet but added the notClearedNeigbourhood method which distinguishes a dwarf and regular planet.

  • If LSP is not maintained, class hierarchies would be a mess, and if a subclass instance was passed as parameter to methods, strange behavior might occur.
  • If LSP is not maintained, unit tests for the base classes would never succeed for the subclass.

Swifty can design objects and apply LSP as a verification tool to test the hierarchy whether inheritance is properly done.

Interface Segregation Principle

The Principle of segregation of the interface indicates that it is better to have different interfaces (protocols) that are specific to each client, than to have a general interface. In addition, it indicates that a client would not have to implement methods that he does not use.

Now let’s describe Interface Segragation Principle says :

CLIENTS SHOULD NOT BE FORCED TO DEPEND UPON INTERFACES THAT THEY DO NOT USE.

This principle introduces one of the problems of object-oriented programming: the fat interface.

An interface is called “fat” when has too many members/methods, which are not cohesive and contains more information than we really want. This problem can affect both classes and protocols.

Let’s continue our swifty example. Swifty was quite astonished with the improvement in his program. All the changes were making more sense. Now, it was time to share this code with different planet. Swiftzen 50% GDP was dependent on selling softwares and many planet has requested and signed MOU for the Inter Planet communication system.

Swifty was ready to sell the program and but he was not satisfied with current client interface. Let’s us look into it.

protocol interPlanetCommunication {
  func switchOnAntenna()
  func setAntennaAngle()
  func transmitMessage()
  func receivedMessage()
  func displayMessageOnGUI()
}

Now for anyone who want to use interPlanetCommunication, he has to implement all the five methods even-though they might not required.

So the principle says that Many client-specific interfaces are better than one general purpose interface. The principle ensures that Interfaces are developed so that each of them have their own responsibility and thus they are specific, easily understandable, and re-usable.

Swifty quickly made changes to his program interface:

protocol antenna {
  func switchOnAntenna()
  func setAntennaAngle()
}

protocol message {
  func transmitMessage()
  func receivedMessage()
}

protocol dispaly {
  func displayMessageOnGUI()
}

Dependency Inversion Principle

According to the Dependency inversion principle:

“HIGH LEVEL MODULES SHOULD NOT DEPEND UPON LOW LEVEL MODULES. BOTH SHOULD DEPEND UPON ABSTRACTIONS.”

“ABSTRACTIONS SHOULD NOT DEPEND UPON DETAILS. DETAILS SHOULD DEPEND UPON ABSTRACTIONS.”

This principle tries to reduce the dependencies between modules, and thus achieve a lower coupling between classes.

This principle is the right one to follow if you believe in reusable components.

DIP is very similar to Open-Closed Principle: the approach to use, to have a clean architecture, is decoupling the dependencies. You can achieve it thanks to abstract layers.

Let’s continue our swifty example. Before finally shipping the program to all the clients, Swifty was trying to fix the password reminder class which looks like this.

class PasswordReminder {
  func connectToDatabase(db: SwiftZenDB) {
    print("Database Connected to SwiftzenDB")
  }

  func sendReminder() {
    print("Send Reminder")
  }
}

PasswordReminder class is dependent on a lower level module i.e. database connection. Now, let suppose that you want to change the database connection from Swiftzen to Objective-Czen, you will have to edit the PasswordReminder class.

Finally the last principle states that Entities must depend on abstractions not on concretions.

To fix above program Swifty made these changes:

protocol DBConnection {
  func connection()
}

class SwiftzenDB: DBConnection {
  func connection() {
    print("Connected to SwiftzenDB")
  }
}

class PasswordReminder {
  func connectToDatabase(db: DBConnection) {
    db.connection()
  }

  func sendReminder() {
    print("Send Reminder")
  }
}

The DBConnection protocol has a connection method and the SwiftzenDB class implements this protocol, also instead of directly type-hinting SwiftzenDB class in PasswordReminder, Swifty instead type-hint the protocol and no matter the type of database your application uses, the PasswordReminder class can easily connect to the database without any problems and OCP is not violated.

The point is rather than directly depending on the SwiftzenDB, the passwordReminder depends on the abstraction of some specification of Database so that if any the Database conforms to the abstraction, it can be connection with the PasswordReminder and it will work.

That’s all about in this article.

Conclusion

In this article, We understood about SOLID principles in Swift. We learnt that how SOLID is application for Swift. If we follow SOLID principles judiciously, we can increase the quality of our code. Moreover, our components can become more maintainable and reusable.

The mastering of these principles is not the last step to become a perfect developer, actually, it’s just the beginning. We will have to deal with different problems in our projects, understand the best approach and, finally, check if we are breaking some principles.

We have 3 enemies to defeat: Fragility, Immobility and Rigidity. SOLID principles are our weapons. We tried to explain the SOLID concepts in Swift easy way with examples.

Thanks for reading ! I hope you enjoyed and learned about SOLID Principles in Swift. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

ReactJS – Jest Framework – The Most Valuable Concepts Improve Code Quality

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will talk about the ins and outs of Jest to help you get started with testing. we will learn more about the vocabulary associated with Jest testing, like mocks and spies. Also, we’ll cover some of the basics of Jest testing, like using describe blocks and the keywords it and expect. Finally, we’ll take a look at snapshot testing and why it’s particularly useful for front-end testing.

A famous quote about learning is :

The more I live, the more I learn. The more I learn, the more I realizes, the less I know.


So Let’s start.


What Is Jest?

Jest was created by Facebook specifically for testing React applications. It’s one of the most popular ways of testing React components. Since its introduction, the tool has gained a lot of popularity. This popularity has led to the use of Jest for testing both JavaScript front-end and back-end applications. Many large companies—including Twitter, Instagram, Pinterest, and Airbnb—use Jest for React testing.

Jest itself is actually not a library but a framework. There’s even a CLI tool that you can use from the command line. To give an example, the CLI tool allows you to run only specific tests that match a pattern. Besides that, it hosts much more functionality, which you can find in the CLI documentation.

Jest offers a test runner, assertion library, CLI tool, and great support for different mocking techniques. All of this makes it a framework and not just a library.


Jest Characteristics

From the JestJS.io website, we can find four main characteristics of Jest:

  • Zero config: “Jest aims to work out of the box, config free, on most JavaScript projects.” This means you can simply install Jest as a dependency for your project, and with no or minimal adjustments, you can start writing your first test.
  • Isolated: Isolation is a very important property when running tests. It ensures that different tests don’t influence each other’s results. For Jest, tests are executed in parallel, each running in their own process. This means they can’t interfere with other tests, and Jest acts as the orchestrator that collects the results from all the test processes.
  • Snapshots: Snapshots are a key feature for front-end testing because they allow you to verify the integrity of large objects. This means you don’t have to write large tests full of assertions to check if every property is present on an object and has the right type. You can simply create a snapshot and Jest will do the magic. Later, we’ll discuss in detail how snapshot testing works.
  • Rich API: Jest is known for having a rich API offering a lot of specific assertion types for very specific needs. Besides that, its great documentation should help you get started quickly.


Jest Vocabulary

Mock

From the Jest documentation, we can find the following description for a Jest mock: 

“Mock functions make it easy to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls).”

In addition, we can use a mock to return whatever we want it to return. This is very useful to test all the paths in our logic because we can control if a function returns a correct value, wrong value, or even throws an error.

In short, a mock can be created by assigning the following snippet of code to a function or dependency:

jest.fn()

Here’s an example of a simple mock, where we just check whether a mock has been called. We mock mockFn and call it. Thereafter, we check if the mock has been called:

const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled();

The following example also mocks a return value for checking specific business logic. We mock the returnsTrue function and let it return false:

const returnsTrue = jest.fn(() => false);
console.log(returnsTrue()); // false;

Spy

A spy has a slightly different behavior but is still comparable with a mock. Again, from the official docs, we read,

“Creates a mock function similar to jest.fn() but also tracks calls to object[methodName]. Returns a Jest mock function.”

What this means is that the function acts as it normally would—however, all calls are being tracked. This allows you to verify if a function has been called the right number of times and held the right input parameters.

Below, you’ll find an example where we want to check if the play method of a video returns the correct result but also gets called with the right parameters. We spy on the play method of the video object. Next, we call the play method and check if the spy has been called and if the returned result is correct. Pretty straightforward! In the end, we must call the mockRestore method to reset a mock to its original implementation.

const video = require('./video');

test('plays video', () => {
const spy = jest.spyOn(video, 'play');
const isPlaying = video.play();

expect(spy).toHaveBeenCalled();
expect(isPlaying).toBe(true);

spy.mockRestore();
});


Jest Basics

Let’s take a look at some basics on writing tests with Jest.

Describe Blocks

A describe block is used for organizing test cases in logical groups of tests. For example, we want to group all the tests for a specific class. We can further nest new describe blocks in an existing describe block. To continue with the example, you can add a describe block that encapsulates all the tests for a specific function of this class.

“It” or “Test“ Tests

We use the test keyword to start a new test case definition. The it keyword is an alias for the test keyword. Personally, I like to use it, which allows for more natural language flow of writing tests. For example:

describe('Beverage()', () => {
   it('should be delicious', () => {
      expect(myBeverage.delicious).toBeTruthy();
   });
});

Matchers

Next, let’s look at the matchers Jest exposes. A matcher is used for creating assertions in combination with the expect keyword. We want to compare the output of our test with a value we expect the function to return.

Again, let’s look at a simple example where we want to check if an instance of a class is the correct class we expect. We place the test value in the expect keyword and call the exposed matcher function toBeInstanceOf(<class>) to compare the values. The test results in the following code:

it('should be instance of Car', () => {
   expect(newTruck()).toBeInstanceOf(Car);
});

The complete list of exposed matchers can be found in the Jest API reference.

Snapshot Testing for React Front Ends

At last, the Jest documentation suggests using snapshot tests to detect UI changes. As I mentioned earlier, snapshot testing can also be applied for checking larger objects, or even the JSON response for API endpoints.

Let’s take a look at an example for React where we simply want to create a snapshot for a link object. The snapshot itself will be stored with the tests and should be committed alongside code changes.

it('renders correctly', () => {
   const tree = renderer
      .create(<Link page="http://www.facebook.com">Facebook</Link>)
      .toJSON();
   expect(tree).toMatchSnapshot();
});

Following, the above code renders the following snapshot:

exports[`renders correctly 1`] = `
<a
  className="normal"
  href="http://www.facebook.com"
  onMouseEnter={[Function]}
  onMouseLeave={[Function]}
>
  Facebook
</a>
`;

If the link object changes, this test will fail in the future. If the changes to the UI elements are correct, you should update the snapshots by storing the results in the snapshot file. You can automatically update snapshots using the Jest CLI tool by adding a “-u” flag when executing the tests.


Conclusion

In this article, We understood about the Jest Framework Concepts . We learnt more about the vocabulary associated with Jest testing, like mocks and spies. Also, we have covered some of the basics of Jest testing, like using describe blocks and the keywords it and expect with snapshot testing and why it’s particularly useful for front-end testing.

Thanks for reading ! I hope you enjoyed and learned about the Jest unit testing framework concepts . Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING!!???

JavaScript – Understanding Let vs Var vs Const Concepts

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, We will learn about most popular basic fundamental Variables concepts Lets, Var and Const from JavaScript. Let, Var, and Const are the various ways that JavaScript provides for declaration of JavaScript Variables. Var is an old way of declaring variables. Whereas, Let Const came into the picture from the ES6 version. Before starting the discussion about JavaScript let Vs var Vs const, let’s understand what ES is?

ES stands for Ecma Script, which is a scripting language specification specified by ECMA international. It standardized various implementations of JavaScript.

In this article, we will discuss differences of following ways of declaring a variable concerning their scope, use, and hoisting:

  • Var keyword: What, How, and Where?
  • Let keyword: What, How, and Where?
  • Const keyword: What, How, and Where?

A famous quote about learning is :

” Education is not the filling of a pail, but the lighting of a fire. “


Var keyword: What, How, and Where?

What is a “var” keyword ?

The “var” keyword is one of the ways using which we can declare a variable in JavaScript. Before the advent of ES6, var was the only way to declare variables. In other words, out of JavaScript let Vs var Vs const, var was the sole way to declare variables. Its syntax looks like below: 

Syntax:

var variable = value;

Scope of var:

The scope specifies where we can access or use the variables. When we declare a variable outside a function, its scope is global. In other words, it means that the variables whose declaration happens with “var” outside a function (even within a block) are accessible in the whole window. Whereas, when the declaration of a variable occurs inside a function, it is available and accessible only within that function.

It is illustrated with the help of following code snippet:

<html>

<body> Demonstrating var scopes in javascript:</br>
    <script type="text/javascript">
        var globalVariable = 5;
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        if (globalVariable == 5) 
        { 
            globalVariable = 10; 
            var localBlockVariable = 15;
            document.write("The value of global variable inside block is: ", globalVariable, "</br>"); 
        }
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        document.write("The value of block local variable outside block is: ", localBlockVariable, "</br>");

        function updateVariables() {
            globalVariable = 20; 
            localBlockVariable = 25;
            var localFunctionVariable = 30;
            document.write("The value of global variable inside function is: ", globalVariable, "</br>"); 
            document.write("The value of block local variable inside function is: ", localBlockVariable, "</br>");
        }

        updateVariables();
        document.write("The value of global variable outside function is: ", globalVariable, "</br>");
        document.write("The value of block local variable outside function is: ", localBlockVariable, "</br>");
        // This following statement will give error, as the local function variable can't be accessed outside
        // document.write("The value of function local variable outside function is: ", localFunctionVariable, "</br>");

    </script>
</body>

</html>

As is evident in the above code snippet, the variables declared in global and block scope are accessible in the whole window. In contrast, variables declared inside in the function can just be accessed within that function only.

Re-declaration of “var” variables:

The variables declared using var can be re-declared within the same scope also, and it will not raise any error.

Let’s understand it with the help of following code snippet:

<html>

<body> Demonstrating var scopes in javascript:</br>
    <script type="text/javascript">
        var globalVariable = 5;
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        if (globalVariable == 5) 
        { 
            var globalVariable = 10; // Re-declare in block
            document.write("The value of global variable inside block is: ", globalVariable, "</br>"); 
        }
        var globalVariable = 15;  // Re-declare in same scope
        document.write("The value of global variable outside block is: ", globalVariable, "</br>"); 

    </script>
</body>

</html>

As is clear from the above code snippet, the same variable “globalVariable” has been declared multiple times without any error.

Hoisting of var:

Hoisting is a JavaScript mechanism where variables and function declarations move to the top of their scope before code execution.

For Example, Let see below code snippet :

document.write(variable1);
var variable1 = "Hello World"

Here, JavaScript will interpret it as:

var variable1;
document.write(variable1); // variable1 will be undefined
variable1 = "Hello World"

So var variables hoist to the top of its scope and initialize with a value of undefined. If we access it before its declaration, the value of a variable declared using var is printed as “undefined,” .


Let keyword: What, How, and Where?

What is the “let” keyword?

In ES 2015 release, ES released one more keyword for declaration of variables, which is known as the “let“. Its syntax looks like below: 

Syntax:

let variable = value;

Scope of let:

let is block scoped. A block is a chunk of code bounded by {}. Moreover, a variable that one declares in a block with the “let” is only available for use within that block only.

Let’s try to understand the same with the help of following code snippet:

<html>

<body> Demonstrating let scopes in javascript:</br>
    <script type="text/javascript">
        let globalVariable = 5;
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        if (globalVariable == 5) 
        { 
            globalVariable = 10; 
            let localBlockVariable = 15;
            document.write("The value of global variable inside block is: ", globalVariable, "</br>"); 
        }
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        // This following statement will give error, as the local block variable can't be accessed outside
        // document.write("The value of block local variable outside block is: ", localBlockVariable, "</br>");

        function updateVariables() {
            globalVariable = 20; 
            localBlockVariable = 25; // This will raise error
            let localFunctionVariable = 30;
            document.write("The value of global variable inside function is: ", globalVariable, "</br>"); 
            // This following statement will give error, as the local block variable can't be accessed outside
            // document.write("The value of block local variable inside function is: ", localBlockVariable, "</br>");
        }

        updateVariables();
        document.write("The value of global variable outside function is: ", globalVariable, "</br>");
        // This following statement will give error, as the local block variable can't be accessed outside
        // document.write("The value of block local variable outside function is: ", localBlockVariable, "</br>");
        // This following statement will give error, as the local function variable can't be accessed outside
        // document.write("The value of function local variable outside function is: ", localFunctionVariable, "</br>");

    </script>
</body>

</html>

The above code snippet clearly understands that the variables declared using “let” are block-scoped and can’t access outside the block in which the declaration happens.

Re-declaration of “let” variables:

The variable declared using let can’t be re-declared.

It can be demonstrated easily with the help of following code snippet:

<html>

<body> Demonstrating let re-declare in javascript:</br>
    <script type="text/javascript">
        let globalVariable = 5;
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        if (globalVariable == 5) 
        { 
            // The following statement will raise an error
            // let globalVariable = 10;
            document.write("The value of global variable inside block is: ", globalVariable, "</br>"); 
        }

        // The following statement will raise an error
        // let globalVariable = 15;  // Re-declare in same scope
        document.write("The value of global variable outside block is: ", globalVariable, "</br>"); 

    </script>
</body>

</html>

The above code snippet clearly shows that the variables using let can’t be re-declared.

Hoisting of let:

Just like var, let declarations hoist to the top. But, unlike var, which initializes as undefined, the let keyword does not initialize. So if you try to use a let variable before the declaration, you’ll get a “Reference Error.

Consider the below code snippet to validate the same:

<html>

<body> Demonstrating let hoisting in javascript:</br>
    <script type="text/javascript">
    	document.write("The value of let variable is: ", letVariable, "</br>");

    	let letVariable = 5; // let variable declared later on
    	</script>
</body>

</html>

As is evident from the above code snippet, JavaScript raises “Uncaught ReferenceError if we access the variable as let before its declaration.


Const keyword: What, How, and Where?

What is the “const” keyword?

Variables declared with the “const” keyword maintain constant values and can’t change their values during the scope. Its syntax looks like below:

Syntax:

const variable = value1;

Scope of const:

Similar to let, the scope of the const variables is also blocked.

The following code snippet will help us understand it better:

<html>

<body> Demonstrating const scopes in javascript:</br>
    <script type="text/javascript">
        const globalVariable = 5;
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        if (globalVariable == 5) 
        { 
            // This following statement will give error, as const can't be assigned a new value
            // globalVariable = 10; 
            const localBlockVariable = 15;
            document.write("The value of global variable inside block is: ", globalVariable, "</br>"); 
            document.write("The value of block local variable inside block is: ", localBlockVariable, "</br>");
        }
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        // This following statement will give error, as the local block variable can't be accessed outside
        // document.write("The value of block local variable outside block is: ", localBlockVariable, "</br>");

        function updateVariables() {
            // This following statement will give error, as const can't be assigned a new value
            //globalVariable = 20; 
            const localBlockVariable = 25; // This will be considered a new variable
            const localFunctionVariable = 30; 
            document.write("The value of global variable inside function is: ", globalVariable, "</br>"); 
            document.write("The value of block local variable inside function is: ", localBlockVariable, "</br>");
        }

        updateVariables();
        document.write("The value of global variable outside function is: ", globalVariable, "</br>");
        // This following statement will give error, as the local block variable can't be accessed outside
        // document.write("The value of block local variable outside function is: ", localBlockVariable, "</br>");
        // This following statement will give error, as the local function variable can't be accessed outside
        // document.write("The value of function local variable outside function is: ", localFunctionVariable, "</br>");

    </script>
</body>

</html>

The above code snippet depicts that const variables are block-scoped and can’t update with a new value.

Re-declaration of const variables:

Similar to let variables, the variable declared using const can’t be re-declared.

We can easily demonstrate it with the help of following code snippet:

<html>

<body> Demonstrating const re-declare in javascript:</br>
    <script type="text/javascript">
        const globalVariable = 5;
        document.write("The value of global variable outside block is: ", globalVariable, "</br>");
        if (globalVariable == 5) 
        { 
            // The following statement will raise an error
            // const globalVariable = 10;
            document.write("The value of global variable inside block is: ", globalVariable, "</br>"); 
        }

        // The following statement will raise an error
        // const globalVariable = 15;  // Re-declare in same scope
        document.write("The value of global variable outside block is: ", globalVariable, "</br>"); 

    </script>
</body>

</html>

The above code snippet makes it clear that the const variables can’t re-declare.

Hoisting of const:

Just like “let,” “const” declarations hoist to the top but don’t initialize.

Consider the below code snippet to validate the same:

<html>

<body> Demonstrating const hoisting in javascript:</br>
    <script type="text/javascript">
    	document.write("The value of const variable is: ", varVariable, "</br>");

    	const constVariable = 5; // const variable declared later on
    	</script>
</body>

</html>

As is evident from the above code snippet, JavaScript raises “Uncaught ReferenceError” if we access a variable that we declare as const before its declaration.


Conclusion

In this article, We understood the Javascript Variables Let,Var and Const Concepts . We conclude that :

  • If you declare a variable using the “var” keyword, it will be in the global scope(accessible to the whole program) if declared outside all functions. It will have a local scope(accessible within the function only) if defined inside a function.
  • If you declare a variable using the “let” keyword, it will be blocked scope, i.e., any variable declared using let, will be accessible with the surrounding curly brackets ({ }) only.
  • If you declare a variable using the “const” keyword, you will not be able to change its value later on. As per scope, it will be the same as variables declared using the “let” keyword.

Thanks for reading ! I hope you enjoyed and learned about JavaScript different types of Variable Concepts. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING!!???

JavaScript – How to Schedule a Timeout ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about JavaScript Timeout Concept. There can be multiple scenarios where a programmer decides to execute a function at a later time, instead of running it instantaneously. This kind of behavior is called “scheduling as call or “scheduling a timeout”.

For better understanding about the timeout concepts, We will discuss the below following the list of topics which we are going to cover in this article:-

  • What is Timeout in JavaScript?
  • How to Schedule a Timeout in JavaScript?
  • How to clear the Scheduled Timeout in JavaScript?

A famous quote about learning is :

” Tell me and I forget, teach me and I may remember, involve me and I learn.”

So, Let’s begin.

What is Timeout in JavaScript?

We are sure that every programmer would have faced the following scenarios during their development career:

  • A specific function developed need to wait for some time before performing a particular task or triggering an event.
  • A specific function or task needs to repeat at a predefined interval.

Now, to handle all such kind of scenarios, JavaScript provides the “Timeout” functionality. Moreover, this functionality essentially allows the JavaScript developer to specify in a script that a particular function or piece of JavaScript code should execute after a specified interval of time has elapsed or should be repeated at a set interval time only.

How to schedule a Timeout in JavaScript?

JavaScript provides two methods to achieve the scheduling functionality. These are:

  • setTimeout()
  • setInterval()

Let’s discuss both of these functions in detail:

1. setTimeout()

This function allows us to run a function once after the specified interval of time. Additionally, its syntax looks like below:

Syntax:

let timerId = setTimeout(function, timeInMilliseconds, <em>param1, param2, ...</em>);

Where,

  • function: This parameter specifies the function that needs to execute. Additionally, it is a mandatory parameter.
  • timeInMilliseconds: The parameter specifies the “number of milliseconds” to wait before executing the code. If omitted, we use the value 0. Additionally, it is an optional parameter.
  • param1, param2, … : These are the additional parameters to pass to the function. Moreover, these are the optional parameters.

Let’s understand the usage of setTimeout() function with few examples for some sample scenarios:

Example 1: Wait for Alert

Now, consider a straightforward situation, that the user needs to display an alert after 2 seconds. One can achieve this with the help of setTimeout() as shown in the below code snippet:

<html>

   <body>  

      Demonstrating setTimeout in javascript

   </br>

      <script type = "text/javascript">

        setTimeout(()=>{

            alert("WelCome!!");

        },2000)

      </script>   

   </body>

</html>

It is evident from the above code that the browser will display the alert with “WelCome!!” as text after 2 seconds of the page load.

2. setInterval()

This method allows us to run a function repeatedly, starting after the interval of time and then repeating continuously at that interval. Additionally, its syntax looks like below:

Syntax:

let timerId = setInterval(<em>function, timeInMilliseconds, param1, param2, ...</em>)

Where,

  • function: This parameter specifies the function that needs to execute. Additionally, it is a mandatory parameter.
  • timeInMilliseconds: The parameter specifies the intervals (in milliseconds) on how often to execute the code. If the value is less than 10, we use the value 10. Also, it is an optional parameter.
  • param1, param2, … : These are the additional parameters to pass to the function. Moreover, these are the optional parameters.

Let’s understand the usage of setInterval() function with the following example:

Example: Display a digital clock

Let’s modify the above scenario of displaying a digital clock using the setInterval() method as shown in the below code snippet:

<html>
  <body>
    Demonstrating setInterval for displaying a clock in javascript:
  
    <p id="txt"></p>

    <script>
      const myLet = setInterval(myTimer, 1000);

      function myTimer() {
        const date = new Date();
        const time = date.toLocaleTimeString();
        document.getElementById("txt").innerHTML = time;
      }
    </script>

  </body>
</html>

As it is evident from the above code snippet, it displays the digital time that gets updated every second using the setInterval() method.

How to clear the Scheduled Timeout in JavaScript?

To cancel the scheduled tasks, JavaScript provides two methods:

  • clearTimeout()
  • clearInterval()

1. clearTimeout()

This method clears a timer set with the setTimeout() method and prevents the function set with the setTimeout() to execute. Additionally, its syntax looks like below:

Syntax:

clearTimeout(timerId_of_setTimeout)

Where,

  • timerId_of_setTimeout: This parameter is the ID value of the timer returned by the setTimeout() method. Moreover, it is a mandatory field.

Let’s understand the functionality of clearTimeout() in detail with the help of following code snippet:

<html>
	<body>

		<button onclick="startCount()">Start count!</button>
		<input type="text" id="txt">
		<button onclick="stopCount()">Stop count!</button>

		<p>
			Click on the "Start count!" button above to start the timer 
			</br> Click on the "Stop count!" button to stop the counting.
		</p>

		<script>
			let count = 0;
			let time;
			let timer_flag = 0;

			function timedCount() {
	  			document.getElementById("txt").value = count;
	  			count = count + 1;
	  			time = setTimeout(timedCount, 1000);
			}

			function startCount() {
	  			if (!timer_flag) {
	    			timer_flag = 1;
	    			timedCount();
	  			}
			}

			function stopCount() {
	  			clearTimeout(time);
	  			timer_flag = 0;
			}
		</script>

	</body>
</html>

The above code snippet file shows how using the clearTimeout() method. The user can prevent the function from executing, which set using the setTimeout() method.

2. clearInterval()

This method clears the timer set with the setInterval() method or can cancel the schedule created using the setInterval() method. Additionally, its syntax looks like below:

Syntax:

clearInterval(timerId);

Where,

timeId: The parameter signifies the timer returned by the setInterval() method. It is a required field.

Let’s understand the functionality of clearInterval() in detail with the help of following code snippet, where user can invoke the clearInterval() method to stop the digital clock initiated using setInterval() method:

<html>
  <body>
    Demonstrating clearInterval for displaying/Stopping a clock in javascript:
  
    <p id="txt"></p>

    <button onclick="stopWatch()">Stop Timer</button>

    <script>
      const myInterval = setInterval(myTimer, 1000);

      function myTimer() {
        const date = new Date();
        const time = date.toLocaleTimeString();
        document.getElementById("txt").innerHTML = time;
      }

      function stopWatch() {
        clearInterval(myInterval);
      }
    </script>

  </body>
</html>

In the above example, as soon as one clicks the Stop Timer button, the setInterval function terminates.

That’s all about in this article.

Conclusion

In this article, We understood about JavaScript Timeout Concepts. We conclude that :

  • If we want to schedule the execution of a task/function, the same can be achieved in JavaScript using the setTimeout() and setInterval() methods.
  • If we want to cancel the already scheduled tasks, the same can be achieved in JavaScript using the clearTimeout() and clearInterval() method.

Thanks for reading ! I hope you enjoyed and learned about JavaScript Timeout Concept. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

JavaScript – Understanding DOM Manipulation

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about JavaScript popular DOM Manipulation Concepts. When developing a front-end application, one of the most expected things a programmer wants to do is to manipulate the document structure in some way. It happens by using the Document Object Model (DOM), which is a set of APIs for controlling HTML and styling information.

For better understanding about the concepts, We will discuss the following details related to DOM manipulation using JavaScript:

  • What is DOM?
  • DOM Terminologies
  • How to access DOM elements using JavaScript?
  • How to manipulate DOM elements using JavaScript?

A famous quote about learning is :

” Anyone who stops learning is old, whether at twenty or eighty. Anyone who keeps learning stays young. “

So, Let’s start.

What is DOM?

 DOM is a data representation of the objects in the HTML and XML pages. The document loaded in your browser is represented by a document object model. Moreover, it is a “tree structure” representation created by the browser that enables the HTML structure to be easily accessed by programming languages. Additionally, the DOM represents the document as nodes and objects. In this way, programming languages can connect to the page. Furthermore, a simple structure of a web page DOM will look like below:

DOM Terminologies

Before starting working on the DOM, we should understand the following terminologies related to DOM:

  • Element node: It represents any element that exists in the DOM.
  • Root node: This is the top node in the tree, which in the case of HTML, is always the “HTML” node.
  • Child node: This is a node that is directly inside another node. For example, <h2> is a child of  <body> in the above example.
  • Descendant node: This is a node that exists anywhere in the hierarchy of another node. For example, <h2> is a descendant of <html> in the above example.
  • Parent node: This is a node that has another node inside it. For example, <body> is the parent node of  <h2> in the above example.
  • Sibling nodes: The nodes which sit on the same level in the DOM tree. For example, <h2> and  <p> are siblings in the above example.
  • Text node: This is a node that contains a text string.

As we are now clear about the fundamental terminologies used in a document, let’s move to the next section to understand how the DOM elements can be accessed using JavaScript.

How to access DOM elements using JavaScript?

A webpage in JavaScript is a document, and JavaScript provides an object “document,” which designates the complete webpage. Moreover, the document object provides various properties and methods to access and manipulate the web elements loaded on the page. To identify and access the DOM elements, JavaScript uses three ways:

  • Accessing elements By ID
  • Accessing elements By TagName
  • Accessing elements By className

Let’s understand the details of each of these ways in the following sections:

1. Accessing elements By ID:

JavaScript can find HTML elements in the DOM based on the “id” of the element. The document object provides a method “getElementById()” to accomplish this task. Moreover, its syntax looks like below: 

Syntax :

document.getElementById(“IDName”);

Let’s understand the usage of the “getElementById” method with the help of the following code snippet.

<body>
 Demonstrating getElementById in javascript:    </br>
    <b id="bold">Development Tools Tutorial</b>
 
     <script type="text/javascript">
    // Get the element by Id and update text on that
     document.getElementById("bold").innerHTML = "Development Tools";
     </script>
    </body>
</html>

In the above example, we can see that element by id “bold” has been found. In addition to that, we also changed its attribute innerHTML to Development Tools.

2. Accessing a DOM element By TagName:

JavaScript can find the elements in the HTML based on the “tagName” and return an array of matching nodes. The inbuilt function, of document object, available for this is getElementByTagName(). Additionally, its syntax looks like below:

Syntax :

document.getElementByTagName(“tagName”);

Let’s understand the usage of “getElementByTagName” method with the help of following code snippet:

<html>    
 <body>
 Demonstrating getElementByTag in javascript:    </br>
    <b>Development Tools Tutorial</b>
 
     <script type="text/javascript">
    // Get the element by tag <b> and update text on that
     document.getElementsByTagName("b")[0].innerHTML = "Development Tools";
     </script>
    </body>
</html>

In the above example, we can see that the element by HTML tag “<b>” has been found. Additionally, we changed its attribute innerHTML to Development Tools.

3. Accessing a DOM element By ClassName:

JavaScript can find the element in the HTML based on the className attribute of the element and returns an array of matching nodes. The inbuilt function available in this operation is getElementByClassName(). Additionally, its syntax looks like below:

Syntax :

document.getElementByClassName(“ClassName”);

Let’s understand the usage of “getElementByClassName” method with the help of following code snippet:

<html>    
 <body>
 Demonstrating getElementsByClassName in javascript:    </br>
    <b class="bold">Development Tools Tutorial</b>
 
     <script type="text/javascript">
    // Get the element by className "bold" and update text on that
     document.getElementsByClassName("bold")[0].innerHTML = "Development Tools";
     </script>
    </body>
</html>

In the above example, we can see that element by className “bold” has been found. Additionally, we changed its attribute innerHTML to Development Tools.

How to manipulate DOM elements using JavaScript?

Apart from accessing the elements, JavaScript provides some methods and properties which can manipulate or change the values of the DOM elements. Few of those methods and properties are:

  • write
  • innerHTML
  • attributeName
  • Style.property
  • setAttribute
  • createElement and appendChild
  • removeChild
  • replaceChild

Let’s discuss all of these methods and properties in detail in the below sections:

1. write :

This method writes new elements or text to the HTML page. Additionally, its syntax looks like below:

Syntax:

document.write(“data”);

Let’s understand the usage of “write()” method with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating document's write function in javascript:
 
   </br>
 
      <script type = "text/javascript">
 
         document.write("Development Tools Tutorials");
 
         document.write("</br>");
 
         document.write("<b>JavaScript Tutorial</b>");
 
      </script>   
 
   </body>
 
</html>

In the above example, we use the write function to add a text as well as to add a new HTML element.

2. innerHTML :

It is a property that we use to get or set the HTML or XML markup contained within the element. Also, its syntax looks like below:

Syntax:

node.innerhtml = “changingText”;

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “innerHTML” property with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating innerHTML property in javascript
 
   </br>
 
   <b id="example">JavaScript Tutorial</b>
 
      <script type = "text/javascript">
 
         document.getElementById("example").innerHTML="Development Tools";
 
      </script>   
 
   </body>
 
</html>

In the above example, we can see that the innerHTML property updates the text of the HTML element.

3. attributeName :

We use his property is used to get and update the value of an attribute of an HTML element. Additionally, its syntax looks like below:

Syntax :

node.atrributeName = value;

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “attributeName” property with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating attributeName property in javascript
 
   </br>
 
   <b id="example">JavaScript Tutorial</b>
 
      <script type = "text/javascript">
 
         // Update the "id" of the element to "demo" which has "id" as "example"
         document.getElementById("example").id="demo";
 
         
         // Get the element with "id" as "demo" and update its innerHTML text
         document.getElementById("demo").innerHTML="Development Tools";
 
      </script>   
 
   </body>
 
</html>

In the above example, the element is first changed from “example” to “demo” and then based on id “demo,” we are manipulating the text of the element.

4. Style.property :

We use this property to set or edit the existing style properties of an HTML tag. Also, its syntax looks like below:

Syntax:

node.Style.attribute = value;

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “Style.attribute” method with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating updating style properties in javascript
 
   </br>
 
   <b id="example">JavaScript Tutorial</b>
 
      <script type = "text/javascript">
 
         document.getElementById("example").style.color = "red";
 
      </script>   
 
   </body>
 
</html>

In the above example, the style attribute “color” has been updated to “red.”

5. setAttribute :

We use this function to create or update an attribute for the existing HTML element. Additionally, its syntax looks like below:

Syntax :

node.setAttribute(attributeName, attributeValue);

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “setAttribute()” method with the help of following code snippet:

<html>
 
   <body>  
 
      Demonstrating setAttribute function in javascript
 
   </br>
 
   <b>JavaScript Tutorial</b>
 
      <script type = "text/javascript">
 
         document.getElementsByTagName("b")[0].setAttribute("id","example");
 
         document.getElementById("example").innerHTML="Development Tools";
 
      </script>   
 
   </body>
 
</html>

In the above example, the element is first added a new attribute “id” with value “example” to the <b> tagged HTML element and then based on id “example,” we are manipulating the text of the element.

6. createElement and appendChild :

This createElement() method is used to create a new element in the HTML DOM. Once the creation of element happens, it can append to a parent element using the appendChild() method. Moreover, its syntax looks like below: 

Syntax:

// Create a new node
var node = document.createElement(tagName);


// Append the node to parent
document.parentTag.appendChild(node);

Let’s understand the usage of “createElement() and appendChild()  method with the help of following code snippet:

<html>

   <body>  

      Demonstrating createElement function in javascript

   </br>

   <b>JavaScript Tutorial</b>

      <script type = "text/javascript">

         var b = document.createElement("a");

         b.innerHTML="ClickME";

         document.body.appendChild(b);

      </script>   

   </body>

</html>

In the above example, we created a new “anchor” element with the help of the “createElement” method and then appended the element to the document’s <body> element. Hence, it displays on the HTML page.

7. removeChild :

This function removes an HTML element from the document. Also, its syntax looks like below:

Syntax:

node.removechild(childNode);

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “removeChild()” method with the help of following code snippet:

<html>

   <body>  

      Demonstrating removeChild function in javascript

   </br>

   <b>TOOLS QA</b>

   </br>

   <b id="demo">JavaScript Tutorial</b>

      <script type = "text/javascript">

        document.body.removeChild(document.getElementById("demo"));

      </script>   

   </body>

</html>

In the above example, we removed the HTML element, which was having “id” as “demo,” due to which the value “JavaScript Tutorial” could not print on the webpage.

8. replaceChild :

The replaceChild() method replaces a child node with a new node. The new node could be an existing node in the document, or you can create a new node. Additionally, its syntax looks like below: 

Syntax:

node.replaceChild(newnode, oldnode);

Where,

node: is any web element that can be found on the web page using document.getElementBy<Id/tagName/className>.

Let’s understand the usage of “replaceChild()” method with the help of following code snippet:

<html>
   <body>  
      Demonstrating replaceChild function in javascript: </br>
 
      <ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>

      <button onclick="replaceListValue()">Replace first value of list</button>

      <script type = "text/javascript">
         
         function replaceListValue() {
            // Create a new list element
            var newListElement = document.createElement("li");
            var textNode = document.createTextNode("Water");
            newListElement.appendChild(textNode);

            // Replace the first element of list by the newly created element
            var list = document.getElementById("myList");
            list.replaceChild(newListElement, list.childNodes[0]);
         }
    
      </script>   
 
   </body>
 
</html>

In the above example, we replace the first element of the list on the click of the button. The replaceChild method also achieves the same.

That’s all about in this article.

Conclusion

In this article, We understood about JavaScript Fundamental Concept DOM Manipulation. We conclude that :

  • The document loaded in a browser is represented by the document object model (DOM). Moreover, it is a data representation of the objects in the HTML page.
  • Also, the ID, Tag Name, or Class Name of the HTML elements can access the DOM elements.
  • In addition to the above, JavaScript also provides various methods such as setAttribute, createElement, appendChild, removeChild, etc. Moreover, we can use them to manipulate/change multiple HTML elements within the page at run time.

Thanks for reading !! I hope you enjoyed and learned about JavaScript Fundamental Concept DOM Manipulation. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Android – An Overview of Room Persistent Library

Hello Readers, CoolMonkTechie heartily welcomes you in this article (An Overview of Room Persistent Library).

In this article, we will learn about Android Room Persistent Library Overview. We will try to understand the basics of Room, how to use it, major components in Room and type converters in Room.

For better understanding about Android Room Persistent Library, we will discuss the below points:

  • What is Room in Android ?
  • What are the advantages of Room in Android Application ?
  • How to use it in our Project or Application?
  • What is major components of Room in Android ?
  • Type Converters in Room

A famous quote about learning is :

He who learns but does not think, is lost! He who thinks but does not learn is in great danger.

So, Let’s start.

What is Room in Android ?

Room is an Android persistence library, which is part of Google’s Android Jetpack project.

According to the Android Documentation, “Room provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.

The library helps us create a cache of our app’s data on a device that’s running our app. This cache, which serves as our app’s single source of truth, allows users to view a consistent copy of key information within our app, regardless of whether users have an internet connection.

It means that Apps that handle significant amounts of structured data can benefit from persisting that data locally. The most common use case is to cache relevant pieces of data. That way, when the device cannot access the network, the user can still browse that content while they are offline. Any user-initiated content changes are then synced to the server after the device is back online.

What is the advantages of Room in Android Application ?

There are multiple advantages of using Room as compared to other alternate solutions like SQLiteOpenHelper:

  • Compile-time verification of queries.
  • Reduces boilerplate code.
  • Easy to understand and use.
  • Easy integration with RxJava, LiveData and Kotlin Coroutines.

How to use it in our Project or Application?

To use Room in your app, add the following dependencies to our app’s build.gradle file:

dependencies {
  def room_version = "2.2.5"

  implementation "androidx.room:room-runtime:$room_version"
  annotationProcessor "androidx.room:room-compiler:$room_version" // For Kotlin use kapt instead of annotationProcessor

  // optional - Kotlin Extensions and Coroutines support for Room
  implementation "androidx.room:room-ktx:$room_version"

  // optional - RxJava support for Room
  implementation "androidx.room:room-rxjava2:$room_version"

  // optional - Guava support for Room, including Optional and ListenableFuture
  implementation "androidx.room:room-guava:$room_version"

  // Test helpers
  testImplementation "androidx.room:room-testing:$room_version"
}

Note: For Kotlin-based apps, make sure we use kapt instead of annotationProcessor. We should also add the kotlin-kapt plugin.

What is major components of Room in Android ?

There are 3 major components in Room:

  • Database: Contains the database holder and serves as the main access point for the underlying connection to our app’s persisted, relational data.
  • Entity: Represents a table within the database.
  • DAO: Contains the methods used for accessing the database.

Our application uses the Room database to get the data access objects, or DAOs, associated with our database. The app then uses each DAO to get entities from the database and save any changes to those entities back to the database. Finally, the app uses an entity to get and set values that correspond to table columns within the database.

This relationship among the different components of Room appears in Figure 1:

1. Database

As mentioned earlier, it contains the database holder and serves as the main access point for the underlying connection to our app’s persisted, relational data. The class that’s annotated with @Database should satisfy the following conditions:

  • Be an abstract class that extends RoomDatabase.
  • Include the list of entities associated with the database within the annotation.
  • Contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao.

At runtime, you can acquire an instance of Database by calling Room.databaseBuilder() or Room.inMemoryDatabaseBuilder().

@Database(entities = arrayOf(User::class), version = 1)
abstract class UserDatabase : RoomDatabase() {
  abstract fun userDao(): UserDao
}

To get an instance of the database, you can use the following method:

val db = Room.databaseBuilder(
    applicationContext,
    UserDatabase::class.java, "users-db"
    ).build()

We have noted that :

  • If our app runs in a single process, we should follow the singleton design pattern when instantiating an AppDatabase object. Each RoomDatabase instance is fairly expensive, and we rarely need access to multiple instances within a single process.
  • If our app runs in multiple processes, include enableMultiInstanceInvalidation() in our database builder invocation. That way, when we have an instance of AppDatabase in each process, we can invalidate the shared database file in one process, and this invalidation automatically propagates to the instances of AppDatabase within other processes.”

2. Entity

An Entity represents a table within a database. This class is annotated with @Entity annotation. Data members in these class represent the columns within a table. For example :

@Entity
data class User(
  @PrimaryKey val uid: Int,
  @ColumnInfo(name = "first_name") val firstName: String?,
  @ColumnInfo(name = "last_name") val lastName: String?
)
  • All the fields in an entity must either be public or have getter & setter methods.
  • Entity class should have an empty constructor (if all fields are accessible) or a parametrised constructor which takes all the fields. Room can also use partial constructors.
  • Each entity class must have at least one primary key. We can use either @PrimaryKey annotation to define single field primary key or primaryKeys attribute of @Entity annotation for multiple fields. We can also use autoGenerate property of @PrimaryKey annotation to automatically assign primary keys.
@Entity(primaryKeys = arrayOf("firstName", "lastName"))
  • By default, Room uses the class name as the database table name. If we want the table to have a unique name, set the tableName property of the @Entity annotation. Similarly, we can use the name property of the @ColumnInfo annotation for defining the name of columns.
@Entity(tableName = "users")
  • If we don’t want to persist in any field, we can annotate them using @Ignore.
@Ignore val picture: Bitmap?
  • We can use the indices property of @Entity annotation to add indices to an entity. Also, we can create unique indices by setting the unique property of an @Index annotation to true.
@Entity(indices = arrayOf(Index(value = ["last_name", "address"])))@Entity(indices = arrayOf(Index(value = ["first_name", "last_name"],
        unique = true)))

3. Data Access Object (DAO)

DAOs provide an API for accessing the database. This is an interface which is annotated with @Dao annotation. All the methods in this interface are used for getting data from the database or changing the database. These methods are annotated with annotations like @Query, @Insert, @Delete.

@Dao
interface UserDao {
  @Query("SELECT * FROM user")
  fun getAll(): List<User>
  
  @Query("SELECT * FROM user WHERE uid IN (:userIds)")
  fun loadAllByIds(userIds: IntArray): List<User>
  
  @Insert
  fun insertAll(vararg users: User)
  
  @Delete
  fun delete(user: User)
}

Here, all queries using UserDao are made on the caller thread. So we should take care that no method is invoked from the UI(main) thread.

Type Converters in Room

Sometimes, we might need to persist a custom data type in a single database column. We can use type converters for these types of use cases.

class Converters {
  @TypeConverter
  fun fromTimestamp(value: Long?): Date? {
  return value?.let { Date(it) }
  }

  @TypeConverter
  fun dateToTimestamp(date: Date?): Long? {
  return date?.time?.toLong()
  }
}

Next, we have to add the @TypeConverters annotation to the RoomDatabase class so that Room can use the converter, we’ve defined for each entity and DAO in that RoomDatabase.

@Database(entities = arrayOf(User::class), version = 1)
@TypeConverters(Converters::class)
abstract class UserDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}

So Room takes care of these concerns for us, we highly recommend using Room instead of SQLite.

That’s all about in this article.

Conclusion

In this article, we understood about Android Room Persistent Library Overview like Basic, advantages, How to use it, major components and custom type converters in Room.

Thanks for reading! I hope you enjoyed and learned about the basic of Android Room Persistent Library. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of Android as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

ReactJS – Recommended Valuable Design Principles You Need To Know

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about Recommended Design Principles used in ReactJS , and then we will also try to understand a better idea of how we decide what React does and what React doesn’t do, and what our development philosophy is like. The React recommends below common design principles which we will discuss one by one:

  • Composition
  • Common Abstraction
  • Escape Hatches
  • Stability
  • Interoperability
  • Scheduling
  • Developer Experience
  • Debugging
  • Configuration
  • Beyond the DOM
  • Implementation
  • Optimized for Tooling
  • Dogfooding

A famous quote about learning is :

Learning never exhausts the mind.

So, Let’s begin.

1. Composition

The key feature of React is composition of components. Components written by different people should work well together. It is important to us that you can add functionality to a component without causing rippling changes throughout the codebase.

For example, it should be possible to introduce some local state into a component without changing any of the components using it. Similarly, it should be possible to add some initialization and teardown code to any component when necessary.

Components are often described as “just functions” but in our view they need to be more than that to be useful. In React, components describe any composable behavior, and this includes rendering, lifecycle, and state. Some external libraries like Relay augment components with other responsibilities such as describing data dependencies. It is possible that those ideas might make it back into React too in some form.

2. Common Abstraction

In general, we resist adding features that can be implemented in userland. We don’t want to bloat your apps with useless library code. However, there are exceptions to this.

For example, if React didn’t provide support for local state or lifecycle methods, people would create custom abstractions for them. When there are multiple abstractions competing, React can’t enforce or take advantage of the properties of either of them. It has to work with the lowest common denominator.

This is why sometimes we add features to React itself. If we notice that many components implement a certain feature in incompatible or inefficient ways, we might prefer to bake it into React. We don’t do it lightly. When we do it, it’s because we are confident that raising the abstraction level benefits the whole ecosystem. State, lifecycle methods, cross-browser event normalization are good examples of this.

3. Escape Hatches

React is pragmatic. It is driven by the needs of the products written at Facebook. While it is influenced by some paradigms that are not yet fully mainstream such as functional programming, staying accessible to a wide range of developers with different skills and experience levels is an explicit goal of the project.

If we want to deprecate a pattern that we don’t like, it is our responsibility to consider all existing use cases for it and educate the community about the alternatives before we deprecate it. If some pattern that is useful for building apps is hard to express in a declarative way, we will provide an imperative API for it. If we can’t figure out a perfect API for something that we found necessary in many apps, we will provide a temporary subpar working API as long as it is possible to get rid of it later and it leaves the door open for future improvements.

4. Stability

We value API stability. At Facebook, we have more than 50 thousand components using React. Many other companies, including Twitter and Airbnb, are also heavy users of React. This is why we are usually reluctant to change public APIs or behavior.

However we think stability in the sense of “nothing changes” is overrated. It quickly turns into stagnation. Instead, we prefer the stability in the sense of “It is heavily used in production, and when something changes, there is a clear (and preferably automated) migration path.”

When we deprecate a pattern, we study its internal usage at Facebook and add deprecation warnings. They let us assess the impact of the change. Sometimes we back out if we see that it is too early, and we need to think more strategically about getting the codebases to the point where they are ready for this change.

If we are confident that the change is not too disruptive and the migration strategy is viable for all use cases, we release the deprecation warning to the open source community. We are closely in touch with many users of React outside of Facebook, and we monitor popular open source projects and guide them in fixing those deprecations.

Given the sheer size of the Facebook React codebase, successful internal migration is often a good indicator that other companies won’t have problems either. Nevertheless sometimes people point out additional use cases we haven’t thought of, and we add escape hatches for them or rethink our approach.

We don’t deprecate anything without a good reason. We recognize that sometimes deprecations warnings cause frustration but we add them because deprecations clean up the road for the improvements and new features that we and many people in the community consider valuable.

5. Interoperability

We place high value in interoperability with existing systems and gradual adoption. Facebook has a massive non-React codebase. Its website uses a mix of a server-side component system called XHP, internal UI libraries that came before React, and React itself. It is important to us that any product team can start using React for a small feature rather than rewrite their code to bet on it.

This is why React provides escape hatches to work with mutable models, and tries to work well together with other UI libraries. You can wrap an existing imperative UI into a declarative component, and vice versa. This is crucial for gradual adoption.

6. Scheduling

Even when your components are described as functions, when you use React you don’t call them directly. Every component returns a description of what needs to be rendered, and that description may include both user-written components like <LikeButton> and platform-specific components like <div>. It is up to React to “unroll” <LikeButton> at some point in the future and actually apply changes to the UI tree according to the render results of the components recursively.

This is a subtle distinction but a powerful one. Since you don’t call that component function but let React call it, it means React has the power to delay calling it if necessary. In its current implementation React walks the tree recursively and calls render functions of the whole updated tree during a single tick. However in the future it might start delaying some updates to avoid dropping frames.

This is a common theme in React design. Some popular libraries implement the “push” approach where computations are performed when the new data is available. React, however, sticks to the “pull” approach where computations can be delayed until necessary.

React is not a generic data processing library. It is a library for building user interfaces. We think that it is uniquely positioned in an app to know which computations are relevant right now and which are not.

If something is offscreen, we can delay any logic related to it. If data is arriving faster than the frame rate, we can coalesce and batch updates. We can prioritize work coming from user interactions (such as an animation caused by a button click) over less important background work (such as rendering new content just loaded from the network) to avoid dropping frames.

To be clear, we are not taking advantage of this right now. However the freedom to do something like this is why we prefer to have control over scheduling, and why setState() is asynchronous. Conceptually, we think of it as “scheduling an update”.

The control over scheduling would be harder for us to gain if we let the user directly compose views with a “push” based paradigm common in some variations of Functional Reactive Programming. We want to own the “glue” code.

It is a key goal for React that the amount of the user code that executes before yielding back into React is minimal. This ensures that React retains the capability to schedule and split work in chunks according to what it knows about the UI.

There is an internal joke in the team that React should have been called “Schedule” because React does not want to be fully “reactive”.

7. Developer Experience

Providing a good developer experience is important to us.

For example, we maintain React DevTools which let you inspect the React component tree in Chrome and Firefox. We have heard that it brings a big productivity boost both to the Facebook engineers and to the community.

We also try to go an extra mile to provide helpful developer warnings. For example, React warns you in development if you nest tags in a way that the browser doesn’t understand, or if you make a common typo in the API. Developer warnings and the related checks are the main reason why the development version of React is slower than the production version.

The usage patterns that we see internally at Facebook help us understand what the common mistakes are, and how to prevent them early. When we add new features, we try to anticipate the common mistakes and warn about them.

We are always looking out for ways to improve the developer experience. We love to hear your suggestions and accept your contributions to make it even better.

8. Debugging

When something goes wrong, it is important that you have breadcrumbs to trace the mistake to its source in the codebase. In React, props and state are those breadcrumbs.

If you see something wrong on the screen, you can open React DevTools, find the component responsible for rendering, and then see if the props and state are correct. If they are, you know that the problem is in the component’s render() function, or some function that is called by render(). The problem is isolated.

If the state is wrong, you know that the problem is caused by one of the setState() calls in this file. This, too, is relatively simple to locate and fix because usually there are only a few setState() calls in a single file.

If the props are wrong, you can traverse the tree up in the inspector, looking for the component that first “poisoned the well” by passing bad props down.

This ability to trace any UI to the data that produced it in the form of current props and state is very important to React. It is an explicit design goal that state is not “trapped” in closures and combinators, and is available to React directly.

While the UI is dynamic, we believe that synchronous render() functions of props and state turn debugging from guesswork into a boring but finite procedure. We would like to preserve this constraint in React even though it makes some use cases, like complex animations, harder.

9. Configuration

We find global runtime configuration options to be problematic.

For example, it is occasionally requested that we implement a function like React.configure(options) or React.register(component). However this poses multiple problems, and we are not aware of good solutions to them.

What if somebody calls such a function from a third-party component library? What if one React app embeds another React app, and their desired configurations are incompatible? How can a third-party component specify that it requires a particular configuration? We think that global configuration doesn’t work well with composition. Since composition is central to React, we don’t provide global configuration in code.

We do, however, provide some global configuration on the build level. For example, we provide separate development and production builds. We may also add a profiling build in the future, and we are open to considering other build flags.

10. Beyond the DOM

We see the value of React in the way it allows us to write components that have fewer bugs and compose together well. DOM is the original rendering target for React but React Native is just as important both to Facebook and the community.

Being renderer-agnostic is an important design constraint of React. It adds some overhead in the internal representations. On the other hand, any improvements to the core translate across platforms.

Having a single programming model lets us form engineering teams around products instead of platforms. So far the tradeoff has been worth it for us.

11. Implementation

We try to provide elegant APIs where possible. We are much less concerned with the implementation being elegant. The real world is far from perfect, and to a reasonable extent we prefer to put the ugly code into the library if it means the user does not have to write it. When we evaluate new code, we are looking for an implementation that is correct, performant and affords a good developer experience. Elegance is secondary.

We prefer boring code to clever code. Code is disposable and often changes. So it is important that it doesn’t introduce new internal abstractions unless absolutely necessary. Verbose code that is easy to move around, change and remove is preferred to elegant code that is prematurely abstracted and hard to change.

12. Optimized for Tooling

Some commonly used APIs have verbose names. For example, we use componentDidMount() instead of didMount() or onMount(). This is intentional. The goal is to make the points of interaction with the library highly visible.

In a massive codebase like Facebook, being able to search for uses of specific APIs is very important. We value distinct verbose names, and especially for the features that should be used sparingly. For example, dangerouslySetInnerHTML is hard to miss in a code review.

Optimizing for search is also important because of our reliance on codemods to make breaking changes. We want it to be easy and safe to apply vast automated changes across the codebase, and unique verbose names help us achieve this. Similarly, distinctive names make it easy to write custom lint rules about using React without worrying about potential false positives.

JSX plays a similar role. While it is not required with React, we use it extensively at Facebook both for aesthetic and pragmatic reasons.

In our codebase, JSX provides an unambiguous hint to the tools that they are dealing with a React element tree. This makes it possible to add build-time optimizations such as hoisting constant elements, safely lint and codemod internal component usage, and include JSX source location into the warnings.

13. Dogfooding

 Dogfooding it means that our vision stays sharp and we have a focused direction going forward.

We try our best to address the problems raised by the community. However we are likely to prioritize the issues that people are also experiencing internally at Facebook. Perhaps counter-intuitively, we think this is the main reason why the community can bet on React.

Heavy internal usage gives us the confidence that React won’t disappear tomorrow. React was created at Facebook to solve its problems. It brings tangible business value to the company and is used in many of its products. 

For example, we added support for web components and SVG to React even though we don’t rely on either of them internally. We are actively listening to your pain points and address them to the best of our ability. The community is what makes React special to us, and we are honored to contribute back.

After releasing many open source projects at Facebook, we have learned that trying to make everyone happy at the same time produced projects with poor focus that didn’t grow well. Instead, we found that picking a small audience and focusing on making them happy brings a positive net effect. That’s exactly what we did with React, and so far solving the problems encountered by Facebook product teams has translated well to the open source community.

The downside of this approach is that sometimes we fail to give enough focus to the things that Facebook teams don’t have to deal with, such as the “getting started” experience. We are acutely aware of this, and we are thinking of how to improve in a way that would benefit everyone in the community without making the same mistakes we did with open source projects before.

That’s all about in this article.

Conclusion

In this article, We understood about Recommended Design Principles used in ReactJS.

Thanks for reading ! I hope you enjoyed and learned about React recommended design principles. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

ReactJS – Is SOLID Valid For React?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about topic ” Is Solid principle valid for React? “. We will focus each principle details of the SOLID one by one using below points:

  • What does the principle mean?
  • How does React adhere to it ?


SOLID is an interesting topic in React. While React doesn’t force the principles onto you, at least it often allows you to follow them.

A famous quote about learning is :

That is what learning is. You suddenly understand something you’ve understood all your life, but in a new way. ”  

So, Let’s begin.


What does SOLID stand for?

SOLID is an acronym build by the first letter of 5 object oriented programming design principles. The basic idea is, if you follow these principles, your software gets better.

  • Single responsibility principle
  • Open/closed principle
  • Liskov substitution principle
  • Interface segregation principle
  • Dependency inversion principle


What do these principles imply and how does React adhere to it?


1. Single Responsibility Principle

What does it mean?

A class should only have a single responsibility.

How does React adhere to it?

React applications consist of components, which are classes that inherit from the React.Component class. You can start building your application as a component and if it gets too complex, you can split this component up into multiple smaller components.

React doesn’t force you to adhere to the principle, but you can split up your component classes into smaller components till you achieved single responsibility for all of your components.

For example, you could have a button component that just handles clicks and an input component that just handles user input. A level above you use a form component that uses multiple instances of the button and input component to get user credentials and above that a connection component that takes form data and sends it to a server.


2. Open Close Principle

What does it mean?

Software entities should be open for extension, but closed for modification. Which means you can extends it without modifying its source code.

How does React adhere to it?

Reacts component model is build around aggregation instead of inheritance. So you only extend the base React.Component and not its children. This prevents you from overriding behavior of existing components directly. The only way is to wrap it with your own component.

You could for example wrap a Button with a RedButton that always applies specific styles to the basic Button, but the Button is closed for modification.

This is less flexible than inheritance, but it also simplifies the API. While you don’t have direct access to the methods like in an extension, you only have to care about props in your aggregation.


3. Liskov Substitution Principle

What does it mean?

Objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

How does React adhere to it?

Well, it doesn’t use inheritance at all. Sure you extend React.Component, but this class is essentially treated as abstract in React applications, you never directly create an object from it, so you never have to replace it with a child-class later.

On the other hand, you find yourself writing aggregations that should act like their wrapped components rather often. Like the Button I mentioned before. You want that RedButton to be already styled, but you also want it to act like the Button, but since the API between components always is just props, it’s often simple to add something while your wrappers props are passed down to the wrapped component. Because everything is dynamic, your wrapper doesn’t even have to know everything about the data that would originally be passed down to the wrapped component, in the RedButton example it would just have to know about the style.


4. Interface Segregation Principle

What does it mean?

Many client-specific interfaces are better than one general-purpose interface.

How does React adhere to it?

Because React is written in JavaScript, it benefits from the dynamic nature of this language. There are no formal interfaces. If you don’t use refs, which allow you to directly call class methods of a component, the only interaction between components is via props and nobody forces you to use props you don’t need.

If you have a wrapper component that passes down an onClick handler that shows an alert with the wrapped components class name, you can use this wrapper to wrap all components that use this onClick prop and if they don’t, the handler is just ignored.

My experience with this fact was that it simplified many things, you wouldn’t get lost in defining many small interfaces beforehand. The drawback was that I often found me in situations where I passed down props the wrapped component did simply ignore silently. At least glamorous-native threw a few warnings when I tried to pass down unknown CSS attributes. For this it often helps to use PropTypes or something.


5. Dependency Inversion Principle

What does it mean?

One should depend upon abstractions, not concretions.

How does React adhere to it?

In practice, this principle is often followed by removing class names from other classes. Like, you could have a List that has Items, so you could get the idea to create your Item objects inside the List class, now you have your List tightly coupled with your Item. Somewhere in your List class is a new Item(...) or Item.create(...) etc.

React doesn’t strictly adhere to it, you can pass an array of string to your List component and create Item children from it no problem.

But you can also tell the List it should simply render out its children independent of what they are, maybe add some keys to it or justify them etc.

Now you can create an array of Items, sprinkle it with some HighlightItems, both created from different string arrays and put them inside your List who won’t be the wiser.

That’s all about in this article.


Conclusion

In this article, We understood What do SOLID principles imply and how does React adhere to it. We learnt that React doesn’t force the principles onto you, but at least it often allows you to follow them. Sometimes it gets easier because of JavaScript, sometimes JavaScript makes it harder, but overall it is possible to write SOLID applications with React..

Thanks for reading ! I hope you enjoyed and learned about SOLID imply and adhere concepts in React. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Android – How Does RecyclerView Work Internally?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about how recyclerView actually works in the Android system. This article will focus the below points to understand the Android RecyclerView Working Concepts:

  • Overview
  • What is RecyclerView?
  • The Building Components of RecyclerView
  • The Benefits of RecyclerView
  • RecyclerView Used Patterns
  • How it actually works?
  • The View Optimization of RecyclerView

A famous quote about learning is :

Tell me and I forget, teach me and I may remember, involve me and I learn.

So Let’s begin one by one.

Overview

Displaying a list or grid of data is one of the most common UI tasks in Android. Lists vary from simple to very complex. A list of text views might show simple data, such as a shopping list. A complex list, such as an annotated list of vacation destinations, might show the user many details inside a scrolling grid with headers.

To support all these use cases, Android provides the RecyclerView widget. So what’s next.

What is RecyclerView?

RecyclerView is a ViewGroup, which populates a list on a collection of data provided with the help of ViewHolder and draws it to the user on-screen.

The Building Components of RecyclerView

The major components of RecyclerView are:

  • Adapter
  • ViewHolder
  • LayoutManager

1. Adapter

It is a subtype of RecyclerView. Adapter class. This takes the data set which has to be displayed to the user in RecyclerView. It is like the main responsible class to bind the views and display it.

Most of the tasks happen inside the adapter class of the recyclerView.

2. ViewHolder

ViewHolder is a type of a helper class that helps us to draw the UI for individual items that we want to draw on the screen.

All the binding of Views of the individual items happens in this class. It is a subclass of RecyclerView.ViewHolder class.

3. LayoutManager

LayoutManager in recyclerView helps us to figure out how we need to display the items on the screen. It can be linearly or in a grid. RecyclerView provides by default a few implementations of layoutManager out of the box.

It is like the governing body of recyclerView which tells the recyclerView’s adapter when to create a new view.

The Benefits of RecyclerView

The greatest benefit of RecyclerView is that it is very efficient for large lists:

  • By default, RecyclerView only does work to process or draw items that are currently visible on the screen. For example, if our list has a thousand elements but only 10 elements are visible, RecyclerView does only enough work to draw 10 items on the screen. When the user scrolls, RecyclerView figures out what new items should be on the screen and does just enough work to display those items.
  • When an item scrolls off the screen, the item’s views are recycled. That means the item is filled with new content that scrolls onto the screen. This RecyclerView behavior saves a lot of processing time and helps lists scroll fluidly.
  • When an item changes, instead of redrawing the entire list, RecyclerView can update that one item. This is a huge efficiency gain when displaying lists of complex items!

In the sequence shown below, we can see that one view has been filled with data, ABC. After that view scrolls off the screen, RecyclerView reuses the view for new data, XYZ.

RecyclerView Used Patterns

RecyclerView uses Adapter pattern to display complex lists in the UI Screen after transform app data.

If we ever travel between countries that use different electric sockets, we probably know how we can plug your devices into outlets by using an adapter. The adapter lets you convert one type of plug to another, which is really converting one interface into another.

The adapter pattern in software engineering helps an object to work with another API. RecyclerView uses an adapter to transform app data into something the RecyclerView can display, without changing how the app stores and processes the data.

For the sleep-tracker app, we build an adapter that adapts data from the Room database into something that RecyclerView knows how to display, without changing the ViewModel.

How it actually works?

So, now we are going to discuss how the recyclerView actually works. When we talk about recyclerView, you would always hear someone saying that it recycles the views. But what does it actually mean?

So, let’s say when we are scrolling the list which has 50 items in the collection and we show only 5 items at once in the list.

Here, item 1 to item 5 is the ones that are visible on the screen. item x is the one that will be loaded next on the screen when we scroll up. All the items here have their own instance of ViewHolder and the ViewHolder here is helpful for caching the specific item’s view.

This is how recycling of views happens in recyclerView which is one of the main reasons for the better improvement of recyclerView. In this process, the views of the item are reused to draw new items on the screen.

Similarly, if we have multiple view types, let’s say ViewType1 and ViewType2 then we would have two different collections of scrapped view of type ViewType1 and ViewType2.

And while recycling the views, the ViewType1 view will be allocated to only views of ViewType1 and ViewType2 views will be allocated to ViewType2 views.

This is how recyclerView works internally and efficiently.

The View Optimization of RecyclerView

RecyclerView optimizes the view using ViewHolders.

So, let us say we have 100 items be displayed on the list, and we want to show 5 items on the screen.

Each item here has 1 TextView and 1 ImageView in the item.

So, to map each view using findViewById is always an expensive task and just imagine the number of findViewByIds we might need to map all the TextViews and ImageViews of 100 items i.e 200 findViewByIds.

So, when we are using RecyclerView, then only 6 items are created initially with 5 loaded at once to be displayed on-screen and one is the one to be loaded.

Now, if we scroll the list then we have 7 viewHolders. One each for scrapped view and to be loaded view and 5 for the ones which are displayed.

So, at a time, maximum findViewByIds that we are using are only 14 as we have a maximum of 7 ViewHolders.

Because of ViewHolders and recycling of views, we have got the performance improvement in RecyclerViews.

That’s all about in this article.

Conclusion

In this article, We understood how recyclerView actually works in the Android system. This article demonstrates RecyclerView Concepts, Building Blocks , Benefits, Used Patterns, Internal working process and the reasons behind view optimization and performance improvement in RecyclerView.

Thanks for reading ! I hope you enjoyed and learned about Android RecyclerView Concepts. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Android – How To Secure API Keys Using Android NDK ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article.

In this article, we will learn about how to secure API Keys using the Android Native Development Kit. We will focus the below points to understand the API Keys Security Concepts in Android NDK:

  • What is the current problem during secure API Keys?
  • What is the proposed solution to secure the API Keys?
  • How to do this in Android?

A famous quote about learning is :

The more that you read, the more things you will know. The more that you learn, the more places you’ll go.

So Let’s begin one by one.

Overview

What is the current problem during secure API Keys?

Here First question, What is the current problem during secure API Keys?

The Answer is :

While developing Android applications, we use various third-parties libraries that make the development of our application fast. In these libraries, we just call some functions according to our need and we don’t know the code of these functions and we don’t care about that. But to call these functions, we need API keys that are different for different users. Some of these libraries are paid and if somehow, someone gets our API key then we might land to high payment bills and many other problems. During the starting days to Android development, we put our API keys either in strings.xml file or in gradle file.

strings.xml file

Following is an example of storing an API key in strings.xml file:

<resources>
    <string name="app_name">SecureAPI</string>
    <string name="MyAPIKey">YOUR_API_KEY_HERE</string>
</resources>

The problem with approach is that anyone can get the API key by reverse engineering.

gradle file

Another approach that was used is the gradle file approach. Here we add the API key in the gradle.properties file:

#gradle.properties file

#API Key
APIKey = "YOUR_API_KEY_HERE"

After that, import the API key as buildConfigField in the build.gradle file.

buildTypes {
    debug {
        buildConfigField 'String', "ApiKey", MyAPIKey
        resValue 'string', "api_key", MyAPIKey
    }
    ...
}

But still anyone can get the API key by reverse engineering your code. So, both methods failed to secure the API keys. We need a certain concrete method that can be used so that even after reverse-engineering the code, no one can get the desired API key. 

Cool !! So We understood the problem of secure API keys in Android development.

What is the proposed solution to secure the API Keys ?

So the next question is, What is the proposed solution to secure the API Keys ? And what should we do so that even after reverse engineering no one can get the API key ?

The Answer is :

One solution to the above problem can be the use of native language in our application code. In the native languages like in C or C++, the Android Native Development Kit(NDK) compiles the code to .so file. The benefit with this .so file is that it contains binary numbers i.e. in the form of 0s and 1s. So, even after reverse engineering, we will get 0s and 1s and it is very difficult to identify what is written in the form of 0s and 1s.

Great !!

There are methods to get the code from 0s and 1s also, but as I said earlier, we are just providing some extra security layers to our code.

How to do this in Android ?

So next, we will discuss that How to do this in Android ?

The Answer is :

In Android, we have the support of Native languages with the help of the Android Native Development Kit (NDK). Also, there is JNI (Java Native Interface) in Android. JNI defines a way for the byte code that is generated from the Java or Kotlin code to interact with the native code i.e. code written in C or C++.

Three Approaches to secure our API keys

So, with the help of Android NDK, we can secure the API keys. Based on the versions of Android Studio, we have three approaches to secure our API keys using :

  • The Native C++ template
  • CMake
  • ndk-build

But before moving on to these approaches, there are some prerequisites. So, before moving onto that, we have to download some tools. Follow the below steps:

  1. In Android Studio, click on Tools > SDK Manager > SDK Tools.
  2. Select LLBDNDK, and CMake.
  3. Click on Apply and after downloading and installing click on OK.

  • LLBD: It is used by Android Studio to debug the native code present in the project.
  • NDK: Native Development Kit(NDK) is used to code in C and C++ i.e. native languages for Android.
  • CMake: It is an open-source system that manages the build process in an operating system and a compiler-independent manner.

Now, we have done with downloading the tools, let’s quickly move on to the approaches of securing the API keys.

1. The Native C++ template

In the latest versions of Android Studio, we have support for native code i.e. for the C and C++. 

We can find that by default we will be having native-lib.cpp file and the CMakeLists.txt file added to our project under the cpp directory. The native-lib.cpp file is the file that contains our API keys. We can add our API keys in the file as below:

#include <jni.h>
#include <string>

extern "C" JNIEXPORT jstring JNICALL
Java_com_coolmonktechie_myapplication_APIKeyLibrary_getAPIKey(JNIEnv* env, jobject /* this */) {
    std::string api_key = "YOUR_API_KEY_GOES_HERE";
    return env->NewStringUTF(api_key.c_str());
}

Following is the description of the above code:

  • Here, we have to follow the combination of PackageName_ActivityName_MethodName.
  • In the above example, com_coolmonktechie_myapplication is the package name, APIKeyLibrary is the file name and getAPIKey is the method that is used to get the API keys from the native code.
  • We can directly return the API key but normally people use some encryption technique to encrypt the API key. So, the NewStringUTF() method is used to do the UTF-8 encoding.

Now, to use our API key in the Activity or in any file, go to the Activity or the file where we want to use our API keys. To load the native code that we have written, we need to call the System.loadLibrary(“native-lib”) method in the init block.

init {
        System.loadLibrary("native-lib")
}

Now, declare a Kotlin external function with the same name as used in the native code.

external fun getAPIKey(): String

Finally, we can get the API key by calling:

APIKeyLibrary.getAPIKey()

That’s all! We have secured our API key.

2. CMake

Apart from using the Native C++ template, we can use the CMake to secure the API keys.

CMake is used to control the software compilation process using simple platform and compiler independent configuration files, and generate native makefiles and workspaces that can be used in the compiler environment of our choice.

After installing the required tools, Under the app/src/main directory, create a directory named cpp. In the cpp directory, create a native file where we want to store our API keys. So, create a file named api-keys.cpp and add the below code:

#include <jni.h>
#include <string>

extern "C" JNIEXPORT jstring JNICALL
Java_com_coolmonktechie_myapplication_APIKeyLibrary_getAPIKey(JNIEnv* env, jobject /* this */) {
    std::string api_key = "YOUR_API_KEY_GOES_HERE";
    return env->NewStringUTF(api_key.c_str());
}

In the app/ directory, we need to add one text file named CMakeLists.txt file. It is a CMake build script. Add the below content into it:

# For more information about using CMake with Android Studio, read the
# documentation: https://d.android.com/studio/projects/add-native-code.html

# Sets the minimum version of CMake required to build the native library.

cmake_minimum_required(VERSION 3.4.1)

# Creates and names a library, sets it as either STATIC
# or SHARED, and provides the relative paths to its source code.
# We can define multiple libraries, and CMake builds them for us.
# Gradle automatically packages shared libraries with our APK.

add_library( # Sets the name of the library.
api-keys

# Sets the library as a shared library.
        SHARED

# Provides a relative path to our source file(s).
src/main/cpp/api-keys.cpp )

# Searches for a specified prebuilt library and stores the path as a
# variable. Because CMake includes system libraries in the search path by
# default, we only need to specify the name of the public NDK library
# we want to add. CMake verifies that the library exists before
# completing its build.

find_library( # Sets the name of the path variable.
log-lib

# Specifies the name of the NDK library that
# we want CMake to locate.
        log )

# Specifies libraries CMake should link to our target library. We
# can link multiple libraries, such as libraries we define in this
# build script, prebuilt third-party libraries, or system libraries.

target_link_libraries( # Specifies the target library.
native-lib

# Links the target library to the log library
# included in the NDK.
        ${log-lib} )

Now, We have to specify the path of our CMakeLists file in the build.gradle file. So, add the below code in build.gradle file:

android {
    ...
    defaultConfig {
        ...
    }
    buildTypes {
        ...
    }
    externalNativeBuild {
        cmake {
            path 'CMakeLists.txt'
        }
    }
}

Now, to access the API keys from our Activity or file.

3. ndk-build

To compile the native code present in the project, Android Studio supports the ndk-build. Here, we will be having an Android.mk build file that is used by ndk-build.

The Android.mk file is present inside the jni/ directory. It describes our sources and shared libraries to the build system. The basic purpose of the Android.mk file is to define project-wide settings that are not defined by the build system or by Application.mk or by environment variables. Also, the syntax of the Android.mk file allows us to group our sources into modules.

To use ndk-build, Under the app/src/main directory, create a directory named jni. Here we will be having our .mk files and the native code file. In the jni directory that we have created in the previous step, add one file named Android.mk and add the below lines of code to it:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := api-keys
LOCAL_SRC_FILES := api-keys.c

include $(BUILD_SHARED_LIBRARY)

Following is the description of the above code:

  • The LOCAL_PATH variable indicates the location of the source file. my-dir is a macro function provided by the build system to return the current directory.
  • The CLEAR_VARS is used to clear many LOCAL_XXX variables for us like LOCAL_MODULE, LOCAL_SRC_FILES, etc. It doesn’t clear LOCAL_PATH.
  • The LOCAL_MODULE variable stores the name of the module that we want to build. The module name must be unique and we shouldn’t use any space in the module name.
  • The LOCAL_SRC_FILES variable contains a list of C or C++ files that are present in the module.
  • The BUILD_SHARED_LIBRARY variable is used to tie everything together. It determines what to build, and how to do it. It collects the information that we defined in LOCAL_XXX variables since the most recent include.

In the jni directory, create another file named Application.mk file and add the below code:

APP_ABI := all

The Application.mk file is used to specify the project-wide settings for the ndk-build.

The variable APP_ABI is used to specify the ABIs whose code should be generated by the build system. By default, the build system generates the code for all non-deprecated ABIs.

The last file to be added in the jni directory is our native code file. So, in the jni directory, add one file named api-keys.c and add the below code into it:

#include <jni.h>

//For first API key
JNIEXPORT jstring JNICALL
Java_com_coolmonktechie_myapplication_APIKeyLibrary_getAPIKey(JNIEnv *env, jobject instance) {

    return (*env)->  NewStringUTF(env, "YOUR_API_GOES_HERE");

}

After adding the required files in your jni directory, our next aim is to provide the path of our Android.mk file in the build.gradle file.

android {
    ...
    defaultConfig {
        ...
    }
    buildTypes {
        ...
    }
    externalNativeBuild {
        ndkBuild {
            path 'src/main/jni/Android.mk'
        }
    }
}

Now, to access the API keys from your Activity or file.

That’s all about in this article.

Conclusion

In this article, We understood how to secure our API keys with the help of the Android Native Development Kit. We saw three methods of doing so i.e. the ndk-build method, the CMake method and the easiest one i.e. using the native c++ template in our Application project..

Thanks for reading ! I hope you enjoyed and learned about Android Secure API Keys Concepts and Methods. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Exit mobile version