• 开源镜像
  • 开源沙龙
  • 媛宝
  • 猿帅
  • 注册
  • 登录
  • 息壤开源生活方式平台
  • 加入我们

开源日报

  • 2018年3月27日:开源日报第19期

    27 3 月, 2018

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;电报群 https://t.me/OpeningSourceOrg


    今日推荐开源项目:《Flow——针对JavaScript的静态错误检查器》

    推荐理由:Flow是一款针对JavaScript的静态错误检查器,可以在Mac OS X、Linux (64-bit)或是Windows (64-bit)中运行。

     

    Flow的优势

    • 安装便捷(在Mac OS X系统,你可以通过Homebrew或OCaml OPAM 包装安装Flow;而在Windows的安装会略微繁琐一点)
    • 使用简单
    • Flow可以把它的剖析器编译进JavaScript里
    开源项目精选:Flow——针对JavaScript的静态错误检查器
    开源项目精选:Flow——针对JavaScript的静态错误检查器

    详见官方文档:https://flow.org/en/docs/

     

    关于glow

    glow 的作用就不赘述了,今天主要说说glow 的安装与使用:

    1. 首先,你需要安装 flow( glow 是基于 flow 的)
    2. 然后,你有了两个选择:
    • 全局安装glow : yarn global add glow
    开源项目精选:Flow——针对JavaScript的静态错误检查器

    安装成功:

    • 只在你要的项目中安装glow :在项目路径下,输入 yarn add –dev glow

    安装成功会出现类似画面:

    开源项目精选:Flow——针对JavaScript的静态错误检查器
    开源项目精选:Flow——针对JavaScript的静态错误检查器
    • 然后你便可以愉快的使用glow 了,而使用也只是在flow 的基础上改为执行 glow

    测试代码:

    开源项目精选:Flow——针对JavaScript的静态错误检查器

    运行 flow :

    开源项目精选:Flow——针对JavaScript的静态错误检查器
    开源项目精选:Flow——针对JavaScript的静态错误检查器

    运行 glow :

    开源项目精选:Flow——针对JavaScript的静态错误检查器
    开源项目精选:Flow——针对JavaScript的静态错误检查器

     

    关于作者

    詹姆斯·凯尔:http://thejameskyle.com/

     


    今日推荐英文原文:《How to Hack an Engineer》作者:Nemild

    原文链接:https://www.nemil.com/musings/hack-an-engineer.html

    推荐理由:这篇文章事实上也是一个 GitHub repo,它收集了很多宝贵的资源,如果你想做一个好工程师或者黑客的话,这些宝贵的资源应该可以帮到你。

    How to Hack an Engineer


    This essay introduces a Github repo to catalog all the ways that engineering inputs can be influenced. Contributions are welcome.


    In 2015, I found myself talking to a smart entrepreneur who had just raised millions of dollars in venture capital from a prominent venture capital (VC) firm. He was flying high after getting substantial press and recruiting a number of early employees. His business also wholly depended on a popular open source project.

    As part of his strategy, the CEO gave a core open source developer in the project equity. With this, he boasted that he would get critical information sooner, influence the roadmap for his company’s benefit, and recruit developers from the project to his company.1

    I was doubtful this connection would ever be publicized by the open source developer. Would he speak glowingly about the company at a conference, despite private reservations? How would he influence the decisions of his fellow developers? Would developers early in their career follow his missives without adequate reflection?2

    Computer engineers regularly deal with exploits on their technical systems, where an external party takes advantage of a bug or vulnerability. An “exploit” or social engineering of our personal information sources — motivated parties influencing subreddits, conferences, meetups, blogs, journalists, professors, industry analysts — should be perceived similarly. As this example shows, even your peers can be influenced.

    As engineers, it’s valuable to develop the antibodies that enable us to make the best decisions — both for our teams and for our own careers — despite the desires of these motivated parties. Beyond identifying ways we can be influenced, I list out three techniques to help us make better decisions.

    The War to Influence Engineers

    This is just one example in a larger war that rages in this global era of computing: that for the hearts of engineers.

    Some of the many groups that will try to shape our views include:

    • Developer tools teams who want to sell their technology or grow their platform
    • Companies who wants to hire us
    • Open source developers who want to recruit contributors and users
    • Venture capitalists who want to fund us
    • Training programs that want to sell their courses
    • Consulting firms that want us to hire them
    • Social networks that are trying to maximize engagement, readership, and revenue

    The content they create and sponsor (press releases, meetups, blog posts, conferences, speaker talks) play a critical role in the decisions we make — from the technology we adopt to the companies we join.

    A press release indicating large traction (often with many missing numbers) may be a primary reason to join a startup. A blog post or popular talk on the latest database technology — like NoSQL — may be a reason to experiment and later switch. A college lecturer may partly be there to pitch their own company’s technology. The most upvoted Hacker News (HN) posts over a year may influence what technologies we choose to adopt. And yet, as consumers of this information, many of us don’t always critically examine the information and its source.

    In startups, bad technology choices made based on these inputs can divert the focus, putting the mission at risk. For an individual engineer, learning the wrong technology can waste our time. Joining the wrong company that sells us false promises can set our career back.

    Example: Recruiting engineers and raising venture capital in startups

    A friend in VC once laughed after seeing an article extolling how well a startup was doing. After having been pitched by that company, he knew they were struggling and the article was their way to attract investor interest and continue hiring good talent before their funding ran out. I know many people who would have taken the exact opposite impression from the post. Crucially, with the right training, it would have been possible to suss out some of the reality behind this article.3

    In a public example, Theranos popularized the idea of the pinprick blood test and had potentially huge social benefits. It must have been exciting for technical talent to join the company.

    Yet many were attracted by universally adulatory press (example) that had been shaped by a motivated management team and media organizations that uncritically covered them.4 While much has been written about investor losses, Theranos’s exceptional engineers and scientists also likely lost important years to do truly impactful work and had their resumes sullied.

    Example: Dev Tool Marketing at MongoDB

    MongoDB was one of the fastest growing NoSQL databases in the late 2000s that promised a “modern” database experience.

    In my deep dive into the early marketing strategy behind MongoDB, I pointed out issues relevant in dev tools marketing including:

    • Speakers invited to many MongoDB meetups/conferences would have their own motivations (trying to sell their consulting services, marketing for their own dev tools products)
    • Hack academies and early programmer blogs were valuable allies for pitching the MEAN stack, while not seeming like a sales pitch when seen on HN/Reddit
    • MongoDB would argue that nearly every use case should be solved with their database, without highlighting the tradeoffs in different use cases
    • College hackathons were a way to influence early developers who may not have fully understood the tradeoffs they were making

    Have your own example? Email me at example at this domain. (my public key)

    Even though I point out the issues in these case studies, I am far from a dispassionate scientist when on a mission for my team. Given that, it’s at least important to ensure that all engineers have the general tools to understand some of the messages we see. And in this era of fake news, selective facts, and troll armies, these lessons can also help us assess information far beyond engineering content.

    Hidden Influences

    Unlike previous generations of marketing, the external influences in engineering media today are often disguised.

    The purpose of a press release or a sales call is clear. When this content is used to give a talk at a conference or inspire someone else to write a blog post, they blur the line. With a powerful marketing budget or fundraise, it becomes increasingly easy to publicize and convince others with one’s message, regardless of the veracity.5

    I’ve had a personal experience with this in a different part of the world. After my engineering studies, I worked for the World Bank in Dili, East Timor. One day, we were explaining to a group of journalists6 the benefits of a project we were funding. There were many debates to be had for a thoughtful Timorese citizen7, but our focus was on how the World Bank perceived it. We predictably sent the journalists home with a press release extolling the project’s virtues.

    The next day, our press release appeared verbatim in a local Timorese newspaper with no mention that it was a press release — under the author’s byline. It made sure that the World Bank’s key points were shared. And yet it raised troubling questions for me about how Timorese citizens used media to make decisions.8

    Only later would I realize how prevalent this is around the world. In Silicon Valley, well placed friends tell me that they shudder at the information sources available to most — and how uncritically different messages are internalized. I worry especially about junior engineers (such as those in college and on r/learnprogramming) and those far from top tech centers, who may not realize how “the sausage is made.”

    Example: Microservices hype

    The engineering community has gone through large debates about the benefits of microservices. My own view is that the popularity of microservices in startups was a function of the hype and marketing spend around containerization. For example, compare a blog post on microservices at startups to Martin Fowler’s more nuanced view.

    Many of these messages come from other engineers, open source teams, or training programs who are often trusted in a way few others are. This highlights a common mistake in startup engineering, where products/techniques pitched at mid-size company CTOs appear in pre-product market fit startups regardless of their appropriateness.

    Example: Developer training programs

    Training programs aren’t immune from the desire to engage readers and maximize the distribution for their content as they seek to increase readership and attract students. Some of the teachers they work with have their own motivations to push a certain technology — and their background may not be vetted.

    Free Code Camp, a popular developer blog with 350k followers, carried a recent post that argued REST is dead and GraphQL is the future (“REST in Peace. Long Live GraphQL”). The article had been posted by the head of Free Code Camp and written by an author who was concurrently selling a GraphQL training program (my critique here).

    Reflecting back on my own early days, I worry about junior engineers who might feel like they have to learn GraphQL based on an article like this rather than realizing all the conflicts involved. An older example from them is “The Real Reason to learn the MEAN stack: Employability” — which many of my most thoughtful friends would have strenuously disagreed with. I especially worry about what content like this does in early developer communities, where there many not be enough thoughtful engineers to disagree with these viewpoints.

    Example: Content marketing in tech

    Beyond direct influence, a surprising percentage of posts on engineering social media are content marketing. These posts aim to add value — but are written for the primary purpose of helping their companies sell their product. Readers can sometimes internalize them as “journalism,” even though their objective is to make a sale, influence a mindset shift, or improve SEO.

    Union Square’s Fred Wilson notes how pervasive content marketing is in tech and encourages critical assessment of the message (emphasis added):

    So how should entrepreneurs use this knowledge that is being imparted by VCs [like myself] …? Well first and foremost, you should see it as content marketing…

    That doesn’t mean it isn’t useful or insightful. It may well be. But you should understand the business model supporting all of this free content. It is being generated to get you to come visit that VC and offer them to participate in your Seed or Series A round. That blog post that Joe claimed is not scripture in his tweet is actually an advertisement. Kind of the opposite of scripture, right?

    For all these reasons and more, my most thoughtful friends use their own networks to understand reality instead: college/graduate school friends from select universities, frank talks with portfolio CEOs (for investors), ‘off the record’ conversations with connections at the various platform providers, trenchant blogs from front line engineers. Their information sources are less influenced by self-interest, providing a more objective view of the world. People can also say things privately they wouldn’t feel comfortable sharing broadly.

    These friends of mine also have a deep-seated desire (specifically, a financial or technical motivation) to get at the truth, and so aim to understand the incentives driving every one of their sources. Though they may be outwardly agreeable, internally they’re deeply critical thinkers.

    How Engineers Can Make Better Choices

    These issues have a basic lesson: nothing is a replacement for surrounding oneself with primary sources, a community interested in the truth, and thoughtful engineers.

    I’ve created a Github repo listing a few of the oft used inputs for startup engineering decisions that I’ve seen over my own startup journey. For each, I’ve noted how they work — and how they can be exploited. Contributions are welcome.

    Beyond the self-interested factors, engineering media can be distorted for other reasons. For example, each upvote on Hacker News is equal — meaning that the world’s most thoughtful expert on a topic has the same voting power as someone inexperienced. Nearly every social media algorithm favors engagement over any other metric, meaning that what we read is simply a function of what those around us want to read (this echoes my research on what types of deaths are covered in a leading US newspaper).

    Example: Cryptocurrency tribes and social media

    In social media, the group you surround yourself by can shape your attitudes, even though engineering decisions should be based on empiricism and facts. Social media groups and algorithms pick content that confirms its users’ beliefs — and paint the opposite side in the worst light. This tribalism can be regularly seen in cryptocurrency subreddits, meaning that readers consume a distorted reality (see also filter bubbles).

    As the cofounder of Coinbase, Fred Ehrsam, explains:

    Cryptocurrencies create strong tribalism. Once you own a currency, your incentives are to make that currency go up in value. Crypto tribalism can be seen on reddit every day. Subreddits generate and report news that support their holdings. Crypto tribalism plays out in two common ways: 1) people promoting their own currency and 2) people discrediting other currencies. People promoting their own currency is evidenced by the imbalance of positive to negative news about a currency on its own subreddit.

    For now, I’ll suggest three simple points that go far in assessing engineering media:

    1. Identify incentives behind content that informs important decisions

    First, consider a writer/speaker’s motivation — both directly (an employee or investor in the company) or indirectly (a public speaker who is a consultant looking for a gig or employee looking for a job/advisorship).

    When I read a post or hear a speaker, I often ask myself a few questions:

    • Background: What is their technical background and why are they well suited to speak on this topic?
    • Objectives: What are their personal objectives in speaking/blogging? (e.g., recruiting, personal brand, new business); there almost always is one
    • Conflicts: What conflicts might they have and how does this influence the message?
    • Allies: Who else wants this content out there?
    • Distributor Incentives; Why is the distributor (social network, media publication) putting this content in front of me? (who are the upvoters, what is the business model, etc.)

    When we see a lot of press from a company, it’s often a sign that they want something from us. Their employees have consciously spent the time to sit down with a journalist or taken the time to write a post.9

    2. Debunk claims

    Second, inculcate a desire to debunk claims.

    For example, companies regularly trumpet their (tailor-made) benchmarks that show their products in the best light. It’s often not that difficult to run our own benchmarks that reflect our real world use cases.

    The direct reading of codebases is a powerful corrective (where available). It’s a primary source that doesn’t have ‘spin’ built in.

    Looking back on trends in technology and where they ended up is another approach, which is akin to backtesting10: it’s easier to tune out hype, when we think about how people in a few years may perceive it, based on things we’ve seen in the past.

    Say something in online communities when you disagree or see egregious incentive issues (here’s one favorite recent example on AV1 vs HEVC). On HN, this could be comments or a post of your own, even if it’s with a throwaway account. New social network designs might let us award karma to people who list out the key incentive issues in the future.

    3. Build a community of respected peers and thoughtful experts

    Third, examine the community that you lean on to determine important technical decisions.

    It’s important to have a community of people who benefit from the truth, think critically, and have content expertise. This could be former employees, classmates, or your coworkers. You can augment this with the most thoughtful engineers you can find. Online, you can often find some of these groups in the comments of niche HN posts and open source mailing lists/chat rooms. In your early years, finding a thoughtful mentor is critical.

    In many ways, this approach mirrors the web of trust in computer security, where we look to trusted friends — and people these trusted friends are connected to.

    This point underlines the benefits of a thoughtful engineering curriculum taught by dispassionate teachers. I’m unaware of any school who teaches early engineers how they should best consume engineering media — or how to choose a technical tool. Often, this means that we’re then vulnerable for a few years, until we’ve incorporated the lessons from working on a good team.

    Having a few thoughtful experts in our community is also critical when assessing deeply technical decisions like what database to use or how best to architect a system. The danger with some experts — the non-thoughtful variety — is that their confidence in their abilities means they don’t question many deep seated assumptions and can’t make adjustments when the world changes. Thoughtful experts have both content expertise and strong opinions that are weakly held.

    Coda

    We engineers share some similarities with the machine learning algorithms we design. In both, data is used to make inferences about future decisions. As such, it’s important to have a thoughtfully curated training data set — and to adjust for any errors when our engineering inputs are compromised.

    I’ve hardly touched on all the other questions we should be discussing, beyond encouraging critical thinking and finding trusted networks of thoughtful engineers. For example, should we debate alternate Hacker News and Twitter algorithms with the hope of creating better engineers? Should there be conflict disclosures for open source developers? Should popular engineering blogs such as Free Code Camp have a board of engineers who technically assess content and the background of writers? Should we teach engineering media literacy in bootcamps and CS programs?

    Still, I’m encouraged by the fact that critical thinking and testing hypothesis is such a natural part of how engineers and scientists approach the world. This mindset has a critical role to play far beyond the day to day engineering problems we aim to solve.

    See the Hacking Engineers and Engineering Media Github. Contributions are welcome.


    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;电报群 https://t.me/OpeningSourceOrg
  • 2018年3月26日:开源日报第18期

    26 3 月, 2018

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;电报群 https://t.me/OpeningSourceOrg


    今日推荐开源项目:《Carbon帮你做出更漂亮的代码截图》

    推荐理由:Carbon让你可以改变你代码的语法主题、背景颜色、系统主题或者装饰来自定义你的图片,帮你做出更漂亮的代码截图让你发到社交网站上去分享。

    使用carbon

    1. 直接在https://carbon.now.sh/中使用,或部署在本地
    2. (1)将你想要截图的代码片段复制过去

    (2)直接将你的代码文件拖进去

    (3)在https://carbon.now.sh/后追加GitHub gist id ,例如:

    https://carbon.now.sh/YOUR_GIST_ID

    1. 愉快的更换语法主题,背景颜色,窗口主题或填充得到你要的效果
    2. 你可以选择开源项目精选:Carbon帮你做出更漂亮的代码截图来下载图片,也可以按开源项目精选:Carbon帮你做出更漂亮的代码截图共享链接

    例如:Zenburn+BG:1D1F22+其他默认

    开源项目精选:Carbon帮你做出更漂亮的代码截图

    Seti + BG:93B2DB+ windows theme:3+ line number+ drop shadow

    开源项目精选:Carbon帮你做出更漂亮的代码截图

    当然,背景也可以自定义图片,你可以用骚气无比的方式来分享你的源码

    注:Atom , VS Code, Sublime Text 3, Vim 等都可支持Carbon,详情自看官方说明

    关于GitHub gist

    代码片段管理服务,可以作为个人的代码管理器,文档管理器等等

    官方说明:https://help.github.com/articles/about-gists/

    知乎回答:https://www.zhihu.com/question/21343711

     

    Atom(github专门为程序员推出的一个跨平台文本编辑器)

    按shift-cmd-A,你可以在Carbon里打开你最近的Atom文件

     

    VS Code

    命令‘carbon’来打开你最近的 VS Code文件

     

    Sublime Text 3

    按你自己特定的键在你最近的Sublime Text 3文件打开可选择的项

     

    Vim

    使用函数CarbonNowSh()在你的最近的Vim/Neovim中打开可选择的项

     

    作者介绍

    • Brian Dennis
    开源项目精选:Carbon帮你做出更漂亮的代码截图

    美国威斯康星大学大三的学生,学习计算机科学和应用数学,有管理和领导学生组织的能力,有编程马拉松(英语:hackathon,又译为黑客松,一个流传于黑客(hacker)当中的新词汇)的经验

    个人主页:http://briandennis.io/

     

    • Michael Fix
    开源项目精选:Carbon帮你做出更漂亮的代码截图

    待人热忱,推动了麦迪逊城市创业的生态系统,喜欢设计网页,喜欢喝咖啡,爱好工科,也爱好艺术

    个人主页:https://mfix22.github.io/


    今日推荐英文原文:《Pseudo-Code, Humor, and the Art of Googling》作者:Joseph Cardillo

    原文链接:https://medium.com/@josephcardillo/pseudo-code-humor-and-the-art-of-googling-71f6b5e8ce2e

    Pseudo-Code, Humor, and the Art of Googling

    The most important things I’ve learned about programming so far have nothing to do with writing code. Rather, they are the things that happen before and in-between the code writing.


    When I’m first given a problem or assignment to work through, my gut reaction is to dive right in to coding or asking questions on Google, because it can seem counter-productive to do anything else. I’ve quickly realized this is not true.

    The generals have a saying:
    “Rather than make the first move
    it is better to wait and see.
    Rather than advance an inch
    it is better to retreat a yard.” (Tao Te Ching, №69)

    I’ve never been in battle, but I think the idea here is that in battle it might seem like moving forward is the most productive thing you could do, and that to retreat is to give ground to the enemy. To give them the advantage.

    In regards to coding, I’m finding that taking a few steps back to get the big picture, write pseudo-code and think through my problem with pencil and paper (or in the text editor) goes a long way, sets me up for more insightful and thoughtful questions, and actually saves time in the long run.

    Write in Pseudo-Code

    When we were first encouraged to do this I didn’t see the point. Maybe because we were working on simpler problems that didn’t require the use of extensive pseudo-code. But as the assignments got more complicated, this has become invaluable.

    It gives me a chance to flesh out the problem from beginning to end.

    // My pseudo-code process:
    // 1. Read over the problem.
    // 2. Write out in long form what I’m trying to accomplish, even if I repeat verbatim parts of the question. Where am I starting? Where am I going? What path am I taking? What side-paths may I want to take along the way? What tools do I need? What kind of functionality?
    // 3. Go back over my notes (from #2) and add in sub-thoughts to further flesh out the process and include questions I have for myself (or others, or Google) I’ll likely ask along the way.
    // 4. Start coding.
    // 5. Test each baby-step in the console.
    // 6. Repeat step five.
    // 7. Repeat step five.
    // 8. Repeat step five. [...]

    Think First, Then Google

    As mentioned above, another gut reaction of mine is to ask questions on Google immediately. Besides, we’ve been told that eighty to ninety percent (or more) of a developer’s day is spent Googling how to do things. So why would I not do the same?

    I cannot attest to this, not being a full fledged developer yet. But what I am realizing is that there are ways of Googling that are helpful to me, and some that are actually counter-productive.

    I’m finding that when I turn to Google first, a part of my brain is actually shutting down.

    If I turn to Google thoughtlessly, I’m not actually learning to think like a programmer.

    What I mean is this: If I don’t take time to write pseudo-code and think through the details of the project, I’ll end up Googling in an inefficient way. I’ll end up wasting time, which in the short-term — even though writing psuedo-code might feel like I’m taking two steps back to go one-step forward — it actually is saving time and headaches along the way by helping me be more thoughtful about the questions I ask on Google, because I’ll be more likely to understand what I’m asking, and why I’m asking it.

    Console.log(“everything”)

    This is huge. I didn’t realize it at first, but this saves an enormous amount of time and energy, too. It gives a chance to test each idea in Chrome’s Developer Tools to see if it actually works, and if there are any errors or bugs to work out.

    Failure is an opportunity. (№79)

    This is where I think of the phrase: “Failure is an opportunity.” The console is unforgiving. Though, because of that, it is also my best friend. It doesn’t beat around the bush and tell me my code looks great, that I’m handsome and doing a great job, etc. If something’s broken, It lets me know. It doesn’t praise or berate me. It just tells me like it is. It keeps me humble and keeps me moving.

    If psuedo-code helped me break the process down into baby-steps, the console helps me break it down into micro-steps.

    For example, if one of my baby steps is to create a function that replaces the innerHTML of an element based in its id, the console gives me the ability to find out if my syntax is correct when I use jQuery to target that id, if I’m actually capturing the innerHTML, and if everything is properly formatted when I run the function. All without changing a single line of code.

    The console gives me the chance to fail, and learn from my mistakes. It helps keep things moving, and target where I’m specifically getting stuck. It helps me ask better questions.

    Have a Sense of Humor

    Programming can be frustrating! And I’m just a baby at it. But if I can have a sense of humor along the way, it helps relieve the tension that tends to get me stuck. I try to write humorous things in my pseudo-code, even if I’m making fun of myself, because laughing at myself helps relieve the tension, and helps keep me grounded.

    If frustration gets me stuck, humor is a way of getting unstuck. It helps keep the code flowing.

     


    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;电报群 https://t.me/OpeningSourceOrg

  • 2018年3月25日:开源日报第17期

    25 3 月, 2018

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;电报群 https://t.me/OpeningSourceOrg


    今日推荐开源项目:《几分钟初步认识JSON》

    推荐理由:本文旨在短时间内让读者简单的认识 JSON

    JSON 简介

    JSON,即 JavaScript Object Notation 的缩写,指的是 JavaScript 的对象表示法,虽然 JSON 使用 JS 语法来描述数据对象,但其本身独立于语言和平台,JSON 的解析器和库都支持不同的编程语言。

    与 XML(可扩展标记语言)类似的是,JSON 是纯文本;具有自我描述性,即我们可以简单的理解它;具有层级结构。

    JSON 语法

    JSON 数据的书写格式是名称/值对,其中包括双引号中的字段名称,后面写一个冒号,然后是值,值可以是整数或浮点数、双引号中的字符串、true or false、方括号中的数组、花括号中的对象;null。例如下面这条

    "JSON":"helloworld"

    这条语句等价于

    JSON = "helloworld"

     

    JSON 对象在花括号中书写,其中可以包含多个名称/值对,比如下面这条

    {
      "JS":"hello",
      "ON":"world"
    }

    等价于

    JS ="hello", ON ="world"

     

    JSON 数组在方括号中书写,其中可以包含多个对象,

    {
     "JP":[
        {"JS":"hell", "ON":"wrld"},
        {"JS":"helo", "ON":"wold"},
        {"JS":"hllo", "ON":"word"}
      ]
    }

    因为 JSON 使用的是 JavaScript 的语法,所以无需额外的软件就能处理JS 中的 JSON,比如这样

    var JP = [
      {"JS":"hell", "ON":"wrld"},
      {"JS":"helo", "ON":"wold"},
      {"JS":"hllo", "ON":"word"}
    ];

    如果要访问对象数组,可以像这样进行访问

    JP[0].JS

    返回的内容是

    hell

    JavaScript 处理 JSON 数据

    JSON 最常见的用法之一,是从 web 服务器上读取 JSON 数据,将 JSON 数据转换为 JavaScript 对象,然后在网页中使用该数据。接下来,我们来讨论 JavaScript 如何处理 JSON 数据。

    在 web 页面中用 JavaScript 处理 JSON 数据时,

    function handleJson() {
     var Message={"name":"Michael","address":
         {"city":"Beijing","street":"Chaoyang Road","postcode":100025}
     };
     document.write(Message.name);
     document.write(Message.address.city);
    }

    假定服务器返回的 JSON 数据是上文的:

    {
      "name":"Michael",
      "address":{
        "city":"Beijing",
        "street":" Chaoyang Road ",
        "postcode":100025
      }
    }

    只需将其赋值给一个 JavaScript 变量(例如上文中的 Message),就可以立刻使用该变量并更新页面中的信息了。

    这相比起 XML 就显得更加的容易。我们要做的仅仅是将服务器返回的JSON 数据赋给一个 JavaScript 变量即可。

    JSON 的数据可移植性问题

    JSON 允许 Unicode 行结束符 U + 2028(行分隔符)和 U + 2029(段落分隔符)在引用字符串中显示为非转义,而 JavaScript 不显示。这是JSON 只禁止”控制字符”的结果。为了最大限度地提高可移植性,这些字符应该反斜杠转义。生成 JSONP 时,这个微妙之处非常重要。

    更多关于 U+2028/2029 的讨论:

    https://github.com/rack/rack-contrib/pull/37

    JSON 文档可以用 UTF-8,UTF-16 或 UTF-32 编码,默认编码为 UTF-8(I-JSON 仅支持 UTF-8)。这些编码支持完整的 Unicode 字符集,包括基本多语言面以外的字符(U + 10000至U + 10FFFF)。但是,如果转义,那么这些字符必须使用 UTF-16 代理对(一些 JSON 解析器遗漏的细节)编写。例如,在 JSON 中包含表情符号字符U + 1F602 ?(喜极而泣):

    { “face” : “?” }

    //或

    { “face” : “\uD83D\uDE02” }

    JSON 中的数字在编程语言中的表示是不可知的。整数和浮点值之间没有区分太清楚:一些可能把42,42.0以及4.2E+1当成是一样的,而其他的可能不会。对于溢出,下溢,精度损失或舍入等问题没有要求。另外,JSON 没有提及有符号零的处理:0.0是否不同于-0.0。使用 IEEE 754浮点标准(包括 JavaScript)的大多数实现都保留带符号的零; 但并不是所有的 JSON 实现都可以这样做。


    今日推荐英文原文:《Python Top 10 Open Source Projects (v.Mar 2018)》作者:Mybridge

    原文链接:https://medium.mybridge.co/python-top-10-open-source-projects-v-mar-2018-e2ce1d645ec

    Python Top 10 Open Source Projects (v.Mar 2018)

    For the past month, we ranked nearly 250 Python Open Source Projects to pick the Top 10.

    We compared projects with new or major release during this period. Mybridge AI ranks projects based on a variety of factors to measure its quality for professionals.

    • Average number of Github stars in this edition: 570⭐️
    • “Watch” Python Top 10 Open Source on Github and get email once a month.
    • Topics: Datetime, Debugger, Maps, Data validation, Print, Trading Bot, Multidiff, Matrix, Downloder

    Open source projects can be useful for programmers. Hope you find an interesting project that inspires you.

    Rank 1

    Delorean: Delorean: Time Travel Made Easy [V 1.0] [1335 stars on Github]. Courtesy of Mahdi Yusuf


    Rank 2

    Birdseye: Quick, convenient, expression-centric, graphical Python debugger using the AST [674 stars on Github]. Courtesy of Alex Hall


    Rank 3

    Som-tsp: Solving the Traveling Salesman Problem using Self-Organizing Maps [432 stars on Github]. Courtesy of Diego Vicente


    Rank 4

    Voluptuous: Voluptuous, despite the name, is a Python data validation library. [1066 stars on Github]. Courtesy of Alec Thomas


    Rank 5

    Icecream: Sweet and Creamy Print Debugging [530 stars on Github]. Courtesy of Gruns


    Rank 6

    Binance-trader: Cryptocurrency Trading Bot for Binance (Experimental) [590 stars on Github]. Courtesy of Yasin


    Rank 7

    Multidiff: Binary data diffing for multiple objects or streams of data [188 stars on Github]. Courtesy of Juha Kivekäs


    Rank 8

    Unimatrix: Python script to simulate the display from “The Matrix” in terminal. Uses half-width katakana unicode characters by default, but can use custom character sets. Accepts keyboar… [558 stars on Github]. Courtesy of Will8211


    Rank 9

    Mypy-protobuf: open source tools to generate mypy stubs from protobufs [33 stars on Github]. Courtesy of Dropbox


    Rank 10

    Lulu: A friendly you-get fork (⏬ Dumb downloader that scrapes the web) [296 stars on Github].

     


    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;电报群 https://t.me/OpeningSourceOrg

  • 2018年3月24日:开源日报第16期

    24 3 月, 2018

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;电报群 https://t.me/OpeningSourceOrg


    今日推荐开源项目:《SIX——Python2和3的兼容性库》

    推荐理由:SIX是用于python2与python3兼容的库。它存在的目的是为了拥有无需修改即可在Python 2和Python 3上同时工作的代码。话虽这么说,但是这并不代表在Python 3中引用该库就可以轻松地跑Python 2的代码。

    实际上,SIX是重定义了在python2和3中有差异的函数,例如dict的获取全部键值函数:在Python2中是

    .iterkeys()

    在Python3中是

    .keys()

    而在SIX中是

    six.iterkeys(dict)(当然对应版本的原函数也能够使用)

    也就是说,离开了SIX库的话你写的代码不论在Python2还是Python3中都无法运行。因此不是急于追求兼容性的话并不需要使用这个库。

    安装:

    https://github.com/benjaminp/six/releases

    解压后双击steup.py即可。

     

    使用

    import six

    之后按照SIX提供的语法书写即可写出pyhton2/3上兼容的代码。

     

    six.PY2/ six.PY3 :检查编译器版本是否为python2/3

     

    以下是SIX提供的兼容语法:

    常量定义:

    six.class_types

    可能的类类型。在Python 2中,这包含旧类和新类。在Python 3中,这只是新类。

     

    six.integer_types

    可能的整数类型。在Python 2中,这是long或 int,在Python 3中同int。

     

    six.string_types

    文本数据的可能类型。这是Python 2终点basestring()和 Python 3中的str。

     

    six.text_type

    用于表示(Unicode)文本数据的类型。这是unicode()在Python 2和Python 3中的str(Pyhon3对文本数据进行了整合,默认为Unicode文本数据)。

     

    six.binary_type

    代表二进制数据的类型。这是Python 2中的str和 Python 3中的bytes。

     

    six.MAXSIZE

    像list 或dict这样的容器的最大尺寸。这相当于 Python 2.6及更高版本(包括3.x)的sys.maxsize。请注意,这与sys.maxint Python 2 非常相似,但并不相同 。sys.maxint在Python 3中没有直接的等价物, 因为它的整数类型的长度仅受限于内存大小。

     

    内置函数定义

    1、six.get_unbound_function(meth)

    获取非绑定方法的meth。在Python 3,不存在非绑定方法,所以这个功能只是返回meth不变。用法示例:

    from six import get_unbound_function

     

    class X(object):

    def method(self):

    pass

     

    method_function = get_unbound_function(X.method)six.get_method_function(meth)

     

    2、six.get_method_self(meth)

    获取self绑定的方法的meth。

     

    3、six.get_function_closure(func)

    等效于Python 2.6+中的func.__closure__和Python 2.5中的func.func_closure

     

    4、six.get_function_code(func)

    获取与func关联的代码对象。等效于Python 2.6+中的 func.__code__和Python 2.5中的func.func_code。

     

    5、six.get_function_defaults(func)

    获取与func关联的默认元组。等效于Python 2.6+中的 func.__defaults__和Python 2.5中的func.func_defaults。

     

    6、six.get_function_globals(func)

    获取全局函数。等效于Python 2.6+中的func.__globals__和Python 2.5中的func.func_globals。

     

    7、six.next(it) six.advance_iterator(it)

    获取迭代器it的下一个项目。如果迭代器到达末尾,则会引发StopIteration。等效于Python 中的it.next()2和Python 3中的next(it).Python 2.6及更高版本具有内置next函数,因此只有需要兼容Python 2.5版本及以下时才需要该函数。

     

    8、six.callable(obj )

    检查是否可以调用obj。callable标记已经在Python 3.2中有返回,所以只有在支持Python 3.0或3.1时才需要使用six的版本。

     

    9、six.iterkeys(字典,** kwargs )

    返回字典键上的迭代器。等效于Python 2中的 dictionary.iterkeys()和Python 3中的dictionary.keys()。 kwargs被传递给底层方法。

     

    10、six.itervalues(字典,** kwargs )

    返回字典值的迭代器。等效于Python 2中的dictionary.itervalues()和Python 3中的dictionary.values()。kwargs被传递给底层方法。

     

    11、six.iteritems(字典,** kwargs )

    返回字典项目的迭代器。等效于Python 2中的 dictionary.iteritems()和Python 3中的dictionary.items()。 kwargs被传递给底层方法。

     

    12、six.iterlists(字典,** kwargs )

    调用Python 2中的dictionary.iterlists() 或Python 3中的dictionary.lists()。原版的Python映射类型没有这种等效; 此方法旨在能够使用像Werkzeug’s这样的多值词典。 kwargs被传递给底层方法。

     

    13、six.viewkeys(字典)

    通过字典的键返回视图。等效于 Python 2.7中的dict.viewkeys()和Python 3中的dict.keys()。

     

    14、six.viewvalues(字典)

    通过字典的值返回视图。等效于 Python 2.7中的dict.viewvalues()和Python 3中的dict.values()。

     

    15、six.viewitems(字典)

    返回字典项目的视图。等效于 Python 2.7中的dict.viewitems()和Python 3中的dict.items()。

     

    16、six.create_bound_method(func,obj )

    返回一个方法对象包装func并绑定到obj。在Python 2和Python 3上,这将返回一个types.MethodType对象。这个包装器函数存在的原因是,在Python 2中,MethodType构造函数需要传递obj的类。

     

    17、six.create_unbound_method(func,cls )

    返回一个未绑定的方法对象包装函数。在Python 2中,这将返回一个types.MethodType对象。在Python 3中,未绑定的方法不存在,并且此包装将简单地返回func。

     

    18、class six.Iterator

    一个用于制作小型迭代器的类。其目的是将其划分子类并提供一种__next__方法。在Python 2中,Iterator 有一个方法:next。它只代表__next__。或许可以仅仅为 __next__取别名next。但是这会对重定义了 __next__的子类造成严重影响。Iterator在Python 3中是空的。(实际上,它只是被命名为object。)

     

    关于SIX的函数就介绍到这里。想要了解更多SIX的兼容语法请访问其官网

    http://six.readthedocs.io/

    而github上提供的是对SIX库本身的更新与建议。如果你在使用SIX的过程中遇到了问题,不妨在github中提出issue。

     


    今日推荐英文原文:《Code Review Best Practices》原文作者:Robert F.

    原文链接:https://medium.com/@palantir/code-review-best-practices-19e02780015f

    Code Review Best Practices

    XKCD ‘Code Quality’, copied under CC BY-NC 2.5

    The Internet provides a wealth of material on code reviews: on the effect of code reviews on company culture, on formal security reviews, shorter guides, longer checklists, humanized reviews, reasons for doing code reviews in the first place, best practices, more best practices, statistics on code review effectiveness for catching bugs, and examples of code reviews gone wrong. Oh, and of course there are books, too. Long story short, this blog post presents Palantir’s take on code reviews. Organizations with deep cultural reluctance to peer reviews may want to consult Karl E. Wiegers’ excellent essay on Humanizing Peer Reviews before trying to follow this guide.

    This post is copied from the best practices guides of our Java Code Quality tool chain, Baseline, and covers the following topics:

    • Why, what, and when to do code reviews
    • Preparing code for review
    • Performing code reviews
    • Code review examples

    Motivation

    We perform code reviews (CRs) in order to improve code quality and benefit from positive effects on team and company culture. For example:

    • Committers are motivated by the notion of a set of reviewers who will look over the change request: the committer tends to clean up loose ends, consolidate TODOs, and generally improve the commit. Recognition of coding expertise through peers is a source of pride for many programmers.
    • Sharing knowledge helps development teams in several ways:
      – A CR explicitly communicates added/altered/removed functionality to team members who can subsequently build on the work done.
      – The committer may use a technique or algorithm that reviewers can learn from. More generally, code reviews help raise the quality bar across the organization.
      – Reviewers may possess knowledge about programming techniques or the code base that can help improve or consolidate the change; for example, someone else may be concurrently working on a similar feature or fix.
      – Positive interaction and communication strengthens social bonds between team members.
    • Consistency in a code base makes code easier to read and understand, helps prevent bugs, and facilitates collaboration between regular and migratory developer species.
    • Legibility of code fragments is hard to judge for the author whose brain child it is, and easy to judge for a reviewer who does not have the full context. Legible code is more reusable, bug-free, and future-proof.
    • Accidental errors (e.g., typos) as well as structural errors (e.g., dead code, logic or algorithm bugs, performance or architecture concerns) are often much easier to spot for critical reviewers with an outside perspective. Studies have found that even short and informal code reviews have significant impact on code quality and bug frequency.
    • Compliance and regulatory environments often demand reviews. CRs are a great way to avoid common security traps. If your feature or environment has significant security requirements it will benefit from (and probably require) review by your local security curmudgeons (OWASP’s guide is a good example of the process).

    What to review

    There is no eternally true answer to this question and each development team should agree on its own approach. Some teams prefer to review every change merged into the main branch, while others will have a “triviality” threshold under which a review is not required. The trade-off is between effective use of engineers’ (both authors’ and reviewers’) time and maintaining code quality. In certain regulatory environments, code review may be required even for trivial changes.

    Code reviews are classless: being the most senior person on the team does not imply that your code does not need review. Even if, in the rare case, code is flawless, the review provides an opportunity for mentorship and collaboration, and, minimally, diversifies the understanding of code in the code base.

    When to review

    Code reviews should happen after automated checks (tests, style, other CI) have completed successfully, but before the code merges to the repository’s mainline branch. We generally don’t perform formal code review of aggregate changes since the last release.

    For complex changes that should merge into the mainline branch as a single unit but are too large to fit into one reasonable CR, consider a stacked CR model: Create a primary branch feature/big-feature and a number of secondary branches (e.g., feature/big-feature-api, feature/big-feature-testing, etc.) that each encapsulate a subset of the functionality and that get individually code-reviewed against the feature/big-feature branch. Once all secondary branches are merged into feature/big-feature, create a CR for merging the latter into the main branch.

    Preparing code for review

    It is the author’s responsibility to submit CRs that are easy to review in order not to waste reviewers’ time and motivation:

    • Scope and size. Changes should have a narrow, well-defined, self-contained scope that they cover exhaustively. For example, a change may implement a new feature or fix a bug. Shorter changes are preferred over longer ones. If a CR makes substantive changes to more than ~5 files, or took longer than 1–2 days to write, or would take more than 20 minutes to review, consider splitting it into multiple self-contained CRs. For example, a developer can submit one change that defines the API for a new feature in terms of interfaces and documentation, and a second change that adds implementations for those interfaces.
    • Only submit complete, self-reviewed (by diff), and self-tested CRs. In order to save reviewers’ time, test the submitted changes (i.e., run the test suite) and make sure they pass all builds as well as all tests and code quality checks, both locally and on the CI servers, before assigning reviewers.
    • Refactoring changes should not alter behavior; conversely, a behavior-changing changes should avoid refactoring and code formatting changes. There are multiple good reasons for this:
      – Refactoring changes often touch many lines and files and will consequently be reviewed with less attention. Unintended behavior changes can leak into the code base without anyone noticing.
      – Large refactoring changes break cherry-picking, rebasing, and other source control magic. It is very onerous to undo a behavior change that was introduced as part of a repository-wide refactoring commit.
      – Expensive human review time should be spent on the program logic rather than style, syntax, or formatting debates. We prefer settling those with automated tooling like Checkstyle, TSLint, Baseline, Prettier, etc.

    Commit messages

    The following is an example of a good commit message following a widely quoted standard:

    Capitalized, short (80 chars or less) summary
    More detailed explanatory text, if necessary. Wrap it to about 120 characters or so. In some contexts, the first
    line is treated as the subject of an email and the rest of the text as the body. The blank line separating the
    summary from the body is critical (unless you omit the body entirely); tools like rebase can get confused if you run
    the two together.
    Write your commit message in the imperative: "Fix bug" and not "Fixed bug" or "Fixes bug." This convention matches
    up with commit messages generated by commands like git merge and git revert.
    Further paragraphs come after blank lines.
    - Bullet points are okay, too

    Try to describe both what the commit changes and how it does it:

    > BAD. Don't do this.
    Make compile again
    > Good.
    Add jcsv dependency to fix IntelliJ compilation

    Finding reviewers

    It is customary for the committer to propose one or two reviewers who are familiar with the code base. Often, one of the reviewers is the project lead or a senior engineer. Project owners should consider subscribing to their projects in order to get notified of new CRs. Code reviews among more than three parties are often unproductive or even counter-productive since different reviewers may propose contradictory changes. This may indicate fundamental disagreement on the correct implementation and should be resolved outside a code review in a higher-bandwidth forum, for example in person or in a video conference with all involved parties.

    Performing code reviews

    A code review is a synchronization point among different team members and thus has the potential to block progress. Consequently, code reviews need to be prompt (on the order of hours, not days), and team members and leads need to be aware of the time commitment and prioritize review time accordingly. If you don’t think you can complete a review in time, please let the committer know right away so they can find someone else.

    A review should be thorough enough that the reviewer could explain the change at a reasonable level of detail to another developer. This ensures that the details of the code base are known to more than a single person.

    As a reviewer, it is your responsibility to enforce coding standards and keep the quality bar up. Reviewing code is more of an art than a science. The only way to learn it is to do it; an experienced reviewer should consider putting other less experienced reviewers on their changes and have them do a review first. Assuming the author has followed the guidelines above (especially with respect to self-review and ensuring the code runs), here’s an list of things a reviewer should pay attention to in a code review:

    Purpose

    • Does this code accomplish the author’s purpose? Every change should have a specific reason (new feature, refactor, bugfix, etc). Does the submitted code actually accomplish this purpose?
    • Ask questions. Functions and classes should exist for a reason. When the reason is not clear to the reviewer, this may be an indication that the code needs to be rewritten or supported with comments or tests.

    Implementation

    • Think about how you would have solved the problem. If it’s different, why is that? Does your code handle more (edge) cases? Is it shorter/easier/cleaner/faster/safer yet functionally equivalent? Is there some underlying pattern you spotted that isn’t captured by the current code?
    • Do you see potential for useful abstractions? Partially duplicated code often indicates that a more abstract or general piece of functionality can be extracted and then reused in different contexts.
    • Think like an adversary, but be nice about it. Try to “catch” authors taking shortcuts or missing cases by coming up with problematic configurations/input data that breaks their code.
    • Think about libraries or existing product code. When someone re-implements existing functionality, more often than not it’s simply because they don’t know it already exists. Sometimes, code or functionality is duplicated on purpose, e.g., in order to avoid dependencies. In such cases, a code comment can clarify the intent. Is the introduced functionality already provided by an existing library?
    • Does the change follow standard patterns? Established code bases often exhibit patterns around naming conventions, program logic decomposition, data type definitions, etc. It is usually desirable that changes are implemented in accordance with existing patterns.
    • Does the change add compile-time or run-time dependencies (especially between sub-projects)? We want to keep our products loosely coupled, with as few dependencies as possible. Changes to dependencies and the build system should be scrutinized heavily.

    Legibility and style

    • Think about your reading experience. Did you grasp the concepts in a reasonable amount of time? Was the flow sane and were variable and methods names easy to follow? Were you able to keep track through multiple files or functions? Were you put off by inconsistent naming?
    • Does the code adhere to coding guidelines and code style? Is the code consistent with the project in terms of style, API conventions, etc.? As mentioned above, we prefer to settle style debates with automated tooling.
    • Does this code have TODOs? TODOs just pile up in code, and become stale over time. Have the author submit a ticket on GitHub Issues or JIRA and attach the issue number to the TODO. The proposed code change should not contain commented-out code.

    Maintainability

    • Read the tests. If there are no tests and there should be, ask the author to write some. Truly untestable features are rare, while untested implementations of features are unfortunately common. Check the tests themselves: are they covering interesting cases? Are they readable? Does the CR lower overall test coverage? Think of ways this code could break. Style standards for tests are often different than core code, but still important.
    • Does this CR introduce the risk of breaking test code, staging stacks, or integrations tests? These are often not checked as part of the pre-commit/merge checks, but having them go down is painful for everyone. Specific things to look for are: removal of test utilities or modes, changes in configuration, and changes in artifact layout/structure.
    • Does this change break backward compatibility? If so, is it OK to merge the change at this point or should it be pushed into a later release? Breaks can include database or schema changes, public API changes, user workflow changes, etc.
    • Does this code need integration tests? Sometimes, code can’t be adequately tested with unit tests alone, especially if the code interacts with outside systems or configuration.
    • Leave feedback on code-level documentation, comments, and commit messages. Redundant comments clutter the code, and terse commit messages mystify future contributors. This isn’t always applicable, but quality comments and commit messages will pay for themselves down the line. (Think of a time you saw an excellent, or truly terrible, commit message or comment.)
    • Was the external documentation updated? If your project maintains a README, CHANGELOG, or other documentation, was it updated to reflect the changes? Outdated documentation can be more confusing than none, and it will be more costly to fix it in the future than to update it now.

    Don’t forget to praise concise/readable/efficient/elegant code. Conversely, declining or disapproving a CR is not rude. If the change is redundant or irrelevant, decline it with an explanation. If you consider it unacceptable due to one or more fatal flaws, disapprove it, again with an explanation. Sometimes the right outcome of a CR is “let’s do this a totally different way” or even “let’s not do this at all.”

    Be respectful to the reviewees. While adversarial thinking is handy, it’s not your feature and you can’t make all the decisions. If you can’t come to an agreement with your reviewee with the code as is, switch to real-time communication or seek a third opinion.

    Security

    Verify that API endpoints perform appropriate authorization and authentication consistent with the rest of the code base. Check for other common weaknesses, e.g., weak configuration, malicious user input, missing log events, etc. When in doubt, refer the CR to an application security expert.

    Comments: concise, friendly, actionable

    Reviews should be concise and written in neutral language. Critique the code, not the author. When something is unclear, ask for clarification rather than assuming ignorance. Avoid possessive pronouns, in particular in conjunction with evaluations: “my code worked before your change”, “your method has a bug”, etc. Avoid absolute judgements: “this can never work”, “the result is always wrong”.

    Try to differentiate between suggestions (e.g., “Suggestion: extract method to improve legibility”), required changes (e.g., “Add @Override”), and points that need discussion or clarification (e.g., “Is this really the correct behavior? If so, please add a comment explaining the logic.”). Consider providing links or pointers to in-depth explanations of a problem.

    When you’re done with a code review, indicate to what extent you expect the author to respond to your comments and whether you would like to re-review the CR after the changes have been implemented (e.g., “Feel free to merge after responding to the few minor suggestions” vs. “Please consider my suggestions and let me know when I can take another look.”).

    Responding to reviews

    Part of the purpose of the code review is improve the author’s change request; consequently, don’t be offended by your reviewer’s suggestions and take them seriously even if you don’t agree. Respond to every comment, even if it’s only a simple “ACK” or “done.” Explain why you made certain decisions, why some function exists, etc. If you can’t come to an agreement with the reviewer, switch to real-time communication or seek an outside opinion.

    Fixes should be pushed to the same branch, but in a separate commit. Squashing commits during the review process makes it hard for the reviewer to follow up on changes.

    Different teams have different merge policies: some teams allow only project owners to merge, while other teams allow the contributor to merge after a positive code review.

    In-person code reviews

    For the majority of code reviews, asynchronous diff-based tools such as Reviewable, Gerrit or, GitHub are a great choice. Complex changes, or reviews between parties with very different expertise or experience can be more efficient when performed in person, either in front of the same screen or projector, or remotely via VTC or screen share tools.

    Examples

    In the following examples, suggested review comments are indicated by //R: ... comments in the code blocks.

    Inconsistent naming

    class MyClass {
      private int countTotalPageVisits; //R: name variables consistently
      private int uniqueUsersCount;
    }

    Inconsistent method signatures

    interface MyInterface {
      /** Returns {@link Optional#empty} if s cannot be extracted. */
      public Optional<String> extractString(String s);
      /** Returns null if {@code s} cannot be rewritten. */
      //R: should harmonize return values: use Optional<> here, too
      public String rewriteString(String s);
    }

    Library use

    //R: remove and replace by Guava's MapJoiner
    String joinAndConcatenate(Map<String, String> map, String keyValueSeparator, String keySeparator);

    Personal taste

    int dayCount; //R: nit: I usually prefer numFoo over fooCount; up to you, but we should keep it consistent in this project

    Bugs

    //R: This performs numIterations+1 iterations, is that intentional?
    //   If it is, consider changing the numIterations semantics?
    for (int i = 0; i <= numIterations; ++i) {
      ...
    }

    Architectural concerns

    otherService.call(); //R: I think we should avoid the dependency on OtherService. Can we discuss this in person?

    每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,欢迎关注开源日报。交流QQ群:202790710;电报群 https://t.me/OpeningSourceOr

←上一页
1 … 255 256 257 258 259 … 262
下一页→

Proudly powered by WordPress