当前位置: 首页 > news >正文

三个“清洁代码”技巧将使您的开发团队效率提高 50%

c1a28c244d456ac52aac1caa0f0dea35.png

如果我必须从软件工程最佳实践的圣经“清洁代码”中选择一点,我们就是作者。阅读与写作的时间比例远远超过 10:1。

50755aee1a5796f0f9687157a1351cf5.png

再读一遍。慢慢地。作为编写新代码的一部分,我们不断地审查旧代码。

由于我们花费大量时间阅读旧代码,因此对我们和我们的团队来说,投入一点使其简单易懂可能是个好主意。

尽管我建议阅读整本书,但我发现以下三个想法很容易获胜,它们可以极大地提高团队的生产力、效率,最重要的是——减少挫败感:

  1. 使用好名字

1.1。意图揭示:变量、函数或类的名称应该告诉你它为什么存在,它做什么,以及它是如何使用的。如果名称需要注释,则该名称不会显示其意图。

1c9b806be53ad74c39287bbc2ca8e547.png

1.2. 做出有意义的区分:不要试图满足编译器,如果名称必须不同,那么它们也应该意味着不同的东西。假设您有一个Product类。如果您有另一个名为ProductInfoProductData的名称,则您已经使名称不同,而没有使它们的含义有所不同。

e1e93828518468114df32c942a4e0a7b.png

2. 避免函数副作用

函数应该只做一件事。并做好。

考虑到这一点,我们应该避免对我们的功能产生副作用。副作用是谎言。你的函数承诺做一件事,但它也做其他隐藏的事情。它可能会对自己类的变量进行意外更改,或者可能会修改传递给函数或系统全局变量的参数。在任何一种情况下,它们都是狡猾和破坏性的错误,通常会导致奇怪的时间耦合和顺序依赖。

因此,在下面的示例中,我不希望该函数初始化会话,而只是验证密码。

8390264367ea241dd45488669fbf95e4.png

3. 仅在必要时写注释

887e10915b3fb80df6475485c4496481.png

3.1. 用代码解释自己,而不是注释:编写注释的更常见动机之一是糟糕的代码。你更想看哪个?
这个:

52190b3e43b7c4f53778a29305e60f9b.png

或这个?

9da0f3a72507fd1c173daeb327f2f5f5.png

更多属于“试图弥补不良代码”类别的不良评论示例:

  • 多余的注释——阅读时间可能比阅读代码要多。

  • 注释掉的代码——请不要这样做。其他看到的人都没有勇气删除它。他们会认为它的存在是有原因的,并且太重要而无法删除。

  • 信息过多——不要在评论中加入有趣的历史讨论或不相关的细节描述。

3.2 注释错误:不总是,也不是故意的,但太频繁了。注释越旧,离它描述的代码越远,它就越有可能是完全错误的。原因很简单。程序员实际上无法维护它们。

6bc3032f63be7e8c9f94c747cb04dd85.png

代码会不时更改,并且在提交更改之前也可能由团队成员进行审查。不幸的是,评论有时会落在裂缝之间,在过去被遗忘,仍然在解释一些不存在的东西。此外,代码块可以从这里移动到那里,而它们的注释并不总是跟随并成为准确性不断降低的孤立模糊。

62d24fde61034199090b588a1541fcc3.png


可以指出,程序员应该有足够的纪律性,以使评论保持高度的修复、相关性和准确性。我同意,他们应该。但我宁愿将精力用于使代码如此清晰和富有表现力,以至于它首先不需要注释。
真相只能在一个地方找到:代码。

总而言之,如果您想显着提高团队的生产力,请记住并应用以下三个“干净代码”原则:

  1. 使用好名字

  2. 避免函数副作用

  3. 仅在必要时发表评论


【更多阅读:禅与计算机程序设计艺术】

  1. 清洁代码之道:一份实用关于如何编写和维护干净整洁的好代码的的方法 The Art Of Clean Code

  2. 干净的代码——一种实用的方法

  3. To Be A Good Programmer? All it takes is these 10 habits !

  4. 什么是微服务?

  5. NoSQL and LSM Tree

  6. API 网关如何工作?

  7. 软件架构图和模式

  8. 来自软件架构大师的 4 个真理

  9. 程序员架构修炼之道:软件架构设计的37个一般性原则

  10. 软件架构设计的核心:抽象与模型、“战略编程”

  11. 软件架构的本质

  12. 快看软件架构风格总结: 各种历史和现代软件架构风格的快速总结

  13. 软件架构师成长之路: Master Plan for becoming a Software Architect

  14. 软件架构设计杂记:  好作品是改出来的,好的代码是不断重构打磨出来的, 心性是历经艰难困苦修炼出来的

Three “Clean Code” tips that will make your dev team 50% more efficient

dc0afed2c72e2bc19bc6df5f5b0f8ac4.png

If I had to choose one point from the “Clean Code”, the bible of software engineering best practices, WE ARE AUTHORS would be it. The ratio of time spent reading vs writing is well over 10:1. Read that again. Slowly. We are constantly reviewing old code as part of the effort to write new code.

Since we spend so much time reading old code, it might be a good idea to invest a bit in making it simple and easy to understand, for us and our team.

Although I recommend reading the entire book, I find that the following three ideas are easy wins that can make a huge difference in your team’s productivity, efficiency, and most importantly — frustration reduction:

  1. Use Good Names

1.1. Intention Revealing: The name of a variable, function, or class, should tell you why it exists, what it does, and how it is used. If a name requires a comment, then the name does not reveal its’ intent.

80cccbc8f234fe3d67d3ec611a2f860e.png

1.2. Make Meaningful Distinctions: Don’t try to satisfy the compiler, If names must be different, then they should also mean something different. Imagine that you have a Product class. If you have another called ProductInfo or ProductData, you have made the names different without making them mean anything different.

2. Avoid Functions Side Effects

FUNCTIONS SHOULD DO ONE THING. THEY SHOULD DO IT WELL. THEY SHOULD DO IT ONLY.

With that in mind, we should avoid having side effects on our functions. Side effects are lies. Your function promises to do one thing, but it also does other hidden things. It can be making unexpected changes to the variables of its own class, or maybe modifying the parameters passed into the function or to system globals. In either case, they are devious and damaging mistruths that often result in strange temporal couplings and order dependencies.

Accordingly, in the example below, I would not expect the function to initialize the session, only to verify the password.

84c7db0b163fce66b584dad9fb011224.png

3. Comment Only When Necessary

3.1. Explain Yourself in Code, Not Comments: One of the more common motivations for writing comments is bad code. Which would you rather see?
This:

21fcc8d1e2249ffb665d667adc5a9c35.png

Or this?

603d0de79a1466d4f81a9b92bdeadc32.png

Some more examples for bad comments that fall into the category of “trying to make up for bad code”:

  • Redundant comments — it might take more time to read than the code.

  • Commented-out code — please don’t do this. Others who see that won’t have the courage to delete it. They’ll think it is there for a reason and is too important to delete.

  • Too Much Information — Don’t put interesting historical discussions or irrelevant descriptions of details into your comments.

3.2 Comments Lie: Not always, and not intentionally, but too often. The older a comment is, and the farther away it is from the code it describes, the more likely it is to be just plain wrong. The reason is simple. Programmers can’t realistically maintain them.
Code changes from time to time and might also be reviewed by team members before the change is committed. Unfortunately, comments sometimes fall between the cracks, forgotten in the past, still explaining something that just isn’t there. In addition, chunks of code can move from here to there, while their comments don’t always follow and become orphaned blurbs of ever-decreasing accuracy.
It is possible to make the point that programmers should be disciplined enough to keep the comments in a high state of repair, relevance, and accuracy. I agree, they should. But I would rather that energy go toward making the code so clear and expressive that it does not need the comments in the first place.
Truth can only be found in one place: the code.

To sum things up, if you want to dramatically improve your team’s productivity, remember and apply these three “clean code” principles:

  1. Use Good Names

  2. Avoid Functions Side Effects

  3. Comment Only When Necessary

But there's always room to learn. No one writes clean code from the beginning. Recently, X-Teamers discussed their most important principles to keep their code clean, and we decided to share the best ones with the world.

Clean Code Principles

Clean code doesn't rely on language-specific rules. Instead, it relies on language-agnostic principles agreed upon by the developer community. As such, even though the initial question on our Slack channel was about how to keep your JavaScript / TypeScript code clean, X-Teamers replied with some of the general design principles of clean code.

KISS: Keep It Simple Stupid. A design principle originating from the U.S. Navy that goes back to 1960 already. It states that most systems should be kept as simple as possible (but not simpler, as Einstein would have said). Unnecessary complexity should be avoided. The question to ask when you're writing code is "can this be written in a simpler way?"

DRY: Don't Repeat Yourself. Closely related to KISS and the minimalist design philosophy. It states that every piece of knowledge (code, in this case) must have a single, unambiguous, authoritative representation within a system (codebase). Violations of DRY are referred to as WET: We Enjoy Typing, Write Everything Twice, Waste Everyone's Time.

YAGNI: You Aren't Gonna Need It. A developer should not add functionality unless deemed necessary. YAGNI is part of the Extreme Programming (XP) methodology, which wants to improve software quality and increase responsiveness to customer requirements. YAGNI should be used in conjunction with continuous refactoring, unit testing, and integration.

Composition over inheritance: Not an acronym, sadly. It's a principle where you design your types over what they do instead of over what they are. It's explained in more detail in this video. One of the ways to implement this principle is with the Object.assign() method in ES6.

Composition is favored over inheritance by many developers, because inheritance forces you to build a taxonomy of objects early on in a project, making your code inflexible for changes later on.

Favor readability: It's not because a machine can read your code that another human can. Particularly when working with multiple people on a project, always favor readability over conciseness. There's no point in having concise code if people don't understand it.

There are many ways to make your code more readable. Two examples are placing common numbers into well-named constants (e.g. const CACHE_TIME = 200;) and creating long names instead of shorter ones (e.g. userHasFormAccess over canAccess, which doesn't tell as much).

Practice consistency: This is arguably the overarching principle of all clean code principles. If you decide to do something a certain way, stick to it throughout the entire project. If you have no choice but to move away from your original choice, explain why in the comments.


Of course, this is by no means a comprehensive list. There's so much more to clean code. In fact, if you want an excellent book on clean code, we recommend The Art of Readable Code by D. Boswell and T. Foucher.

Want more? Read about programming best practices to improve the way you write code.


It doesn’t matter if you are a beginner or an experienced programmer, you should always try to become a good programmer (not just a programmer…). Remember that you are responsible for the quality of your code so make your program good enough so that other developers can understand and they don’t mock you every time to understand the messy code you wrote in your project.

What Makes a Clean Code: Before we discuss the art of writing clean and better code let’s see some characteristics of it…

  1. Clean code should be readable. If someone is reading your code they should have feeling of reading a poetry or prose.

  2. Clean code should be elegant. It should be pleasing to read and it should make you smile.

  3. Clean code should be simple and easy to understand. It should follow single responsibility principle (SRP).

  4. Clean code should be easy to understandeasy to change and easy to taken care of.

  5. Clean code should run all the tests.

“Clean code is simple and direct. Clean code reads like a well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.”
-Grady Booch (Author of Object-Oriented Analysis and Design with Applications)

How to Write Clean and Better Code?

1. Use Meaningful Names

You will be writing a lot of names for variables, functions, classes, arguments, modules, packages, directories and things like that. Make a habit to use meaningful names in your code. Whatever names you mention in your code it should fulfill three purposes…what it doeswhy it exists and how it is used. For Example:

int b; // number of users.

In the above example, you need to mention a comment along with the name declaration of a variable which is not a characteristic of a good code. The name that you specify in your code should reveal it’s intent. It should specify the purpose of a variable, function or methods. So for the above example, a better variable name would be:- int number_of_users. It may take some time to choose meaningful names but it makes your code much cleaner and easy to read for other developers as well as for yourself. Also, try to limit the names to three or four words.

2. Single Responsibility Principle (SRP)

Classes, Functions or methods are a good way to organize the code in any programming language so when you are writing the code you really need to take care that how to write a function that communicates it’s intent. Most of the beginners do this mistake that they write a function that can handle and do almost everything (perform multiple tasks). It makes your code more confusing for developers and creates problems when they need to fix some bugs or find some piece of code. So when you are writing a function you should remember two things to make your function clean and easy to understand…

  1. They should be small.

  2. They should do only one thing and they should do it well.

The above two points clearly mention that your function should follow single responsibility principle. Which means it shouldn’t have nested structure or it should not have more than two indent level. Following this technique make your code much more readable and other developers can easily understand or implement another feature if your function fulfills a specific task.
Also, make sure that your function should not have more than three arguments. More arguments perform more tasks so try to keep the arguments as less as possible. Passing more than three arguments makes your code confusing, quite large and hard to debug if any problem would be there. If your function has try/catch/finally statement then make a separate function containing just the try-catch-finally statements.
Take care of your function name as well. Use a descriptive name for your function which should clearly specify that what it does.

Example:

function subtract(x, y) {
    return x - y;
}

In the above example the function name clearly shows that it’s purpose is to perform subtraction for two numbers, also it has only two arguments. Read more about writing a good function from the link 7 Common Programming Principles That Every Developer Must Follow and SOLID Principle.

3. Avoid Writing Unnecessary Comments

It’s a common thing that developers use comments to specify the purpose of a line in their code. It’s true that comments are really helpful in explaining the code what it does but it also requires more maintenance of your code. In development code move here and there but if the comment remains at the same place then it can create a big problem. It can create confusion among developers and they get distracted as well due to useless comments. It’s not like that you shouldn’t use comments at all, sometimes it is important, for example…if you are dealing with third party API where you need to explain some behavior there you can use comments to explain your code but don’t write comments where it’s not necessary.
Today modern programming languages syntax are English like through and that’s good enough to explain the purpose of a line in your code. To avoid comments in your code use meaningful names for variables, functions or files.

Good code is its own best documentation. As you’re about to add a comment, ask yourself, “How can I improve the code so that this comment isn’t needed?” Improve the code and then document it to make it even clearer.
-Steve McConnell

4. Write Readable Code For People

A lot of people especially beginners make mistake while writing a code that they write everything in a single line and don’t give proper whitespace, indentation or line breaks in their code. It makes their code messy and difficult to maintain. There’s always a chance that another human will get to your code and they will have to work with it. It wastes other developers’ time when they try to read and understand the messy code. So always pay attention to the formatting of your code. You will also save your time and energy when you will get back to your own code after a couple of days to make some changes. So make sure that your code should have a proper indentation, space and line breaks to make it readable for other people. The coding style and formatting affect the maintainability of your code. A software developer is always remembered for the coding style he/she follow in his/her code.

// Bad Code

class CarouselRightArrow extends Component{render(){return ( <a href="#" className="carousel__arrow carousel__arrow--left" onClick={this.props.onClick}> <span className="fa fa-2x fa-angle-left"/> </a> );}};

// Good Code

class CarouselRightArrow extends Component {

  render() {

    return (

      <a

        href="#"

        className="carousel__arrow carousel__arrow--left"

        onClick={this.props.onClick}

      >

        <span className="fa fa-2x fa-angle-left" />

      </a>

    );

  }

};

Code formatting is about communication, and communication is the professional developer’s first order of business.
-Robert C. Martin (Uncle Bob)

5. Write Unit Tests

Writing Unit test is very important in development. It makes your code clean, flexible and maintainable. Making changes in code and reducing bugs becomes easier. There is a process in software development which is called Test Driven Development (TDD) in which requirements are turned into some specific test cases then the software is improved to pass new tests. According to Robert C. Martin (Uncle Bob), the three laws of TDD demonstrate…

  1. You are not allowed to write any production code unless it is to make a failing unit test pass.

  2. You are not allowed to write any more of a unit test than is sufficient to fail, and compilation failures are failures.

  3. You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

fbfcd6df816593138c6d87d493040c81.png

After I jumped on board the unit testing bandwagon, the quality of what I deliver has increased to the point that the amount of respect I get from my colleagues makes me feel awkward. They think I’m blessed or something. I’m not gifted or blessed or even that talented, I just test my code.
– Justin Yancey, Senior Systems Development Engineer, Amazon

6. Be Careful With Dependencies

In software development, you really need to be careful about your dependencies. If possible your dependencies should always be a singular direction. It means….let’s say we have a kitchen class which is dependent on a dishwasher class. As long as the dishwasher doesn’t also dependent on the kitchen class this is a one-directional dependency. The kitchen class is just using the dishwasher but the dishwasher doesn’t really care and anyone can use it. It doesn’t have to be a kitchen. This example of one-directional dependency is easier to manage however it’s impossible to always have one-directional dependency but we should try to have as many as possible. When dependency goes in multiple directions, things get much more complicated. In bidirectional dependency both the entities depend on each other, so they have to exist together even though they are separate. It becomes hard to update some systems when their dependencies don’t form a singular direction. So always be careful about managing your dependencies.

7. Make Your Project Well Organized

This is a very common problem in software development that we add and delete so many files or directories in our project and sometimes it becomes complicated and annoying for other developers to understand the project and work on that. We agree that you can not design a perfect organization of folders or files on day one but later on, when your project becomes larger you really need to be careful about the organization of your folder, files, and directories. A well-structured folder and file make everything clear and it becomes easier to understand a complete project, search some specific folder and make changes in it. So make sure that your directory or folder structure should be in an organized manner (Same applies for your code as well).


10+ Java tips for cleaner code

“Clean code is simple and direct. Clean code reads like well-written prose“
Grady Booch

Clean code is code that is easy to understand, easy to change and easy to maintain. A developer’s work is not finished when the application operates as expected but when the code is so simple and clean that anyone can use it, change it and maintain it without reading any documentation. But have you thought about what can make your Java code cleaner? In this article, we will discuss some of the most important clean code habits a Java developer should adopt.

1. Use proper and consistent naming conventions

One of the most important tips for code readability in any language is naming. How you name things has a tremendous impact on the quality of your code, as everything from variables to classes to interfaces are identified by their names in the code. These names should be descriptive, self-explanatory and follow the Java naming conventions as much as possible. So, set proper naming conventions for each class, method, variable etc. If other developers are working with you on the same project, they should also follow these conventions to maintain consistency. Don’t assign random names just to please the compiler, but use names that can later be understood by you, your teammates, and anyone else involved in maintaining the project. For example:

Can you understand what this code does and why you need to have it in your codebase at all?

public double DO_Calc (double a) {
    return x * a * a;
}

But look at the following example, where the names have been changed. You can immediately see that this code calculates the area of a circle.

public double getAreaOfCircle(double radius) {
    return Math.PI * radius * radius;
}

Also, I’d say that you don’t even have to decide the conventions. Just follow Java’s conventions and standards, not blindly 😊, but try to keep up with them. For example, in Java there are the following conventions:

✔ For variables and methods, the convention is to write in lower camelCase e.g.:

  • private String movieTitle;

  • equalsIgnoreCase(String anotherString)

✔ For constant variables, use screaming (upper-case) snake case.
e.g.: PI_VALUE

✔ For classes, interfaces, enums, records, annotations, use PascalCase
e.g.: public class CodeEncryptor

✔ For packages and property files, use lower dot case
e.g.:

  • java.net.http

  • com.company.splitter

  • application.properties

2. Do not leave catch blocks empty, with no reason

This advice may cost you many hours of debugging, if you don’t follow it. Please do not leave the catch blocks empty. Not only that, write a proper and meaningful message, including the exception. If you do not, when an exception occurs (and it will), the program will not display anything, making debugging harder and time-consuming for no reason.

3. Use correct access modifiers and encapsulation

Learn about access modifiers and how they can be used. Java supports four access modifiers you can use to define the visibility of classes, methods and attributes. Each modifier specifies a different level of accessibility, and you can use only one modifier per class, method, or attribute.

Starting from the most to the least restrictive, these modifiers are:

  • Private ➡ no access outside the class. A private entity can only be accessible from within the class.

  • Default ️➡ Whenever a specific access level is not specified, then it is assumed to be ‘default’. The scope of the default level is within the package.

  • Protected ➡ ️package scope. A protected entity is also accessible outside the package through inherited class or child class.

  • Public ➡ accessible from everywhere, etc.

Generally, the best practice is that you should always use the most restrictive modifier that still allows you to implement your business logic.

For example all class members and internal methods that shouldn’t be called from external classes should be private, as you should not expose these variables outside of the class they reside. This practice is recommended to preserve encapsulation, one of the fundamental concepts of OOP. Although it’s one of the first concepts one learns when reading about object-oriented programming, many developers still do not properly assign access modifiers, even though they know how it affects their code and simply prefer to keep everything public as it’s easier to make changes.

4. Extract to classes and methods and encapsulate business logic

If you deal with methods with 1000+ lines of code where everything is unorganized and there are no rules to speak of, try to simplify the code by extracting methods and encapsulating the business logic. You can extract this complex logic into a function or a class. This way, instead of thousands of lines of code, you have many meaningful methods to call, when needed. For example, IntelliJ provides an easy way to extract methods. It lets you take a code fragment that can be grouped, and move it into a separate method. Then you can replace the old code with a call to the method, making your code cleaner. So try to split your business properly and make right use of encapsulation so that people who take over can understand the business quickly, even if there is no documentation.

5. Encapsulate method parameters

Your methods should not have too many parameters, generally no more than 3 or 4 (there is no clear limit). Uncle Bob Martin in Clean Code for instance, recommends a maximum of 3 parameters.

When your method has too many parameters, it’s often better to encapsulate the related parameters in a single object that contains all the required fields.

For example, let’s look at the following sample, which is to be avoided.

public void insertBook(long id, String isbn, String title, String year, String author, Category category, String comments) {
    //…code
}

You could write an object instead, which can be used as a model in some way.

public class Book {
    private Long id;
    private String isbn;
    private String title;
    private String year;
    private String author;
    private Category category;
    private String comments;
}

That’s a lot better. Suppose you want to add data to a database and your method receives some parameters which will later be used in a query. If you added a query condition in the future, you would have to change the method’s parameter list, in the first case. Encapsulate an object by passing a Book object that contains all the required fields, and no matter how many query conditions you add in the future, you only need to add fields to the object and not change the method. This way, you can easily accomplish the task with this object and make your code cleaner.

6. A better way to decide if a collection type is empty

The traditional way for determining whether a collection is empty is to check if it is null and if it contains any elements. There’s no problem with the following code, but it can be rewritten more clearly.

if (list == null || list.size() == 0) {
    return null;
}

For example, you may use Apache commons-collections CollectionUtils.isEmpty, which more clearly expresses what you actually intend.

7. Return Empty Collections instead of returning Null elements

If a method returns a collection that has no value, then do not return null elements. Return an empty collection instead, as this is a much better practice. The reason is that null elements need extra handling and work afterwards. So in this way you skip this handling, saving the efforts needed for testing on Null Elements. Besides, it’s not very nice to force the caller(s) to execute this NULL judgment because you were lazy :P.

8 You may use Lombok

Lombok is a java library that automatically plugs into your editor and build tools, spicing up your Java, so that you do not need to write the boring getters and setters or equals methods again. It just needs one annotation in your class to insert this functionality. So, in this way, you can automate many of the boring tasks and reduce boilerplate code. Of course, not everyone likes Lombok and you should not follow this advice blindly, but there’s a chance here to reduce boilerplate code, by omitting getters, setters, toString, etc. which is a good thing and should be noted.

9 Don’t replace existing libraries with your own tools

There are 2 reasons for this. The first and simplest is, why spend all this time creating a tool that already exists? That’s what libraries are for and most of the tools you need are already included in classes inside the jar package you invisibly introduced, such as String, Assert, IO upload file, Bigdecimal, and so on. The second reason is that these libraries are well tested by thousands of developers. If you write your own code, you may introduce your own bugs and unnecessary classes and methods and you should be responsible for maintaining it. Of course, I’m not saying that you should never write your own code if you can’t find what you need or if you need something better than the existing tools, but be careful when making that decision.

10 Write comments and make them meaningful

I don’t believe in 100% self-documenting code. Comments do have a purpose. You can use them to give a summary of certain parts of your code, or provide additional information to help someone understand concepts that cannot be found directly in the code itself. Comments should be easily readable even for non-technical people such as managers, quality assurance engineers etc. Your code can never be so objectively clean that not a single comment is needed. But, don’t clutter your code with comments that aren’t useful.

Eg.: Of course, the below comment is bad, because everyone can understand this without reading the comment.

// this code is used to add number1 and number2
int result = number1 + number2

This Javadoc is also bad as it does not add any more information. It’s not descriptive and it’s better not to write it or just add a nice description instead. You’ll also get a bunch of warnings from your IDE.

/**
 * This method is used to add a movie
 *
 * @param nameOfMovie The name of the movie
 * @param releaseYear The release year
 * @param durationInMinutes The duration of the movie in minutes
 */
public void addMovie(String nameOfMovie, int releaseYear, int durationInMinutes) {
    // code...
}

Finally, it is bad practice to leave your old code behind by commenting it out, for fear of losing your old logic. Do not comment out big chunks of unused code. This code may never be read or used again and what it does is just bloat your existing codebase. That’s what source control is for, where you have the complete history of the changes you make to a project, so you can revisit your old code if you’d like. I’ve been guilty of this too, many times and I understand the feeling, but stop leaving unused code behind, unless you have a very good reason.

Good practice

One good practice for actually omitting comments is to extract variables to explain things and remove some of the not so helpful comments.

eg.: Consider the following expression which is hard to understand and needs to be commented out.

// if platform is MacOs and browser is IE so something
public void renderBanner() {
    if ((platform.toUpperCase().indexOf("MAC") > -1) &&
         (browser.toUpperCase().indexOf("IE") > -1)) {
    
        // do something    }
}

If you extract the parts of the expression in separate variables that are self-explanatory, you may omit the comment, but I would also leave the comment in here, because if someone reads the comment and decides that this function is not what he/she needs, he/she can escape early and don’t read the continuation of the code.

public void renderBanner() {
    private final boolean platformIsMacOs = platform.toUpperCase().indexOf("MAC") > -1;
    private final boolean browserIsIE = browser.toUpperCase().indexOf("IE") > -1;    if (platformIsMacOs && browserIsIE) {
        // do something
    }
}

11 Keep an eye on IDE warnings

Check for warnings in your IDE. Warnings may be potential bugs or your IDE may just wants to alert you that your code can be optimized. IDES like IntelliJ can perform these optimizations with one click, which will not only reduce IntelliJ’s whining but will also make your code better.

12. In later Java, versions you may use underscores for oversized numbers

As a simple bonus tip, this simple but useful feature was introduced in Java 7 and it can help to make your lengthy numbers more readable. So instead of writing in the old way, like this:

int num = 1000000000;

You can assign a lengthy number like this:

int num = 1_000_000_000;

What’s next?

相关文章:

  • create® 3入门教程-使用多个机器人
  • Redis实战篇一 (短信登录)
  • Java高级——Class文件及解析
  • 高效代码静态测试工具Klocwork 2022.3版本快讯
  • java毕业设计艾灸减肥管理网站Mybatis+系统+数据库+调试部署
  • 【day12】【洛谷算法题】-P5712Apples-刷题反思集[入门2分支结构]
  • 【C语言进阶考试】你是否真正学懂了C语言
  • JS手写章节(1)—手写实现call、apply、bind
  • 零基础小白学Node-RED(04):仪表板
  • 【正点原子I.MX6U-MINI应用篇】2、点亮开发板的LED
  • 【C++】第五章 数组:一维数组/二维数组
  • 阿里云大数据开发一面面经,已过,面试题已配答案
  • 自定义模块和第三方模块,cnmp
  • 【正点原子I.MX6U-MINI应用篇】3、Framebuffer应用编程,操作屏幕
  • 区间预测 | MATLAB实现GRU门控循环单元分位数回归多输入单输出
  • php的引用
  • 2018以太坊智能合约编程语言solidity的最佳IDEs
  • chrome扩展demo1-小时钟
  • docker容器内的网络抓包
  • Docker下部署自己的LNMP工作环境
  • LintCode 31. partitionArray 数组划分
  • Redis字符串类型内部编码剖析
  • spring security oauth2 password授权模式
  • vue从创建到完整的饿了么(18)购物车详细信息的展示与删除
  • 闭包--闭包之tab栏切换(四)
  • 关于 Cirru Editor 存储格式
  • 诡异!React stopPropagation失灵
  • 机器学习中为什么要做归一化normalization
  • 码农张的Bug人生 - 初来乍到
  • 日剧·日综资源集合(建议收藏)
  • 原生Ajax
  • raise 与 raise ... from 的区别
  • ​ArcGIS Pro 如何批量删除字段
  • #pragma 指令
  • (~_~)
  • (145)光线追踪距离场柔和阴影
  • (3)(3.5) 遥测无线电区域条例
  • (MIT博士)林达华老师-概率模型与计算机视觉”
  • (TipsTricks)用客户端模板精简JavaScript代码
  • (附源码)spring boot车辆管理系统 毕业设计 031034
  • (论文阅读23/100)Hierarchical Convolutional Features for Visual Tracking
  • (免费领源码)Java#Springboot#mysql农产品销售管理系统47627-计算机毕业设计项目选题推荐
  • (免费领源码)python+django+mysql线上兼职平台系统83320-计算机毕业设计项目选题推荐
  • (强烈推荐)移动端音视频从零到上手(下)
  • (自用)learnOpenGL学习总结-高级OpenGL-抗锯齿
  • (自用)网络编程
  • ... 是什么 ?... 有什么用处?
  • .bat批处理出现中文乱码的情况
  • .NET Core 版本不支持的问题
  • .NET Core 网络数据采集 -- 使用AngleSharp做html解析
  • .sh 的运行
  • /3GB和/USERVA开关
  • ::
  • ::什么意思
  • ?php echo $logosrc[0];?,如何在一行中显示logo和标题?