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

开源日报

  • 开源日报第480期:《取其精华 pattern-dreamer》

    8 7 月, 2019
    开源日报 每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。
    今日推荐开源项目:《取其精华 pattern-dreamer》
    今日推荐英文原文:《How To Create Meaningful Names In Code》

    今日推荐开源项目:《取其精华 pattern-dreamer》传送门:GitHub链接
    推荐理由:这个项目能够提取一个字符串中的重要元素——比如邮件地址和 URL 以及它们的各种参数等。为了避免这些繁杂的工作,用户的输入通常应该遵守规定的格式以便于处理;但是在有些比如处理文本等无法预先给定格式的场合,要想把 URL 和参数等一个个分拣出来并非易事,要把正则表达式和字符串处理等各种神通都用上兴许才能做到准确拆分,而这个项目就做到了。
    今日推荐英文原文:《How To Create Meaningful Names In Code》作者:Daan Daan
    原文链接:https://medium.com/better-programming/how-to-create-meaningful-names-in-code-20d7476537d4
    推荐理由:哦我亲爱的老伙计,放下那本见鬼的婴儿起名指南吧

    How To Create Meaningful Names In Code

    Simple rules you can follow to create good names


    As a developer, you spend a lot of your coding time making variables and thinking about proper names. Names are everywhere. You name files, classes, methods, and variables.

    As we spend so much time naming things it’s really important to do it well. In this article, I will show you some simple rules you can follow for creating good names. Naming things in your code is an art in itself!

    Use Names Which Reveal Intention

    Having names which reveal their intent is easier said than done. How often do you come across variable names that don’t tell you anything about their intent?

    A good rule of thumb is: If a name requires a comment, then it doesn’t reveal the intent.

    The following piece of code is a variable which does not reveal intent:
    <?php
    private $s; // Time in seconds
    
    The variable $s reveals nothing. It does not evoke a sense of lapsed time. It would be better to choose a name that specifies what is being measured, and the unit of that measurement.

    One of the variable names in the example below would be much better.
    <?php
    private $days_since_creation;
    private $elapsed_time_in_seconds;
    private $seconds_since_last_modified;
    
    Choosing names that reveal intent can make it much easier to understand a piece of code, and therefor easier to maintain.

    Choosing good names takes time, but it saves more time than it takes.

    Let’s take a look at the following example:
    <?php
    function getList() {
        $list1 = [];
    
        foreach ($this->the_list as $x) {
            if ($x % 2 != 0) {
                $list1[] = $x;
            }
        }
    
        return $list1;
    }
    function getOddNumbers() {
        $odd_numbers = [];
    
        foreach ($this->numbers as $number) {
            if (isOdd($number)) {
                $odd_numbers[] = $number;
            }
        }
    
        return $odd_numbers;
    }
    
    Why is it so hard to tell what the getList function does? There are no complex expressions. The code is indented and formatted properly. Only three variables are used and there’s no fancy stuff.

    Now take a look at the getOddNumbers function. Did you see that the function does exactly the same as the getList function?

    Notice that the simplicity of the code has not changed. It still has exactly the same number of operators and variables, with exactly the same number of nesting levels. The only thing that has changed, is that the code has become much more explicit.

    With some simple name changes, it is suddenly much easier to tell what this piece of code does.

    Avoid Disinformation

    You should avoid leaving false clues that obscure the meaning of code.

    Avoid misleading words where their meaning varies from the intended meaning. For example, do not refer to a grouping of products as a productList, unless it actually is an object of the type List. This can lead to false conclusions. A better name would be products.

    Probably the worst variable names that you can pick are uppercase O and lowercase L. This is because they look a lot like 0 and 1.

    Beware of using names that vary in small ways. How long does it take to spot the subtle difference between SomeMethodForEfficientHandlingOfFiles in one file, and SomeMethodForEfficientStorageOfFiles in another file? At first sight, these names look the same.

    Make Meaningful Distinctions

    Number-series naming is not a good way of intentional naming. Such names are non-informative, as they provide no clue of the intention for the author of the code.

    Let’s see the following example:
    <?php
    public function duplicateArray($arr1, &$arr2) {
      foreach ($arr1 as $key => $value) {
        $arr2[$key] = $value;
      }
    }
    
    This code would be much better to read when $arr1 and $arr2, would be renamed to$source and $destination.

    Use Names You Can Pronounce

    If you can’t pronounce a name, you can’t discuss it without sounding like an idiot. This actually matters, because a part of programming is social activity. There’s a good chance everybody knows a variable name off the top of their head that they can’t pronounce.

    Let’s pretend we have a variable name called $xsq, which is a very important abbreviation for your company. Imagine a conversation with a colleague:

    “Hey, what about that variable eks ess kjew?”

    “You mean the access queue?”

    Some developers will try to pronounce the variable as one word. Others will spell out the word.

    Use Searchable Names

    Names that consist of one letter have the problem that they can’t be located easily.

    The same applies to numeric constants. Numeric constants could be replaced with a constant variable. The number 8 could give you a lot of trouble when you’re searching your code.

    Replacing it with a constant MAX_BLOCKS_DISPLAYED makes it a lot easier, however.

    The only use case for single-letter names is for local variables inside short methods.

    Member Prefixes

    Don’t use member prefixes.

    Some developers have the habit of prefixing all private members with an underscore, for example. Don’t. Your classes and methods should be small enough that you don’t need any of these prefixes.

    As an alternative, you could use an IDE (or install a plugin) which colorizes variables based on their scope.

    Think of your code like it is a campground — leave it cleaner than you found it.

    Conclusion

    This is how you can create more meaningful names in your code.

    Feel free to leave a comment if you have any feedback, questions or want me to write about another programming related topic.

    This article was inspired by the book Clean Code written by Robert C. Martin, which I highly recommend you read.
    下载开源日报APP:https://opensourcedaily.org/2579/
    加入我们:https://opensourcedaily.org/about/join/
    关注我们:https://opensourcedaily.org/about/love/
  • 开源日报第479期:《抽卡 card》

    7 7 月, 2019
    开源日报 每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。
    今日推荐开源项目:《抽卡 card》
    今日推荐英文原文:《Do You Really Need That Framework?》

    今日推荐开源项目:《抽卡 card》传送门:GitHub链接
    推荐理由:在页面上使用 HTML+CSS+JS 来布置一张银行卡。尽管你很少需要在页面上摆上一张银行卡,但是这可以作为一个基础在这上面发展,比如说制作一个页面来管理自己真实拥有的那些银行卡,虽然它支持的银行卡样式国内都很少见,但是这一点正是可以发展的地方。
    今日推荐英文原文:《Do You Really Need That Framework?》作者:Jimmy M Andersson Jimmy M Andersson
    原文链接:https://medium.com/swlh/do-you-really-need-that-framework-394170ecef7e
    推荐理由:第三方库和框架的优缺点

    Do You Really Need That Framework?

    Third-party frameworks and libraries are (and will probably continue to be) a topic for heated debate. Some developers spend more time researching and evaluating a potential framework than they do developing stuff with it, some developers reach for new libraries as soon as they run into a problem. This article takes a look at some pros and cons of using third-party libraries and frameworks.

    Photo by Carlos Muza on Unsplash

    Framework vs Library

    First off, let’s start with a few words on what constitutes a framework or a library. The Internet is full of different definitions, some of them argue that the application of the Inversion of Control Principle is the main difference between the two, while some argue that a library is a collection of task-specific methods and a framework is a broad, ill-defined term that could be equal to a library, be a collection of libraries or something much more involved. For this article, the only thing we need to agree on is that both a library and a framework are collections of methods with the purpose of speeding up development and abstracting away common or complex calculations.

    The Pros

    Let’s start by looking at what advantages a framework / library can bring to our project if used correctly.

    PrototypingIf you’re doing a quick proof of concept and want to show that your idea is feasible rather than build a production grade application, a framework might be able get you up and running faster than if you were to write all the code yourself. If you manage to get others onboard and secure funding to take the idea to market, you can decide whether you’d like to keep the dependency or whether you’d like to develop your own, custom made solution.

    Faster DevelopmentA framework could come in handy if an application requires a huge amount of work just to lay the invisible foundation for anything tangible. Let’s say that you’re developing an application that displays a lot of different data using graphs. It may take developers quite some time to develop the code that display the different graphs, so you may choose to use a third-party framework to reduce the time it takes to show anything at all.

    This can be a competence and/or financial resources call as well. When implementing a service that relies on maps to display information to users, it probably makes much more sense to use an established maps SDK than to hire an entire department to create your own maps.

    Tested And Refined CodeThis one is only true in an ideal world, because the truth is that far from all libraries and frameworks that are available are updated / iterated on / supported in a timely manner. If a library has a steady user base and has been around for some time, chances are that it has been refined a couple of times. Bugs will have been reported, and a lot of them have hopefully been ironed out in recent versions. This is ultimately a judgement call, and it is one that should not be taken lightly when choosing whether or not to go with a framework.

    The Cons

    The cons of using any frameworks or libraries can pretty much be summarized using a single word: Risk.

    All external dependencies come at the cost of taking risks, and this is something that should be thoroughly considered before choosing whether or not to go with a framework for a production grade application.

    Lack Of SupportWe touched briefly on this is the advantages section, but from the perspective of using tested and matured code. On the other end of the spectrum, we find frameworks and libraries that are abandoned by their authors, and therefore don’t receive proper updates when languages evolve and weaknesses are found. You could end up building your application around a framework that will ultimately keep you from properly maintaining it, and that could cost you a ton of hours to replace it at a later time.

    Major API ChangesSince you don’t control the framework, you also don’t control the changes that are made to the API. You may end up in a situation where you need to migrate to a newer language version (especially true in the Swift world, where I reside most of the time). The authors of the framework may think that the breakpoint between the two language versions is a perfect time to make some bigger, breaking changes to the API, and you will end up having to repair your interactions with the framework on top of the migration. Not fun!

    Application SizeWhenever you’re using a framework, your application will add on the size of that dependency, even though you may only use a fraction of the functionality. This is even more important for developers who have a tendency to reach for libraries and frameworks whenever they feel a bit lazy or don’t want to spend a little bit of time thinking about how to solve a problem.

    So, Do You Really Need That Framework?

    This is ultimately a judgement call (of course), and it varies between situations.

    However, I personally feel like a lot of developers reach for libraries way too fast, before they’ve actually considered if they really need it.

    To me, the best way of deciding is to start out in the “I don’t need this dependency” camp, and try to convince myself that it will actually be worth it in the end. This can be done by pointing to savings in time and/or costs, or the fact that I may not have the competence to create and/or maintain the functionality.

    Note that “may not have the competence” should not be viewed as an easy out by saying “I can’t think of a way to do this right now, I’m gonna use that framework”. There’s a difference between skills I can learn with a few Google searches, and skills that require deep knowledge of a topic, knowledge that takes months or years of studies to acquire. Don’t let laziness make these decisions for you.
    下载开源日报APP:https://opensourcedaily.org/2579/
    加入我们:https://opensourcedaily.org/about/join/
    关注我们:https://opensourcedaily.org/about/love/
  • 开源日报第478期:《你是什么垃圾 trash-classify》

    6 7 月, 2019
    开源日报 每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。
    今日推荐开源项目:《你是什么垃圾 trash-classify》
    今日推荐英文原文:《Speed Up Your Python Code with Cython》

    今日推荐开源项目:《你是什么垃圾 trash-classify》传送门:GitHub链接
    推荐理由:兴许已经有人被垃圾分类搞疯了,即使真的招了一头猪来做垃圾分类员,但是猪能吃猪不能吃的分类方法有的时候也不管用,到了那种时候,兴许这个项目……也不会管用。你可以拍一张照片,然后这个项目会识别出上面可能有的一些垃圾,然后告诉你它们是什么垃圾。那么问题来了,抓了蟑螂的蟑螂屋究竟是什么垃圾呢?
    今日推荐英文原文:《Speed Up Your Python Code with Cython》作者:Lukas Frei
    原文链接:https://towardsdatascience.com/speed-up-your-python-code-with-cython-8879105f2b6f
    推荐理由:有利有弊,Python 在更加灵活的同时带来的弊端就是——你可能需要上个厕所才能得到结果,而 Cython 可能用来补足这个弊端

    Speed Up Your Python Code with Cython

    Introduction

    If you have ever coded in Python, you have probably spent more time waiting for certain code blocks to execute than you would like. While there are ways to make your code more efficient, it will most likely still be slower than C code, for instance. This boils down mainly to the fact that Python is a dynamic programming language and moves many things to runtime that C takes care of during compilation. Nevertheless, if you, like me, enjoy coding in Python and still want to speed up your code you could consider using Cython. While Cython itself is a separate programming language, it is very easy to incorporate into your e.g. Jupyter Notebook workflow. Upon execution, Cython translates your Python code to C, often times significantly speeding it up.

    Installing Cython

    In order to be able to use Cython you are going to need a C compiler. Thus, the installation process differs based on your current OS. For Linux, the GNU C Compiler (gncc) is usually present. For Mac OS, you can download Xcode to get the gncc. If you should be using Windows, the installation process is a little more complex. More info here on Cython’s GitHub. Once you have got your C compiler, all you need to run in your terminal is:
    pip install Cython
    

    How to Use Cython

    The easiest way to demonstrate Cython’s capabilities is through Jupyter Notebooks. To use Cython in our notebook, we are going to use IPython magic commands. Magic commands start with a percent sign and provide some additional features that are supposed to enhance your workflow. Generally, there are two types of magic commands:
    1. Line magics are denoted by a single ‘%’ and only operates on one line of input
    2. Cell magics are denoted by two ‘%’ and operate on multiple lines of input.
    Let’s get started: First, in order to be able to use Cython, we have to run:
    %load_ext Cython
    
    Now, whenever we want to run Cython in a code cell, we have to first put the following magic command into the cell:
    %%cython
    
    Once you have done that, you are good to go and able to start coding in Cython.

    How much faster is Cython?

    How much faster Cython is compared to regular Python code really depends on the code itself. For instance, should you be running computationally expensive loops with many variables, Cython will vastly outperform regular Python code. Recursive functions will also tend to make Cython a lot faster than Python. Let’s demonstrate this with the Fibonacci sequence. This algorithm, to put it simply, finds the next number by adding up the previous two. Here is what that might look like in Python:
    def fibonacci(n):
    
        if n < 0:
            print("1st fibonacci number = 0")
    
        elif n == 1:
            return 0
    
        elif n == 2:
            return 1
    
        else:
            return fibonacci(n-1) + fibonacci(n-2)
    
    Let’s make Python work: As you can see, finding the 39th number in the sequence took 13.3 seconds to compute. Wall time here refers to the total time elapsed from start to finish of the call to the function. Let’s define the same function in Cython. What’s going on here? As you can see, we are using some cell magic up top that allows us to use Cython in this cell. I am going to explain what the ‘-a’ option does shortly. Then, we basically take the same code as we did above except for the fact that now we have the ability to make use of static type declarations and define n to be of type integer. As you can see, by adding ‘-a’ after the magic command, we received annotations that show us how much Python interaction there is in your code. The goal here would be to get rid of all yellow lines and have them have a white background instead. In that case, there would be no Python interaction and all code would run in C. You can also click on the ‘+’ sign next to each line to see the C translation of your Python code. How much faster is that code? Let’s find out: In this case, Cython is around 6.75 times faster than Python. This clearly demonstrates the time-saving capabilities of utilizing Cython where it provides the most improvement over regular Python code.

    Additional Options

    In case you already know C, Cython also allows for the access of C code that the makers’ of Cython have not yet added a ready-to-use declaration for. Using the following code, for instance, you could generate a Python wrapper for a C function and add it to the module dict.
    %%cython
    
    cdef extern from "math.h":
        cpdef double sin(double x)
    
    Cython proves many additional capabilities, such as parallelism, which are all very neatly described in its documentation that you can find here.

    Conclusion

    If you should, at times, run into the issue of having to wait for too long for your Python code to execute, Cython provides a really neatly integrated and efficient way to speed up your code. On top, it offers many capabilities to further optimize your code should you be a little more familiar with C. I would definitely recommend to thoroughly check out the documentation. If you should have any suggestions or remarks, feel free to reach out to me.
    下载开源日报APP:https://opensourcedaily.org/2579/
    加入我们:https://opensourcedaily.org/about/join/
    关注我们:https://opensourcedaily.org/about/love/
  • 开源日报第477期:《名言警句 motivate》

    5 7 月, 2019
    开源日报 每天推荐一个 GitHub 优质开源项目和一篇精选英文科技或编程文章原文,坚持阅读《开源日报》,保持每日学习的好习惯。
    今日推荐开源项目:《名言警句 motivate》
    今日推荐英文原文:《Tidying-Up With Iwan Kurniawan: Clean Code》

    今日推荐开源项目:《名言警句 motivate》传送门:GitHub链接
    推荐理由:How to get a motivational quote?
    Step one: install python3 and git.
    Step two: get this repo.(git clone balabala… .gif)
    Step three: use this command.
    motivate
    
    "When something is important enough, you do it even if the odds are not in your favor."
            --Elon Musk
    

    今日推荐英文原文:《Tidying-Up With Iwan Kurniawan: Clean Code》作者:AccelByte Inc AccelByte Inc
    原文链接:https://medium.com/accelbyte-inc/tidying-up-with-iwan-kurniawan-clean-code-7035876454a3
    推荐理由:书写简单代码的一些 tips

    Tidying-Up With Iwan Kurniawan: Clean Code

    What a software engineer does in a nutshell is that we create applications and/or products with a lot of features within. When our products are used by many clients, most of the time they would request several changes that are tailored to what they need. The changes could be in the form of a customization of the features that are already present or even a request to add new features. This can prove to be a challenge, especially when we have more than two clients, requesting different customization.

    Our product consists of several applications, therefore every customization means another effort to move or tweak certain applications or features which we call context switching. In this case, every engineer is required to understand the code of all applications and/or projects. It seems impossible at first, however, the solution for is one coding fundamental that often overlooked, which is writing clean code.

    Take a look at the following code, is this code clear enough for you to understand?

    There are several questions that might pop-up in your head as you read them. What does the pay function is purchasing? Whiskey Tango Foxtrot does const u and i mean? These questions require several scroll-up so we can understand the meaning — which is time-consuming. This will be frustrating if you are on the receiving end of the context switching. This means that by merely finishing your task faster is not worth the technical debt that will bother us in the future.

    Luckily, AccelByte has implemented the habit of writing clean code from the start. This is one of the core cultural tenants for the engineering teams since implementing a clean-code approach will significantly improve our productivity as an engineer.

    So, can I see an example of a Clean Code?

    From the nightmarish example above, I have rewritten them into a better, cleaner, and much easier to understand code.

    Now with this code, it is known that this function will work for paying in-game items, in which the function requires two parameters namely userId and itemId. For the function itself, we now understand that there is an instruction to make an order and to pay for the order. Now, this code is efficient, much more understandable and sparks joy.

    Well, it ain’t stupid if it works… right?

    We all know the fundamentals of a clean code — it should be easy to understand plus easy to modify or change. But why should you care? Well, your code is the prime representation of your programming skill and your train of thought — keep this in mind because your code will be read by other engineers in your team. Here are reasons why you should write a clean code:
    1. You will be free from unnecessary confusion in the future. You wouldn’t need to guess what that line means or read your code all the way through only to understand what it means
    2. It will be easier for the team to assist you in finishing your tasks. What if you’re on a leave but we forgot a thing or two? Surely, your team would love to help you out to make sure it is finished on time — but I know they wouldn’t love reading a messy code!
    3. What if you encountered a bug? The answer is obvious — debug them! Clean code with a well explanatory error message will save your time in debugging, now isn’t that what we all want?
    4. Precaution is better than cure. By investing your effort in writing a clean code, we are taking the precautious approach in avoiding technical debt in the future.
    Great, so where do we begin?

    There are two mantras that you need to internalize so that you will soon be able to write clean code with ease. They are the DRY mantra and KISS mantra — let me break them down on the following section:
    1. D.R.YDRY is an acronym for “Don’t Repeat Yourself”. When you write your code, sometimes we would like to create the same or similar code twice or more in a separate file. You would copy and then paste the code — it will be more difficult to refactor if there are changes in the future. Instead of making the same code repeatedly, it would be so much better if we make our code more modular.
    2. K.I.S.SKISS is an acronym for the design principle “Keep It Simple, Stupid!”. The computer can only understand binary, it’s either 0 or 1. Therefore humans created a programming language so we can give proper instructions in a way that we could understand, and is readable by the computer. Therefore, we should write our code in a simple and straight manner that is easily understandable by human beings.

      We also need to keep our methods small, each method should never be more than 50 lines! One way to do this is by assigning one method to only solve one small problem instead of many use cases. When you realize you have a lot of conditions in the method, break them into smaller methods. This will make your code easier to read and maintain and also you can find bugs a lot faster.

    BONUS: Extra tips for extra clean code!

    • Review your code yourself Keep in mind that perhaps one day you need to make some changes in the code that you are currently working on. Will it be easy to change it by then? Will you understand the meaning of the code immediately? Or perhaps you still need to see the previous code that uses that code? If you feel the need to see the previous code when reading the code you are currently working on — it means that it isn’t clean enough.
    • Review your code with your colleagues Opinion from your colleagues is very important for it helps you to improve your code and they can notify you when something is missing or seems to be out of place.
    • Proper naming conventions Every language has its own naming conventions, or perhaps your company has its own naming conventions. Make sure that you are using the appropriate naming conventions to avoid problems in the future.
    • Keep an eye on your formatting Formatting (such as block indentations, statements, column limit, comments, and many others) is very important for a clean code, it’s made easier to read:

    A. Braces

    Use Braces for all control structures (such as: if, else, for, etc). The first statement of a non-empty block must begin on its own line. Use the following link as a reference.

    There’s a braces condition that can be ignored + Ternaries operation + ‘If’ statement without ‘else’ statement

    B. Column limit

    A line of code should be less than 80–120 characters to make it easier to read, but there are some condition can’t follow this rule like long URL and specific commands.

    C. Comments

    • For multi line comments, you should use /** … */
    • You can use // for single line comment, make sure you put it above the subject of the comment.
    • Add an empty line before the comment unless it’s on the first line of the block
    • Start all comments with space.

    D. Block Indentation

    There are many helpful sites that can assist you in creating a more readable code, if you are using JavaScript, you can use Prettier, for Python you can use Black. There are many code-formatter that you can search and use to maximize the readability of your code.

    Ask yourself… does this code spark joy?

    Breathe in, breathe out. Congratulations! Now we have reached the end of the page, keep in mind that writing a clean code will not only benefit yourself but also your team as a whole. A code is a representation of your skill and your train of thoughts — start writing cleaner from now, eventually, it will be a habit that will increase your productivity in the future.
    下载开源日报APP:https://opensourcedaily.org/2579/
    加入我们:https://opensourcedaily.org/about/join/
    关注我们:https://opensourcedaily.org/about/love/
←上一页
1 … 139 140 141 142 143 … 262
下一页→

Proudly powered by WordPress