While browsing the article I came across a narrative about itif-else语句的文章,这篇文章作者是Thai Tran,His original text was written in English,Then read the article and it's easy to understand,Try to translate it into Chinese.如有不妥还望指出.

原文链接:https://thaitran.hashnode.dev/how-to-code-like-a-pro-in-2022-and-avoid-if-else#comments-list

If you learn a programming language,我们都会知道if...else...、for循环等基本语法.

作为一个初学者,We can learn and use it according to the book.

但是,If you want to become a senior programmer,It is necessary to constantly consider how to apply programming languages ​​more efficiently.

使用if...else...It's one of the programming fundamentals we learn in college,It is often used when you are just starting out with programming.但是,Many senior developers think soif...else...存在很多问题,And we also try to avoid over-reliance during developmentif...else....

This article is about beginners、中级、How advanced programmers deal with some similar problems in programming.

怎样在2022Years to discard like a proif-else来编写代码?

使用if-elseStatements are one of the foundations of how we study programming in college,It helps us start our first mission.有趣的是,Many senior developers hate itif-else语句.只要情况允许,It should be avoided in codeif-else.

我们来看一些例子

How junior developers write code:

var input = "Dog";
var output = "";
if (input == "Dog")
{
output = "Bow Wow";
}
else if (input == "Cat")
{
output = "Meow Meow";
}
else if (input == "Chicken")
{
output = "Cluck Cluck";
}
else if (input == "Pig")
{
output = "Oink Oink";
}

这个例子中,The developer needs to output the sounds of different animals according to the input animals.这个问题可以使用If-ElseStatements easily repeat logic.

How an intermediate developer would write this code:

var input = "Dog";
var output = "";
switch (input)
{
case "Dog":
output = "Bow Wow";
break;
case "Cat":
output = "Meow Meow";
break;
case "Chicken":
output = "Cluck Cluck";
break;
case "Pig":
output = "Oink Oink";
break;
}

通过使用switch语句来代替if-elsestatement and get the same result,But this is still not the best solution.

How advanced developers write code:

var input = "Dog";
var map = new Dictionary<string, string>
{
{ "Dog", "Bow Wow" },
{ "Cat", "Meow Meow" },
{ "Chicken", "Cluck Cluck" },
{ "Pig", "Oink Oink" }
};
map.TryGetValue(input, out var output);

在这个例子中,Store the animal's name and animal sound in a dictionary as key-value pairs,并调用TryGetValue()method to get the output,Such code is more readable.

But things can get more complicated

例如,We need to use a comparison method instead of an exact match,Then take the appropriate action.If the input contains keywordsDog,Then use it to filter dog breeds.If the input contains keywordsCat,Then use it to filter cat breeds.

Available to junior developersIf-Elsestatement to solve this problem:

var input = "Dachshund Dog";
var dogBreeds = new[] { "Dachshund" };
var catBreeds = new[] { "British Shorthair" };
var result = Enumerable.Empty<string>();
if (input.Contains("Dog"))
{
result = dogBreeds.Where(b => input.Contains(b));
}
else if (input.Contains("Cat"))
{
result = catBreeds.Where(b => input.Contains(b));
}

Because he needs more conditions,He will continue to add in the codeIf-else语句.The code will become unusable and harder to read.When this code is handed over to a senior developer,Will be rewritten as follows:

var input = "Dachshund Dog";
var dogBreeds = new[] { "Dachshund" };
var catBreeds = new[] { "British Shorthair" };
var result = Enumerable.Empty<string>();
var eval = delegate (string key, string[] array)
{
if (!input.Contains(key))
return false;
result = array.Where(b => input.Contains(b));
return true;
};
var conditions = new[] {
() => eval("Dog", dogBreeds),
() => eval("Cat", catBreeds)
};
conditions.Any(c=> c());

By moving the action todelegate(这是一个关键字,After consulting many articles, I found that there is no particularly suitable Chinese translation),The same method can be reused under different conditions.将delegate存储在数组中,并使用LINQ Any()Calling these functions will give the same result.最好的部分是,Once one of the functions returns true condition,The comparison operation will exit,This will save performance.

If you are a junior developer,You should learn and use these professional skills.Next you will become a senior developer.

要记得:

If the people maintaining your code still need to constantly tweak the code,Then he'll be a violent psychopath who knows where you live.

The original sentence is:

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.

我的理解是:If one maintains your code you need to constantly rewrite the code,Then the defender will become a violent psychopath,And he may be violent to you.

That is to say, try to write as efficient as possible,Reusable,Clean and concise code,Reduce stress for subsequent maintainers.

This article is not about total rejectionif-else语句,Rather, it is to be avoided as much as possibleif-elseThe verbosity and unmaintainability brought by the statement.如果借助if-elseCan make the statement more efficient,Of course it's still in use.In general, try to make the code as reusable as possible、可维护性,Make it concise and efficient,It's not just yourself that helps,It will also make it easier, faster and more efficient for team members or other users.

公众号文章地址:https://mp.weixin.qq.com/s/wSRxHPqYqZkwtEwuX9nGOA

欢迎关注公众号:愚生浅末.

How to code like a pro in 2022 and avoid If-Else的更多相关文章

  1. Code Runner for VS Code,下载量突破 4000 万!支持超过50种语言

    大家好! 我是韩老师.还记得 6 年前的夏天,我在巨硬写着世界上最好的语言,有时也需要带着游标卡尺写着另一门语言.然而,我对这两门语言都不熟悉,如果能在 VS Code 中方便快捷地运行各种语言,how about that ...

  2. C# DistinctInstructions for use of the method

    引自:http://blog.csdn.net/shaopengfei/article/details/36426763 从C# 3.0开始提供了Distinct方法,This has a richer way to use collections ...

  3. 反汇编(Disassembler) iPhone

    What is disassembly? Disassembly is the conversion of executable binary files into assembly code,The program can then be studied.IDA Pro Adv v5.2 Directly supported since version 1 iPhone ARM Static disassembly analysis of code.IDA Pro Adv ...

  4. 免费的Visual Studio的插件

    in depth(的)研究之后(通过在google网站搜索),,我编译了15个免费Visual Studio 2005插件表..Some of these plugins will improve you(的)代码(的)质量,,Others enable you to compile(的)更快,,但 ...

  5. Lab 9-3

    Analyze the malware found in the file Lab09-03.exe using OllyDbg and IDA Pro. This malware loads thr ...

  6. Lab 7-2

    Analyze the malware found in the file Lab07-02.exe. Questions and Short Answers How does this progra ...

  7. JavaScript常用设计模式

    单例模式:Make sure the class can only be instantiated once. var obj = {} 2.函数返回值 var func = function () {return {}} var obj = func(); 3.构造函数初始 ...

  8. C++ Core Guidelines

    C++ Core Guidelines September 9, 2015 Editors: Bjarne Stroustrup Herb Sutter This document is a very ...

  9. 【Spring-web】RestTemplate源码学习

     2016-12-22   by 安静的下雪天  http://www.cnblogs.com/quiet-snowy-day/p/6210288.html 前言 在Web开发工作中,有一部分开发任务 ...

  10. Google C++ Style Guide

    Background C++ is one of the main development languages used by many of Google's open-source project ...

随机推荐

  1. 偶的《javascript框架设计》终于出版

    #cnblogs_post_body p{ text-indent:2em!important; } 历时两年多,我的书终于付梓出版了.应各方面的要求,写软文一篇,隆重介绍一下此书对各位程序员的钱途有 ...

  2. File缓存

    /**      * 保存对象      * @param ser      * @param file      * @throws IOException      */     public b ...

  3. Linux网桥设置

    1. sudo apt-get install bridge-utils   2. brctl --help Usage: brctl [commands]  commands:         ad ...

  4. JS 代码编一个倒时器

    有时候在生活中,你需要一个JavaScript倒计时时钟,而不是一个末日装置设备.不管你是否有一次约会,销售.促销.或者游戏,你可以受益于使用原生JavaScript构建一个时钟,而不是拿到一个现成的 ...

  5. Matlab中bsxfun和unique函数解析

    一.问题来源 来自于一份LSH代码,记录下来. 二.函数解析 2.1 bsxfun bsxfun是一个matlab自版本R2007a来就提供的一个函数,作用是”applies an element-b ...

  6. HAPROXY实习

    Nothing to play,简单搞定. 同一个URLCan be distributed to different backendsWEB上. STATSThe page art is also brushed out. 参考网址: http://www.cnblogs.com/kgdxpr/p/3272861.html 如果 ...

  7. Use the firmware library operationSTM32F4necessary configuration(转)

    源:Use the firmware library operationSTM32F4necessary configuration 使用STM32F4firmware library,The default crystal oscillator is 25Mhz晶振,Therefore some modifications are required.Because I haven't paid attention to this issue before,I fiddled with it for a long time,It is found that the working clock is always wrong,Check out one ...

  8. SpringCloud学习之Zuul统一异常处理及回退

    一.Filter中统一异常处理 其实在SpringCloud的Edgware SR2版本中对于ZuulFilter中的错误有统一的处理,但是在实际开发当中对于错误的响应方式,我想每个团队都有自己的处理 ...

  9. centos7 下安装mysql教程

    最近要在centos服务器上配置环境,在部署mysql的时候,碰到各种各样的问题,网上博客文章也是有各种坑,目前发现一个比较好的博客: https://blog.csdn.net/xiaomojun/ ...

  10. Git——常用场景解析

    总结:本篇文章从初识GitHub.Git,实践GitHub的五种常用场景,分别是:git for windows安装,git配置,克隆远程代码到本地,上传本地代码到远程以及Git的常用指令.相信Jam ...