编码的良好习惯_如何通过良好的编码习惯使自己的未来自我成功

编码的良好习惯

Think before you code. You have the power to make your future self's life Heaven on Earth or a living hell.

在编写代码之前请三思。 您有能力使自己未来的生活成为人间天堂或生活地狱。

In this article we'll explore what kinds of things you can do to make it a little easier on your future self.

在本文中,我们将探索可以做些什么,使自己将来的生活更轻松一些。

回顾“现有技术” (Revisiting "prior art")

We've all been there. Six months into a project, you're trying to squash a bug, and what you find is shocking. You might be asking yourself, "who would write this kind of code?"

我们都去过那里。 进入项目六个月后,您正试图解决一个错误,并且发现的结果令人震惊。 您可能会问自己:“谁会编写这种代码?”

So you dig through your git commit history using git log -p filename.js showing changes for a specific file, trying to see who would come up with something like that. And then your heart drops – you're the one who wrote it!

因此,您可以使用git log -p filename.js浏览git提交历史记录,以显示特定文件的更改,并尝试查看谁会提出类似的建议。 然后你的心就掉下来了–你就是写它的人!

This is a common scenario for any developer, experienced or new. If you haven't hit that scenario, I promise if you stick with coding long enough, you will.

对于任何经验丰富的新手开发人员来说,这都是常见的情况。 如果您还没有遇到这种情况,我保证如果您坚持编码足够长的时间,您会的。

更加意识到我们的编码习惯 (Becoming more conscious about our coding habits)

That six month reflection point is inevitable. That's a lot of time which you've most likely been using to work on other parts of the project or another project completely. Chances are, you've leveled up which has changed the way you write code.

那六个月的反思点是不可避免的。 您很可能会花费大量时间在项目的其他部分或完全在另一个项目上工作。 您可能已经升级,这改变了您编写代码的方式。

On the other hand, sometimes it takes stepping outside of the code to see the bigger picture and get a better look at how all the pieces fit together. We can naturally dig ourselves too deep into a solution and can become a little narrowly focused as we work to solve those challenges.

另一方面,有时需要走出代码之外才能看到更大的画面并更好地了解所有部分如何组合在一起。 我们自然可以将自己深深地深入到解决方案中,并且在我们努力解决这些挑战时可以变得有点狭focused。

But either way, while part of the code journey will simply be gaining more experience and learning more about your craft, there are other small habits you can get used to early on that will help you down the road.

但是,无论哪种方式,虽然一部分代码之旅将只是获得更多经验并进一步了解您的手艺,但您还可以早日习惯于其他一些小习惯,这将对您有所帮助。

So let's jump in.

因此,让我们进入。

提高代码的可读性 (Improving the readability of your code)

挑战是什么? (What is the challenge?)

Part of the fun about our craft is there are a ton of ways you can do the same thing. Think an if statement is too many lines? Well we can write it ternary style!

关于我们的手艺的部分乐趣在于您可以做很多事情来做同样的事情。 认为if语句行太多? 好吧,我们可以写成三元样式!

// Example ternary statement
const isFreezing = temperature <= 32 ? true : false;

But sometimes this takes a toll on the readability of your code. While it might seem like it looks nice and super clean on one line, imagine that as that ternary gets more complex, someone will have to spend more time understanding what it means.

但这有时会损害代码的可读性。 尽管看起来似乎很不错,而且很干净,但是想像一下,随着三元数变得越来越复杂,某人将不得不花费更多的时间来理解它的含义。

const minutes = 30;
const cookie = {
  color: 'black'
};

const cookieStatus = minutes > 20 ? cookie.color === 'black' ? 'burned' : 'done' : 'not done';

我们能做得更好吗? (What can we do better?)

Now I would imagine most of us can figure out what cookieStatus is in this example (spoilers: burned). But think about the time you spent figuring it out. Whether an extra 1s or 2s, it forces you to spend additional cognitive energy to read through the code.

现在,我可以想象我们大多数人都能弄清楚本示例中的cookieStatus是什么(破坏者: burned )。 但是请考虑一下您花费的时间来解决它。 无论是额外的1s还是2s,它都会迫使您花费更多的认知能力来阅读代码。

On the other hand:

另一方面:

const minutes = 30;
const cookie = {
  color: 'black'
};
let cookieStatus;

if ( minutes <= 20 ) {
  cookieStatus = 'not done';
} else if ( cookie.color === 'black' ) {
  cookieStatus = 'burned';
} else {
  cookieStatus = 'done';
}

No, it may not be as clean or clever as the 1-line ternary statement, but the next time you visit it, the less you'll have to think about what the answer is.

不,它可能不像一行三元声明那么干净或聪明,但是下次访问它时,您不必再多想什么答案。

It's also going to make it that much easier for bugs to creep up and get past your code reviewers when all of your code changes are in a 1-line git diff.

当所有代码更改都在1行git diff中时,这也将使错误更容易蔓延并通过代码检查器。

And yes, this is a simple example. But imagine this in a real world scenario with important business logic where you could run into these situations frequently.  

是的,这是一个简单的例子。 但是,在具有重要业务逻辑的现实场景中想象一下,您可能经常遇到这些情况。

Say you need to add another condition – that ternary is just going to keep getting more complex! You're just making it more difficult to debug or extend, where the if statements can continue on in an easily readable way.

假设您需要添加另一个条件–三元态将变得越来越复杂! 您使调试或扩展变得更加困难,而if语句可以以易于阅读的方式继续进行。

For what it's worth, ternaries and other shortcuts can be simple and effective in code, but don't abuse that effectiveness and end up making things more difficult.

值得一提的是,三元代码和其他快捷方式在代码中既简单又有效,但不要滥用这种有效性,而最终会使事情变得更加困难。

保持一致 (Keeping things consistent)

挑战是什么? (What is the challenge?)

We all have our favorite way to code. Though I'd argue not including a semicolon at the end of your JavaScript is just completely wrong, you might prefer to write your code the wrong way without them.

我们都有最喜欢的编码方式。 尽管我认为在JavaScript末尾不包含分号是完全错误的,但是您可能更喜欢在没有它们的情况下以错误的方式编写代码。

// Jim's code style

function MyComponent() {
  function handleOnClick() {
    alert('Click!')
  }
  return (
    <button onClick={handleOnClick}>My Button</button>
  )
}

// Creed's code style

const MyComponent = () => <button onClick={() => alert('Click!')}>My Button</button>;

But it's not always about what you prefer. When working with a team, chances are, everyone's opinion on how code should look is slightly different. You might agree about the semi-colon, but disagree about whitespace.

但这并不总是关于喜欢什么。 与团队合作时,每个人对代码外观的看法都有所不同。 您可能对分号表示同意,但对空白表示不同意。

And no one is wrong (except for the non-semi-coloners)! There are valid arguments to most code styles, whether for or against, but the solution isn't for everyone to write their code their own way.

没有人是错的(非半殖民者除外)! 大多数代码样式​​都有有效的论据,无论是赞成还是反对,但是解决方案并不是让每个人都以自己的方式编写代码。

我们能做得更好吗? (What can we do better?)

Keeping code consistent is important to maintain code health. A typical goal is to "make the codebase look like one person wrote it."

保持代码的一致性对于保持代码的健康状况很重要。 一个典型的目标是“使代码库看起来像一个人编写的代码”。

The point isn't that one person gets their way, it's that the team came to a conclusion about a set of rules they would use that everyone would follow. Having this consistency provides less cognitive overhead as people work through the code. It gives everyone the ability to know what to expect when reading the code.

关键不是一个人走上正轨,而是团队得出了他们将使用的一组规则的结论,每个人都会遵循这些规则。 当人们遍历代码时,具有这种一致性可以减少认知开销。 它使每个人都能够了解阅读代码时的期望。

And achieving this doesn't need to be hard. There are tools that can simply check for these inconsistencies like Eslint for Javascript. And even better, there is another level of tools like Prettier that will fix it for you!

实现这一目标并不需要困难。 有一些工具可以简单地检查这些不一致情况,例如Eslint for Javascript。 甚至更好的是,还有其他级别的工具(例如Prettier) 可以为您解决

注释您的代码 (Commenting your code)

挑战是什么? (What is the challenge?)

Keeping up with commenting your code is an important way to put context to complex logic. As much as we all want our code to be self-documenting, that's rarely the case.

跟上注释代码是将上下文置于复杂逻辑中的重要方法。 尽管我们所有人都希望我们的代码能够自我记录,但事实并非如此。

Too often we find ourselves dealing with a block of code that just doesn't make sense. And even if it makes sense on its own, we might not be able to figure out how it fits in to the rest of the application.

我们经常发现自己正在处理毫无意义的代码块。 即使它本身有意义,我们也可能无法弄清楚它如何适合应用程序的其余部分。

我们能做得更好吗? (What can we do better?)

By providing a good set of comments, you're setting up the next person who touches that code to have a better understanding of what the code is doing before they make a change.

通过提供一组好的注释,您可以设置下一个接触该代码的人员,以便在他们进行更改之前更好地了解该代码在做什么。

// DONT CHANGE - WILL STOP MAKING MONEY

const shouldMakeMoney = true;

function makeMoney() {
  if ( shouldMakeMoney ) {
    return noMoney;
  }
  return moreMoney;
}

While this is a silly example, it brings up a real world case. Businesses are increasingly dependent on being able to maintain a reliable website to make money. Whether this is as an ecommerce business or an ad giant, these websites rely on business logic that determine things like cost, taxes, discounts, and other math related things we tend to not want to think about, but could make or break a business on the internet.

尽管这是一个愚蠢的例子,但它提出了一个现实世界的案例。 企业越来越依赖能够维护可靠的网站来赚钱。 无论是作为电子商务企业还是作为广告巨人,这些网站都依赖于业务逻辑,这些逻辑确定诸如成本,税金,折扣以及我们通常不希望考虑的其他与数学相关的事物,但这些业务可能会成败互联网。

But it's not all about the company you work for. Touching old code can be scary. It's even scarier when no one on your team was around when it was written, so no one knows what it does!

但这不关乎您所工作的公司。 触摸旧代码可能会令人恐惧。 当您的团队中没有人在写本书时,这甚至更可怕,所以没人知道它在做什么!

While you might not be the next person who touches that code, try to help out your future friend who's tackling the next ticket involving that code. Because there's also a good chance you will be that person and you'll wish you remembered how it worked.

虽然您可能不是下一个接触该代码的人,但请尝试帮助您的未来朋友,以解决涉及该代码的下一张票。 因为您很有可能会成为那个人,并且希望您记得它是如何工作的。

记录解决方案 (Documenting your solutions)

挑战是什么? (What is the challenge?)

Documentation is similar to commenting your code, but from a different perspective. Documentation and commenting are both about finding ways to describe a solution in a human-readable way that will ultimately give more context. But documentation is more about the overall solution rather than the implementation details.

文档与注释您的代码相似,但是从不同的角度来看。 文档和评论都是关于寻找一种以人类可读的方式描述解决方案的方法,最终将提供更多的上下文。 但是文档更多地是关于整体解决方案,而不是实现细节。

Having a high performing application is everyone's goal. But how did we get there? There's a realistic chance that someone will have to be working on the same project you are like onboarding a new team member. How will they be able to maintain that high performance if they don't know how it works?

拥有高性能的应用程序是每个人的目标。 但是我们如何到达那里? 一个现实的机会是,某人必须像加入新团队成员一样从事同一项目。 如果他们不知道如何运作,他们将如何保持这种高性能?

我们能做得更好吗? (What can we do better?)

Whether it's introducing that new team member to the project or trying to share knowledge with another project team, documentation is an important part of maintaining a project. It helps keep everyone on the same page so we all confidently know what we're working towards.

无论是将新团队成员介绍到项目中,还是试图与另一个项目团队共享知识,文档都是维护项目的重要组成部分。 它有助于使每个人都在同一页面上,因此我们都可以自信地知道我们正在努力。

For example, if we're still working with our ecommerce project with our business logic, there will be rules that the code needs to implement. While commenting might give details inline about how the rules were implemented, the documentation would define those rules.

例如,如果我们仍在使用我们的业务逻辑处理电子商务项目,那么将需要规则来实现代码。 尽管评论可能会内嵌有关规则如何实现的详细信息,但文档将定义这些规则。

/**
 * DOCUMENTATION
 * Order Total >= 25: Discount %10
 * Order Total >= 50: Discount %15
 * Order Total >= 100: Discount %20
 * Order Total >= 75: Free Shipping
 */

const orderSubTotal = 84.00;
let orderTotal = orderSubTotal;

// If the order total is under 75, apply shipping discount

if ( orderTotal < 75 ) {
  orderTotal = addShipping(orderTotal);
}

// If the order total reaches a threshold, apply given discount

if ( orderTotal >= 100) {
  orderTotal = applyDiscount(orderTotal, .2);
} else if ( orderTotal >= 50 ) {
  orderTotal = applyDiscount(orderTotal, .15);
} else if ( orderTotal >= 25 ) {
  orderTotal = applyDiscount(orderTotal, .1);
}

This is a minimal example, but we can see the difference between the rules at the top and how we apply them. The documentation should clearly explain what the rules are, but it shouldn't care about how those rules were implemented.

这是一个最小的示例,但是我们可以看到顶部规则与我们如何应用它们之间的差异。 该文档应该清楚地解释什么是规则,但不必在乎这些规则是如何实现的。

On the other hand, the comments might not care about what the rules are, but need to implement them in an efficient and logical way. We should be able to update the code with the business rules, such as changing the top level discount tier from $100 to $80, without having to rework the code.

另一方面,评论可能不在乎规则是什么,而是需要以有效且合乎逻辑的方式来实施它们。 我们应该能够使用业务规则来更新代码,例如将顶级折扣级别从$ 100更改为$ 80,而无需重新编写代码。

But documentation is much more than business rules – it's providing a way for anyone to understand your work from a higher level. This could include anything from architectural diagrams to the theory behind your core algorithm.

但是文档不仅仅是业务规则-它为任何人提供了一种从更高层次理解您的工作的方式。 这可能包括从架构图到核心算法背后的理论的所有内容。

While maybe code isn't the best place for details like this to live, it's really important information that can help instill confidence in your project and give others an opportunity to understand more about the work.

尽管也许代码并不是实现此类细节的最佳场所,但它确实是重要的信息,可以帮助您增强对项目的信心,并为其他人提供更多了解工作的机会。

创建有效的拉取请求 (Creating effective Pull Requests)

挑战是什么? (What is the challenge?)

Pull requests (or merge requests) are a core part of any development team's project lifecycle. It provides a way to package and present your code in a consumable way for your peers to review and understand your work.

拉取请求(或合并请求)是任何开发团队项目生命周期的核心部分。 它提供了一种以可消耗的方式打包和展示您的代码的方法,供您的同行查看和理解您的工作。

There's a lot that can go into a pull request from a single commit to the entirety of the next version of your website. That's a lot of context to expect someone to understand by reading through the commits alone.

从一次提交到下一个网站的整个版本的拉取请求中有很多内容。 期望有人仅通过阅读提交就能理解这是一个很大的背景。

我们能做得更好吗? (What can we do better?)

Pull requests don't need to be an art. There should be one primary goal of the preparation you put into it – providing context into your changes. At a minimum, it should answer the questions of "what" and "why".

拉取请求不必是一门艺术。 您进行准备的首要目的之一就是为变更提供背景信息。 它至少应回答“什么”和“为什么”的问题。

We can even use tools like pull request templates to push us in the right direction. Define an outline of what you want explained and chances are, people will follow that outline. This helps avoid the 1-line "closes [ticket]" description or even worse, an empty description.

我们甚至可以使用拉取请求模板之类的工具将我们推向正确的方向。 定义要解释的内容和机会的轮廓,人们将遵循该轮廓。 这有助于避免出现1行“ closes [ticket]”说明,甚至更糟的是避免使用空说明。

With my projects, I hope to have a few questions answered before I dive into a code review:

在我的项目中,希望在我进入代码审查之前能回答一些问题:

  • What is the change?

    有什么变化?
  • What does it impact?

    有什么影响?
  • How do I reproduce or test the change?

    如何复制或测试更改?

Just a few details around the change set can provide much needed context for those reviewing your code. It's easy to look at code, but it's harder to understand it without knowing how it fits into the bigger picture.

围绕变更集的一些详细信息可以为审查您的代码的人员提供急需的上下文。 看代码很容易,但是如果不知道它如何适应更大的画面就很难理解它。

通过测试强化代码 (Hardening your code with tests)

挑战是什么? (What is the challenge?)

Tests are a way to ensure your code runs the same way each time. Being able to prove that the same input will always have the same output will help provide you and your team with a higher level of confidence that your application won't come crashing down with the next small change.

测试是确保您的代码每次都以相同方式运行的一种方式。 能够证明相同的输入将始终具有相同的输出将有助于为您和您的团队提供更高的置信度,使您的应用程序不会因下一个小更改而崩溃。

Without them, we're left with human error, where no matter how good your QA Engineer is (shoutout to my testers out there), something will always slip through. And that's not to say your tests will always catch every problem, but we can use the tools available to help prevent it.

没有他们,我们将留给人为错误,无论您的QA工程师多么出色(向我的测试人员大喊大叫),总会漏掉一些东西。 这并不是说您的测试将始终解决所有问题,但是我们可以使用可用的工具来帮助防止它。

我们能做得更好吗? (What can we do better?)

Where comments are a way of providing the context of how something works, test are a way to ensure they work. Providing test cases that are repeatable helps enforce that.

评论是提供工作原理的一种方式,而测试是确保其工作的一种方式。 提供可重复的测试用例有助于实施。

function applyDiscount(value, discount) {
  const discountAmount = value * discount;
  return value - discountAmount;
}

expect(applyDiscount(10, .1)).toEqual(.9);
expect(applyDiscount(532151235, .1054)).toEqual(476062494.831);

If I fudge the math on our applyDiscount function above, there's a high probability that the test would fail (never say never).

如果我对上面的applyDiscount函数进行数学运算,则测试很可能失败(永远不会说永远)。

But testing doesn't need to be hard. There are many tools out there that help from different perspectives. For example, you might use Jest to run your unit tests or add Enzyme on top to test your React components. But you can also bring in Cypress as an integration test solution that will work like a robot clicking through your application to make sure all the components actually work together.

但是测试并不需要很困难。 有许多工具可以从不同角度提供帮助。 例如,您可以使用Jest运行单元测试,或者在顶部添加来测试React组件。 但是您也可以引入赛普拉斯作为集成测试解决方案,该解决方案将像机器人一样在您的应用程序中单击以确保所有组件确实协同工作。

There's also different methodologies of testing. While you probably see most teams write their tests after they have a working solution, some people swear by test-driven development. They might write their tests first where the code has to pass the tests rather than the other way around. This is a great way to define the requirements of the code before diving right in.

还有不同的测试方法。 尽管您可能会看到大多数团队在找到可行的解决方案后才编写测试,但有些人还是坚信测试驱动的开发 。 他们可能首先在代码必须通过测试的地方编写测试,而不是相反。 这是在深入研究之前定义代码要求的好方法。

Whatever the method, capture the points that are most likely to break or the functions that add the most business value. You'll be helping to prevent a potential business loss or even simpler, a headache.

无论采用哪种方法,都要捕获最有可能断裂的点或增加最大业务价值的功能。 您将帮助防止潜在的业务损失甚至更简单的麻烦。

我们可以从中学到什么? (What can we learn from this?)

That might be a lot to digest, but they're important points to consider as you grow as a developer. Starting these habits early in your career will help you naturally build these skills and work that way by default.

这可能要消化很多,但是当您成长为开发人员时,它们是要考虑的重要点。 在职业生涯的早期就开始养成这些习惯将有助于您自然地培养这些技能,并默认情况下以这种方式工作。

And if you're late in your career, it's never too late to start. We should all want to strive to be the best developer we can be and do our best to help make our teammate's lives easier, as we're all in this together.

而且,如果您的职业生涯很晚,那么开始就永远不会太晚。 我们所有人都应该努力成为最好的开发人员,并尽我们最大的努力使我们的队友的生活更轻松,因为我们在一起。

寻找更多的东西吗? (Looking for more to learn?)

您对成长为开发者有何建议? (What’s your advice for growing as a developer?)

Share with me on Twitter!

在Twitter上与我分享!

翻译自: https://www.freecodecamp.org/news/set-future-you-up-for-success-with-good-coding-habits/

编码的良好习惯

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值