DEV Community

Hargunbeer Singh
Hargunbeer Singh

Posted on

Abstraction

What is Abstraction

Abstraction is a way to reduce complexity and and produce efficient design. It is used to hide the technical complexity behind something. Layers of abstraction means the times the complexity of the code was reduced. Levels of abstraction are relative to each other.

Advantages

  • if you have some layers of abstraction, it helps the user from writing low level code
  • when you have layers of abstraction, you do no have to care about very specific details
  • for example, javascript is a language which has multiple layers of abstraction over C. JavaScript reduces the complexity of C code, and hides all the technical complexity(at least much of it)

Example 1

Another example of layers of abstraction while dealing with users
you do not provide the user with functions and classes and they have to call them, this will just confuse the user.
A website or in other words HTML is another layer of abstraction over javascript as it hides the complexity of javascript code and just delivers the end user with the result he wants, hiding the technical complexity of the javascript code.

Example 2

code example of layer of abstraction

let input = document.querySelector('input')
let span = document.querySelector('span');
input.addEventListener('input', ()=>{
    let lettersLength = input.value.length;
    let wordsLength = input.value.split(' ').length;
    // splits the name into words and gets the length of the corresponding array

    span.innerText = `Your name has ${lettersLength} letters and ${wordsLength} words in it`;
});
Enter fullscreen mode Exit fullscreen mode

The above code has 2 layers of abstraction over it

  1. if we compare this code with low level code(for example C programming language code), this code has a layer of abstraction which hides the technical complexity of the low level code this code hides the complexity of allocating memory, the document API which we used hides the complexity of contacting to the DOM if we had written the same piece of code in C, it would have been far more complex as we will have to do memory allocation and we will have to make our own API which can contact the browser and the DOM for manipulation thus, javascript hides the technical complexity of C, thus forming a layer of abstraction
  2. if we compare the javascript code to the website render in the browser, the website render has a layer of abstraction and hides the technical complexity of the javascript code from the end user the user just inputs his name and gets the number of letters and words, which is very simple to the user the website has a layer of abstraction over javascript code as you do not have to declare variables, split the text into an array to count the number of words, etc., thus hiding the complexity of the javascript code

Discussion (0)