When writing business code, you often have to make judgments. Do you know what is the best solution for various business scenarios?
Let’s look at the basics:
If there’s nothing else you can do
Intermediate: Switch Case, if else, polymorphic, wrapped in design mode
Depth: Clear boundaries of all judgment conditions, in an explanatory and reasonable manner
Make a ’82 cappuccino for the big boys and savor it.
The code first look
Requirements: Judge today’s work situation, current time and work progress as conditions
{period: afteroon,/ / the current time, afternoon | | nightWorkProgress: start./ / schedule: start | | end
}
Copy the code
if-else
if(period === 'afternoon') {} to workelse if(period === 'night'&& workProgress ! = ='end') {} overtimeelse{} from workCopy the code
Advantages: If else is the most common, most familiar statement to all programmers, and can contain complex conditions.
Cons: Too much logic can become very verbose and difficult to understand.
If you don’t look at the expression on duty and overtime can you quickly understand what state corresponds to off duty
switch-case
switch(period){
case 'afternoon'At work:break;
case 'night'&& workProgress: after workbreak;
case 'night'&& workProgress ! = ='end'Work overtime:break;
default: The liver is donebreak;
}
Copy the code
Advantages: a variety of parallel conditions more concise and intuitive, can jump out, better performance.
Disadvantages: Too much logic with conditions can become difficult like clogging, nesting, and non-condition expressions.
Conditions become complex, and then add a state (weekly, Tuesday, Thursday fixed overtime), but also can maintain
Operation: three yuan, short circuit operation && | |
Advantages: More concise code
Disadvantages: Overly complex ternary operations are not semantic and difficult to maintain
period === 'afternoon'? 'work' : (workProgress === 'end'? 'off' : 'overtime')
Copy the code
Same as above, can the condition be maintained when it becomes complicated, and it already takes a little time to understand this string of code…
Policy pattern/state pattern design pattern encapsulation
Advantages: easy to maintain, explanatory, polymorphic
Disadvantages: Increased code complexity, need some abstraction ability
const AllState = {
'work':onWork,
'off':endWork,
'overtime':stillWork,
}
const period = 'night';
const workProgress = 'start';
function onWork() {
return period === 'afternoon';
}
function endWork() {
return period === 'night' && workProgress === 'end';
}
function stillWork() {
return period === 'night' && workProgress === 'start';
}
function getWorkState() {
let state = "Liver is right.";
Object.keys(AllState).some((result) = >{
if(AllState[result]()){
state = result;
return true;
};
});
console.log(state);
return state;
}
const workState = getWorkState();
Copy the code
Increased code maintainability and readability, support for polymorphism, but also increased code volume and time costs
semantic
You’re a new employee, and your boss taps you on the shoulder and tells you that this is the code left by the three previous employees who left
if(state === 1) {// One gi nest giaogiao
}else if(state === 2) {// Draw a dragon on the left and a bug on the right
}else if(state === 3) {//do something}... And so onCopy the code
The quick growth tip for newcomers is to write projects with no interface documentation, no requirement prototypes, and full of such digital states
Replace judgment conditions with objects
const stateType = {
start: 1./ /
doing: 2./ /
end: 3./ / end
}
if(state === stateType['start']) {// A gigiaogiao in a gigaogiao
}else if(state === stateType['doing']) {// Draw a dragon on the left and a bug on the right
}else if(state === stateType['end']) {// do something
}
Copy the code
Don’t feel like your code is redundant if you have one more object; the key in that object is the best comment to maintain that code
Replace judgment conditions with functions
Taking an e-commerce festival as an example, girls over the age of 18 are required to enjoy greater discounts than boys
if(sex==='feMale' && age>18) {
charge = (quantity * count) - 800; // Boys get a discount of 800 yuan
}else{
charge = (quantity * count)*0.8 - 500; // Girls get 20% off and another 500 yuan off
}
Copy the code
Decomposition of conditions in the way of transformation
1. Function replaces judgment condition
function allowAge(){
return sex==='feMale' && age>18;
}
Copy the code
2. Decompose the execution function
function maleCharge(){
return (quantity * count) - 800;
}
function femaleCharge(){
return (quantity * count)*0.8 - 500;
}
Copy the code
3. Shrink to three simple yuan
charge = allowAge() ? femaleCharge() : maleCharge();
Copy the code
Execution statements are wrapped and made short and easy to understand
SAO operation
1. If a condition is not executed, return early to reduce unnecessary code
function allowAge(age){
if (age<'18') throw new Error('No adult! ');
/ / normal
}
Copy the code
2. Set parameters to default values so that undefined is not needed
function maleCharge(arg){
const count = arg || 5;
return (quantity * count) - 800;
}
/ / after optimization
function maleCharge(count = 5){
return (quantity * count) - 800;
}
Copy the code
3. Place multiple simple conditions in an array object using includes
if(fruit === 'apple'||fruit === 'banana'||fruit === 'lemon') eatFruit()
if(['apple'.'banana'.'lemon'].includes(fruit)) eatFruits()
Copy the code
4. This can be used when there are many states
Maps in ES6 allow the use of objects as keys
const period = 'night';
const workProgress = 'end';
const worklist = (a)= > {
return new Map([[{period:'morning'.workProgress:'start'= > {}, ()/ * * / work}],
[{period:'afternoon'.workProgress:'end'= > {}, ()/ * * / work}],
[{period:'night'.workProgress:'doing'= > {}, ()/ * * / overtime}],
[{period:'night'.workProgress:'start'= > {}, ()/ * * / overtime}],
[{period:'night'.workProgress:'end'= > {}, ()/ * * / work}]./ /...])}Copy the code
Multiple data can be stored using objects as keys (conditions)
function getWorkState (){
const todayWorkState = [...worklist()].filter(([key]) = >(key.period === period && key.workProgress === workProgress));
return todayWorkState[0] [1] (); }const workState = getWorkState ();
Copy the code
If you’re thinking about working overtime after reading it, then you understood!
If you feel good, please diathysilian, like, pay attention to, forward, comment, after all, to just fan