Basic literacy that high-end front-end programmers should have

I have written several articles before on how to write maintainable projects (a little experience in building large front-end business projects, writing maintainable modern front-end projects, taking over new front-end projects? Here are some points you may want to pay attention to), look at it recently Many companies have laid off staff and suddenly woke up. I used to think about the problem from the perspective of the project, but not from the programmers themselves, which almost made a big mistake. If everyone can maintain the project in an orderly manner, no matter who We can all understand and take over quickly, so where is our competitiveness? At this time, I looked at the code in the project that I scolded every day, and suddenly my heart was filled with admiration. It turned out that Shishan is the thing that can really protect us. How can the years be quiet, it's just that someone walks forward with shit for you.
In order to let more people realize this, from the perspective of the front end, I decided to write this article after carefully reading the hidden secret codes in the project, because my skill is still shallow, and I have been walking in the past. It is on the wrong road, so this article may be a bit tricky in the eyes of real masters, so I am ugly here🐶
With TypeScript, but not entirely
TypeScript is very popular. In every team, there are always some juniors who try their best to introduce ts into the project. This behavior seriously hinders the growth rate of Shishan, but it is not easy for us to stop the same workers. But even that doesn't stop us from exercising justice
As we all know, TypeScript alias AnyScript, obviously, this is the hint that TypeScript founder Anders Hejlsberg left us, we have reason to believe that AnyScript is his real purpose
const list: any = []
const obj: any = {}
const a: any = 1

In the project that introduced ts, because type annotations are added on the basis of the original runnable code, the code volume will undoubtedly increase. According to a survey, the code volume may increase by 30%. If the purpose of AnyScript is fully utilized , which means that you can easily increase the code by 30%. Useless but not faulty code, these codes will even increase the compilation time of the project (after all, it increases the cost of ts checksum removal. )
You can not only make your own code use AnyScript, you can even give a big mouth to those third-party frameworks/libraries that support ts
export default defineComponent({
props: {
// now data is of type any
data: {
type: Number as PropType,
},
},
setup(_, { emit }) {
// Now props are of type any
const props: any = _
...
}
})

Of course, the full screen any may still be a bit obvious, so you can add specific types to some variables appropriately, but adding types does not mean that you have to use them correctly
const obj: number[] = []
// ...
// Although obj is a number[], in order to realize the business, we have to insert some types that are not number, I don't want it, right?
// As for the editor will draw a red line to report an error? That's a small problem, don't worry about it, as soon as others open this project, it will be full of red lines, and they will get excited when they think about it.
obj.push('2')
obj.push([3])

Naming should be freer
Naming has always been a problem that plagues many programmers. The reason is that we always want to find a name for the variable that can express the meaning well, so that the readability of the code is high, but now we know that this is not a problem Good thing, so we should indulge ourselves, get rid of the naming difficulty and speed up the accumulation of shit
const a1 = {}
const a2 = {}
const a3 = 2
const p = 1

I must emphasize that naming is not only variable naming, but also file name, class name, component name, etc. These are all places where we can play, such as class name






At first glance, it seems that there is nothing wrong with it, and it seems that there is something wrong with it. Are all boxes? The global search is all for you! What if some of your components accidentally don't use scoped? If you don't pay attention, you don't know what style of components you have changed. It's beautiful when you think about it.
I want to say a little more about css, given its flexibility, we can do more, there are always people who say BEM is not BEM, they dare to use us to write such code
&-card {
&-btn {
&_link {
&--right {
}
}
&-nodata {
&_link {
&--replay {
&--create {}
}
}
}
}
&-desc {}
}

Ok, now please find the style corresponding to the class name .xxx__item_current.mod-xxx__link in a few hundred lines of code (we will talk about this in the next section) in this format
code must be long
The mountain of shit must be high enough and deep enough, which requires our code to be long enough
As large as the length of a file, as small as a class, a function, or even the conditional body of an if, it is a good place for us to play freely.
What single file should be no more than 400 lines, and what one function should be no more than 100 lines, it is simply a tumor,

So this requires us to have the ability to write a hundred lines of things that can be solved by ten lines of code, preferably to give people a feeling that more is less
data === 1
?'img'
: data === 2
? 'video'
: data === 3
?'text'
: data === 4
? 'picture'
: data === 5
?'miniApp'

Ternary expressions can express logic elegantly, like poetry. Although this code seems to be a lot, there is only so much logic. I also used ternary expressions to optimize them. Can't blame me? I have never heard of map mapping enumeration optimization.
You can also choose other ideas that are easier to implement, for example, write more nonsense
if (a > 10) {
// Although the judgment of a in the following ifs is useless, who can see it if you don't look carefully? It's hard to say anything, after all, there's nothing wrong with it
// In addition, multi-level if nesting is also a little trick for stacking shit mountains. I don't quite understand what to return in advance.
if (a > 5) {
if (a > 3 && b) {

}
}
if (a > 4) {

}
}

In addition, you can also write some well-established methods, but the point is that these methods are not used at all, and there are more places for this kind of play, which is simply a weapon to expand the size of the code. It's a bug, but who would have thought it wouldn't work at all? Even if someone is skeptical, do you think he dares to delete some correct code from a business project that is running well?
Components and methods are coupled with multiple drops
In order to prevent other people from reusing my methods or components, when writing methods or components, be sure to couple as much as possible to raise the threshold of reuse
For example, for things that can be solved by passing parameters through Props, I prefer to take them from the global state, such as vuex, a unique global data. If you want to pass parameters, you have to change the store data, but you guess it will not affect when you change it. What about the normal use of a component on some other page? If you use it, then you may cause unexpected problems, if you don't use it you have to rewrite a component yourself
Components do not need to pass parameters? It doesn't matter, I directly linked the internal variables of the component to the global state. Although these internal variables are indeed only used by a certain component, there is nothing wrong with me linking to the global state, right?
Hey, there are two things that can be solved by one component. Now there are two, and there may be three in the back. Isn't the amount of code coming up?
The same is true for methods. It is obvious that parameters can be extracted. Following the concept of functional programming, I prefer to associate with external variables.
// First of all, this naming fits the free nomenclature mentioned above
function fn1() {
// ...
// The logic of fn1 is relatively long, and it solves a general problem,
// But myObj is an external variable, it depends on how you reuse it
window.myObj.name = 'otherName'
window.myObj.children.push({ id: window.myObj.children.length })
// ...
}

Magic strings are a good thing
In fact, according to my observation, most people prefer to write magic strings, except for some people with bad intentions, which makes me very gratified. Knowing a hardcoded string of what it represents gives a sense of security
if (a === 'prepare') {
const data = localStorage.getItem('HOME-show_guide')
// ...
} else if (a === 'head' && b === 'repeating-error') {
switch(c) {
case 'pic':
// ...
break
case 'inDrawer':
// ...
break
}
}

Based on this, we can do more, such as splicing magic strings with variables, and abolishing the global search directly when debugging
if (a === query.name + '_head') {

}

We are all Chinese, why not try Chinese characters?
if (data === 'normal') {

} else if (data === 'error') {

} else if (data === 'pass') {

}

You have to make your own wheels to be comfortable
As we all know, building a wheel can significantly improve the technical level of our programmers. In addition, because we have built the wheel ourselves, it reduces the dependence on the community, and at the same time increases the size of the project, which effectively promotes the growth process of Shishan. It can be said that It's a fish and two
For example, we may often use the method of time formatting in our projects. Most people directly introduce dayjs to finish the job, which is too superficial. We should implement it ourselves, for example, format a string format date into a timestamp
function format(str1: any, str2: any) {
const num1 = new Date(str1).getTime()
const num2 = new Date(str2).getTime()
return (num2 - num1) / 1000
}

How concise and elegant, as for what format you are talking about, what is the special treatment of date strings under safari, we will talk about it when we encounter it, even if it is dayjs, it has gone through many fixes and bugs to get to today, so be more relaxed and be patient
If you think that it is difficult for you to make full use of dayjs, you can even create a vuex. The vue official website states that eventBus can act as a global state management, so we can do it ourselves, not here. For example, this is a place for free play, and it does not limit everyone's ideas.
Leverage the power of community - the wheel is still someone else's
Considering that everyone is just eating and drinking, it is a bit difficult to build wheels for everything, so we can try to go to the other extreme-everything is solved by wheels
To determine whether a variable is a string or an object, use kind-of for you; get the key of an object, use object-keys for you; get screen size, use vue-screen-size for you... etc. , I won't list them one by one, you need to find out for yourself
It doesn't matter whether the actual scene really needs these libraries, and it doesn't matter whether it is a bull's knife to kill a chicken. It would be better if you have never heard of a wheel, so that you can show that you are knowledgeable and knowledgeable. A problem-solving wheel is a good problem,
Here I have to mention lodash, which is a powerful tool to solve many problems, but don't download it wrong, it has to be the commonjs version.
import _ from 'lodash'

Try different ways to solve the same problem
There are many roads in the world, and many roads can lead to the same destination, but most people are mediocre, they only know how to follow the footsteps of their predecessors without their own thoughts, and what others say is what they say. For a high-end profession like our programmers, the disadvantages are great, and any programmer with lofty ideals should avoid it
In practice, it is trying to solve the same problem using different techniques and solutions

Make a css modular solution, what?
Why BEM, OOCSS, CSS Modules, CSS-in-JS are all introduced in the project, keeping up with the trend to expand the horizon
Vue project only uses template? I'm sorry, let's start rendering
I have read some articles on front-end dependency injection and reflection before. Although it is not suitable for most business projects, it is not a big problem. It can be run and imported.
And what about rxjs, people say it's good, although I don't know what's good, but the threshold is high and most people can't figure it out, so I have to try it
Pinia is a good thing, what, we already have vuex in our project? It's out, the official website said that vue2 can also be used, we must try it, keep up with the trend of the community, what is the fuss about having two sets of state management in one project!

Be yourself, don't mind other people's business
I read a little story, someone asked a very old grandfather what is the secret of longevity, the grandfather said that he never minds his own business
This story is also very inspiring for us programmers, write your own code, don't worry about whether others can understand it, don't worry about whether others will fall into the pit you wrote
mounted() {
setTimeout(() => {
const width = this.$refs.box.offsetWidth
const itemWidth = 50
// ...
}, 200)
}

For example, for the above code, why write a setTimeout in mounted? Why is this setTimeout time 200? It may be because the box element will return data about 200ms after being mounted and have content, so you can measure its width and perform a series of other logics. As for whether it is possible for the network and other reasons to exceed 200ms or have no content? These don't need to be concerned, you just need to ensure that 200ms is no problem when you develop;
itemWidth represents the width of another element. When you write the code, the width of this element is 50, so there is no need to measure it in real time. You just write it to death. As for whether other people will change the width of this element later, you are not allowed here. Now, this is not something you have to consider. When you develop it, there is really no problem. Other people will take care of the problems when they come up with them. What are you doing?
code self explanatory
High-end programmers often use the simplest coding method. Experts never write comments, because the code they write is self-explanatory. What is self-explanatory? That is, you look at the code just like you look at the comments, so you don't need comments
I think it makes sense. The code is sitting there, and the logic is clearly written. Why do you need to write comments? Can you just look at the code directly?
At first glance, it seems that this line is a bit hindering the process of stacking shit mountains, but it is not.
A pile of code that is destined to be iterated for countless editions, modified by countless people, and passed down for many years must have complicated logic. It is inevitable that there will be some indescribable logic that makes people inexplicable, without the bonus of comments. These logics have a high probability To become a black hole forever, everyone has to go around when they see it, which is equivalent to building an additional set of logic around these black holes. Isn’t the size and complexity of the code going up?
If you are really itchy, you can also write some comments. Here I will reveal a method that will not only make you more enjoyable to write comments, but also add strength to the pile of shit, that is: lie in the comments!
That's right, who said comments can only be written right? I don't understand enough, so is it weird that the comment is not quite right? I didn't guarantee that the comments were correct, and I didn't force you to read the comments, so when you read the comments, you were misled by the comments and wrote a bug. Why do you blame me?
// Calculate if data is available
//(Actually, the function of this method is to calculate whether data is not available)
function isDisabledData(data: any) {
// ...
}

The above example can only be said to be a small test. After all, it is easy to be found by debugging more, but even if it is found, everyone will only think that you are just a little careless ghost. How can you blame you? A little surprise from other people, besides, if someone really believes it regardless, then you will make a lot of money
The compilation problem is resolutely unchanged
In order to hinder the growth rate of Shishan, some insidious guys always want to restrict at various levels, such as adding various lints, when compiling, the command line will tell you where you are not following the rules, but the big Part of it is at the waring level, that is, you can run normally without changing the project. This is our breakthrough point.
Even if you write the code according to your ideas, don't worry about lint, and if you don't see the warning error, isn't it unusable? In this case, if someone accidentally made an error-level error, he would face the scene of finding his error from several screens of warnings, which is equivalent to having a face-to-face with Shishan in advance. hug
According to the broken window theory, this kind of behavior will affect more and more people, and everyone will tacitly regard the warning as nothing (it is too troublesome to find your own one from several screens of warnings). The so-called lint is a joke
summary
A mountain of shit that lasts for a long time must take the precipitation of time and the practice of countless people to finally take shape. This requires the efforts of all of us. Years later, when you see the mountain of shit you once participated in, it collapses and collapses. When you collapse, even if you really understand the terrifying power that our programmers control! 🐶

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00