📜 ⬆️ ⬇️

Write less code

Hip on Svelte after the recent release of the 3 version of the framework still takes place, as evidenced by the greatly increased community and a huge number of questions both in the official chat and in our Russian-language telegram channel. More and more developers are sneaking up or seriously looking at this technology and are thinking about using it in their new projects. For these developers and all others interested in the topic of maximally efficient code writing, Rich Harris , the author and ideologist of the framework, published an article about how Svelte helps the developer to minimize the efforts to create modern reactive web applications, which I offer the translation below.


There may be bugs in any code. Accordingly, the number of possible bugs in the application grows with the amount of code you write.


Obviously, the more code we have to write, the more time it takes. Soon, it ceases to be enough for such necessary things as optimization, adding new features to the application, well, or for walks in the open air instead of working at a laptop.


In fact, it is widely known that, with an increase in the application code base, the project development time and the number of bugs grow not even with a linear, but with a quadratic dependence. This may explain our subconscious behavior, when a pull-request for 10 lines we will easily pay such a level of attention that rarely gets to a code larger than 100 lines. And as soon as the code becomes too long, and ceases to fit on one screen, the cognitive efforts necessary for its understanding increase significantly. We are trying to rectify the situation by refactoring and adding comments - actions that almost certainly lead to even more code. This is a vicious circle.


We are all a little obsessed, right? We monitor the performance of the application, the size of the bundle and everything else that we can somehow measure, but we rarely pay attention to the amount of code we write.


Readability is important


Of course, I'm not saying that we have to use any tricky tricks to make our code as compact as possible to the detriment of readability. Also, I do not claim that reducing the lines of code is an end in itself, as this can help transform normal, readable code like this ...


for (let i = 0; i <= 100; i += 1) { if (i % 2 === 0) { console.log(`${i} — `); } } 

... into something indigestible:


 for (let i = 0; i <= 100; i += 1) if (i % 2 === 0) console.log(`${i} — `); 

I just want to convince you that it is better to give preference to languages ​​and patterns that allow us to write less code in a natural way.


Yes i'm talking about svelte


Reducing the amount of code you need to write is an obvious advantage of Svelte. To illustrate this, let's look at a very simple component implemented in React, Vue and Svelte. First, the Svelte version:


 <script> let a = 1; let b = 2; </script> <input type="number" bind:value={a}> <input type="number" bind:value={b}> <p>{a} + {b} = {a + b}</p> 

View in action


How do we do the same in React? Most likely, it will look something like this:


 import React, { useState } from 'react'; export default () => { const [a, setA] = useState(1); const [b, setB] = useState(2); function handleChangeA(event) { setA(+event.target.value); } function handleChangeB(event) { setB(+event.target.value); } return ( <div> <input type="number" value={a} onChange={handleChangeA}/> <input type="number" value={b} onChange={handleChangeB}/> <p>{a} + {b} = {a + b}</p> </div> ); }; 

And finally, in Vue:


 <template> <div> <input type="number" v-model.number="a"> <input type="number" v-model.number="b"> <p>{{a}} + {{b}} = {{a + b}}</p> </div> </template> <script> export default { data: function() { return { a: 1, b: 2 }; } }; </script> 

In other words, it takes 442 characters in React and 263 characters in Vue to achieve something that in Svelte takes 145 characters. React version is literally three times more!


I performed the character pbpaste | wc -c by copying the code to the clipboard and running the pbpaste | wc -c pbpaste | wc -c in the terminal


Such a strong difference is more likely an exception - from my experience, the React component is usually about 40% larger than its equivalent in Svelte. Let's now take a look at the features of Svelte, which allow us to express our ideas more compactly.


Top level items


In Svelte, a component can have as many top-level elements as you need. In React and Vue, a component must have a single top-level element — in the case of React, an attempt to return two top-level elements from a component function will result in a syntax error. You can use the fragment - <> - instead of <div> , but the additional level of nesting is not going anywhere.


In Vue, the markup should be placed inside the <template> element, which, in my opinion, is superfluous.


Bindings


In React, we have to independently handle input field events like <input> :


 function handleChangeA(event) { setA(+event.target.value); } 

This is not just a very boring construction that takes up space on the screen; it is also an additional part of the code where errors may appear. Conceptually, the value of the text field is tied to the value a and vice versa, but this relationship is not clearly expressed - instead, we have two closely related but physically separate code fragments (event handler and the property value={a} ). In addition, we must remember that it is necessary to force a string value to a numeric value using the + operator, otherwise 2 + 2 will be equal to 22 instead of 4 .


As in Svelte, Vue has its own way of expressing a binding - the v-model attribute, but here we must be careful and use v-model.number , despite the fact that we take the value from <input type="number"> .


State


In Svelte, the local state of the component is updated using a simple assignment operator:


 let count = 0; function increment() { count += 1; } 

In React, we use the useState hook:


 const [count, setCount] = useState(0); function increment() { setCount(count + 1); } 

There is much more extraneous noise - both code fragments express the same concept, but in the second case 60% more characters were used. Therefore, when you read such a code, you will have to make much more effort to understand the author’s intent.


Well, in Vue we have a default export containing the data function, which returns an object literal with properties corresponding to the local state of the application. I also note that you cannot just import and immediately use such things in the markup as functions from external files and child components, since you first need to 'register' them, specifying the default in certain parts of the export.


Forget the template code


These are just a few of the Svelte features that help you create UI applications with minimal effort. There are many more - for example, reactive declarations , which inherently perform the work of the useMemo , useCallback and useEffect from React functions useMemo useEffect of verbose template code (which also loads the garbage collector by creating inline functions and arrays each time the application changes state).


How? We chose a way to bypass the limitations of the runtime environment in the browser. Since Svelte is a compiler , we are not tied to JavaScript features: we can create a component development method as we like, and not adapt it to the semantics of the language. Paradoxically, but with this approach, the code becomes more idiomatic. For example, we use variables in a natural way, and not through a proxy or hook, while getting significantly more productive applications.


useful links


Documentation in Russian by Svelte 3
Textbook in Russian by Svelte 3
Examples in Russian by Svelte 3
Russian-language channel Telegram


')

Source: https://habr.com/ru/post/451366/


All Articles