`
rensanning
  • 浏览: 3514049 次
  • 性别: Icon_minigender_1
  • 来自: 大连
博客专栏
Efef1dba-f7dd-3931-8a61-8e1c76c3e39f
使用Titanium Mo...
浏览量:37479
Bbab2146-6e1d-3c50-acd6-c8bae29e307d
Cordova 3.x入门...
浏览量:604323
C08766e7-8a33-3f9b-9155-654af05c3484
常用Java开源Libra...
浏览量:678071
77063fb3-0ee7-3bfa-9c72-2a0234ebf83e
搭建 CentOS 6 服...
浏览量:87257
E40e5e76-1f3b-398e-b6a6-dc9cfbb38156
Spring Boot 入...
浏览量:399816
Abe39461-b089-344f-99fa-cdfbddea0e18
基于Spring Secu...
浏览量:69067
66a41a70-fdf0-3dc9-aa31-19b7e8b24672
MQTT入门
浏览量:90474
社区版块
存档分类
最新评论

关于代码风格

阅读更多
良好的代码风格能提高代码可读性及可维护性,程序员都应该遵守基本的代码排版规范、代码命名规范。

首先看看以下三张图,在没有代码的情况下能猜猜各是什么开发语言。
---------------------------------------------------------------

---------------------------------------------------------------

---------------------------------------------------------------


第一张图是CSS,可以看到清晰的选择器和属性键值对。
第二张图是HTML,可以看到清晰的head和body定义。
第三张图是Java,可以看到头部imports,类定义,成员变量,构造函数以及其他方法。
图片来自:https://schneide.wordpress.com/2015/04/26/the-typography-of-source-code/

各个语言都有自己的规范,开发所用的各种IDE也都内置了代码格式化工具,比如Eclipse对Java和JavaScript代码的标准格式化定义:





也可以通过 Checkstyle 检查Java代码的规范性。

这里罗列几个最有争议的。

(1)缩进

使用Tab 还是空格?2个空格还是4个空格?具体关于这个网上的争论太多了,但是需要特别注意的是像Python和CoffeeScript等是通过缩进来控制代码逻辑。



https://softwareengineering.stackexchange.com/questions/57/tabs-versus-spaces-what-is-the-proper-indentation-character-for-everything-in-e
https://medium.com/@hoffa/400-000-github-repositories-1-billion-files-14-terabytes-of-code-spaces-or-tabs-7cfe0b5dd7fd

(2)换行

大括号是否应该换行?

if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}


if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}


if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();


https://softwareengineering.stackexchange.com/questions/2715/should-curly-braces-appear-on-their-own-line

大括号是否应该省略?

for (int i = 0; i < size; i++)  {
   a += b;
}


for (int i = 0; i < size; i++)  
   a += b;


for (int i = 0; i < size; i++) a += b;


https://stackoverflow.com/questions/8020228/is-it-ok-if-i-omit-curly-braces-in-java

(3)对齐

赋值等号对齐
int a_variable           = 1;
int another_variable     = 2;
int yet_another_variable = 3;


注释对齐
// whole line comment
int linePointer;                            // inline comment
BufferredReader br = new BufferredReader(); // inline comment
File f = new File();                        // inline comment


参数对齐
int some_call_result = some_object.a_method(
        with, 
        quite_long, 
        list_of,
        parameters
    );


链式方法对齐
protected void configure(HttpSecurity http) throws Exception {
  http
    .authorizeRequests()
      .antMatchers("/resources/**", "/signup", "/about").permitAll()
      .antMatchers("/admin/**").hasRole("ADMIN")
      .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
      .anyRequest().authenticated()
      .and()
    .formLogin();
}


(4)空行

合理的利用空行来区分代码块。
    /**
     * Initialize this servlet.  Most of the processing has been factored
     * into support methods so that you can override particular functionality
     * at a fairly granular level.

     *
     * @throws ServletException if we cannot configure ourselves correctly
     */
    public void init() throws ServletException {
        final String configPrefix = "config/";
        final int configPrefixLength = configPrefix.length() - 1;

        // Wraps the entire initialization in a try/catch to better handle
        // unexpected exceptions and errors to provide better feedback
        // to the developer
        try {
            initInternal();
            initOther();
            initServlet();
            initChain();

            getServletContext().setAttribute(Globals.ACTION_SERVLET_KEY, this);
            initModuleConfigFactory();

            // Initialize modules as needed
            ModuleConfig moduleConfig = initModuleConfig("", config);

            initModuleMessageResources(moduleConfig);
            initModulePlugIns(moduleConfig);
            initModuleFormBeans(moduleConfig);
            initModuleForwards(moduleConfig);
            initModuleExceptionConfigs(moduleConfig);
            initModuleActions(moduleConfig);
            moduleConfig.freeze();

            Enumeration names = getServletConfig().getInitParameterNames();

            while (names.hasMoreElements()) {
                String name = (String) names.nextElement();

                if (!name.startsWith(configPrefix)) {
                    continue;
                }

                String prefix = name.substring(configPrefixLength);

                moduleConfig =
                    initModuleConfig(prefix,
                        getServletConfig().getInitParameter(name));
                initModuleMessageResources(moduleConfig);
                initModulePlugIns(moduleConfig);
                initModuleFormBeans(moduleConfig);
                initModuleForwards(moduleConfig);
                initModuleExceptionConfigs(moduleConfig);
                initModuleActions(moduleConfig);
                moduleConfig.freeze();
            }

            this.initModulePrefixes(this.getServletContext());

            this.destroyConfigDigester();
        } catch (UnavailableException ex) {
            throw ex;
        } catch (Throwable t) {
            // The follow error message is not retrieved from internal message
            // resources as they may not have been able to have been
            // initialized
            log.error("Unable to initialize Struts ActionServlet due to an "
                + "unexpected exception or error thrown, so marking the "
                + "servlet as unavailable.  Most likely, this is due to an "
                + "incorrect or missing library dependency.", t);
            throw new UnavailableException(t.getMessage());
        }
    }


(5)命名

违反命名规范的例子有很多,这里列2个:

非驼峰命名

package com.test.EC_shop;

public class db_manager {
    private String connection_url;

    public void Init() {
       // ...
    }

}


连续编号

public class UC8010 extends CMN0101 {
    private String FLD0001;

    public int MTD0001() {
       // ...
    }

}
publi class UC8020 extends CMN0101 {
    private String FLD0001;

    public int MTD0001() {
       // ...
    }

}



再列举一些代码书写上的其他Style。

(1)多层嵌套 还是 中途退出?

public String getInsuranceName(Employee employee) {
    if (employee != null) {
        Car car = employee.getCar();
        if (car != null) {
            Insurance insurance = car.getInsurance();
            if (insurance != null) {
                return insurance.getName();
            }
        }
    }
    return "UNKNOWN";
}


public String getInsuranceName(Employee employee) {
    if (employee == null) {
        return "UNKNOWN";
    }
    Car car = employee.getCar();
    if (car == null) {
        return "UNKNOWN";
    }
    Insurance insurance = car.getInsurance();
    if (insurance == null) {
        return "UNKNOWN";
    }
    return insurance.getName();
}


(2)常量放在左侧还是右侧?

if (currentValue == 5) {
    // do work
}
if (5 == currentValue) {
    // do work
}


if (obj == null) {
}
if (null == obj) {
}
if (obj = null) { // 赋值运算、NPE异常
}
if (null = obj) { // 编译错误
}


https://stackoverflow.com/questions/2369226/object-null-or-null-object

(3)定义接口类型还是实现类型?

List<Integer> sampleList = new ArrayList<Integer>();


ArrayList<Integer> sampleList = new ArrayList<Integer>();


(4)标准for循环还是增强for循环?

for (int i = 0; i < peopleList.size(); i++) {
  People p = peopleList.get(i);
  // ..
}


for (People p : peopleList) {
  // ...
}


(5)变量是否需要先定义为null?

Object localVariableObj2 = null;
localVariableObj2 = new Object();


Object localVariableObj2 = new Object();


*** 成员变量有默认值不需要赋值null,本地变量没有默认值需要赋值null。

(6)通过class还是interface定义全局常量?

public final class Constants {
  public static final int PI = 3.14;
}


public interface Constants {
  int PI = 3.14;
}


还有这么定义的:
public interface Constants {
  public static final String TOAST = "toast";
}


这些都是常见的,还有很多。
  • 大小: 7.5 KB
  • 大小: 38.3 KB
  • 大小: 13.7 KB
  • 大小: 113.1 KB
  • 大小: 91.8 KB
  • 大小: 19.6 KB
1
0
分享到:
评论

相关推荐

    程序员之路———关于代码风格

    好的代码风格对于优秀的程序员是必须的。 免费共享 程序员之路——关于代码风格。

    vorlesung_coding_guidelines_ppt.pdf 关于代码风格的

    关于代码风格的 风格 vorlesung_coding_guidelines_ppt.pdf

    C语言编程规约(形成良好的代码风格)

    C语言编程规约 关于代码风格的 形成良好的代码风格

    swift-关于iOS代码风格管理的两三事儿

    关于iOS代码风格管理的两三事儿

    PHP之道(中文word)

    其中有部分是关于代码风格的,即 PSR-0, PSR-1, PSR-2 和 PSR-4。这些推荐只是一些被其他项目所遵循的规则,如 Drupal, Zend, Symfony, CakePHP, phpBB, AWS SDK, FuelPHP, Lithium 等。你可以把这些规则用在自己的...

    C代码风格[DOC]

    C代码风格[DOC] 关于C代码的书,看看吧~!

    免费下载:C语言难点分析整理.doc

    63. 程序员之路──关于代码风格 343 64. 指针、结构体、联合体的安全规范 346 65. C指针讲解 352 66. 关于指向指针的指针 368 67. C/C++ 误区一:void main() 373 68. C/C++ 误区二:fflush(stdin) 376 69. C/C++ ...

    Python-代码风格指南

    请参阅PEP关于Python的C实现的C编码风格指南的描述。 本文档和PEP257(文档字符串规范)改编自Guido的《Python Style Guide》一文,并从《Barry's style guide》添加了部分内容作为补充。 这篇风格指南随着时间的...

    C语言难点分析整理.doc

    63. 程序员之路──关于代码风格 343 64. 指针、结构体、联合体的安全规范 346 65. C指针讲解 352 66. 关于指向指针的指针 368 67. C/C++ 误区一:void main() 373 68. C/C++ 误区二:fflush(stdin) 376 69. C...

    高级C语言 C 语言编程要点

    63. 程序员之路──关于代码风格 343 64. 指针、结构体、联合体的安全规范 346 65. C指针讲解 352 66. 关于指向指针的指针 368 67. C/C++ 误区一:void main() 373 68. C/C++ 误区二:fflush(stdin) 376 69. C/C++ ...

    c语言难点分析整理,C语言

    63. 程序员之路──关于代码风格 343 64. 指针、结构体、联合体的安全规范 346 65. C指针讲解 352 66. 关于指向指针的指针 368 67. C/C++ 误区一:void main() 373 68. C/C++ 误区二:fflush(stdin) 376 69. C/C++ ...

    高级C语言详解

    63. 程序员之路──关于代码风格 343 64. 指针、结构体、联合体的安全规范 346 65. C指针讲解 352 66. 关于指向指针的指针 368 67. C/C++ 误区一:void main() 373 68. C/C++ 误区二:fflush(stdin) 376 69. C/C++ ...

    高级进阶c语言教程..doc

    63. 程序员之路──关于代码风格 343 64. 指针、结构体、联合体的安全规范 346 65. C指针讲解 352 66. 关于指向指针的指针 368 67. C/C++ 误区一:void main() 373 68. C/C++ 误区二:fflush(stdin) 376 69. C/C++ ...

    史上最强的C语言资料

    63. 程序员之路──关于代码风格 343 64. 指针、结构体、联合体的安全规范 346 65. C指针讲解 352 66. 关于指向指针的指针 368 67. C/C++ 误区一:void main() 373 68. C/C++ 误区二:fflush(stdin) 376 69. C/C++ ...

    C语言难点分析整理

    63. 程序员之路──关于代码风格 343 64. 指针、结构体、联合体的安全规范 346 65. C指针讲解 352 66. 关于指向指针的指针 368 67. C/C++ 误区一:void main() 373 68. C/C++ 误区二:fflush(stdin) 376 69. C/C++ ...

    高级C语言.PDF

    PC-Lint与C\C++代码质量 ........................................................................................................ 132 32. spirntf函数使用大全...............................................

    PyUI

    :sparkles:关于代码风格 本项目集成prettier做代码风格统一格式化,所以在书写时,大家可以不关注代码风格,按自己喜欢的写就好,在执行commit时会自动对代码做统一格式化。 :sparkles:关于commit中emoji的使用 ...

    NextDevTemplateForVite:基于vite 2.x的开发模板;支持git提交消息规范校验;支持脚本自动lint代码;支持脚本 校验 文件名称规范;build后的产物,支持接入 qiankun ;支持约定式路由,自动生成路由;

    技术栈 vue3 + vite + typescript + less 下载依赖 npm install 启动 vite 开发环境 npm run dev 项目打包 npm run build 生产环境预览 npm run serve 路由使用 vite-plugin-pages ...关于代码风格 commitlint commi

    leetcode中国-leetnode:利特节点

    关于代码风格 代码块可为三大块:异常处理(空串和边界处理),主体,返回 代码风格(可参考 Google 的编程语言规范) 变量名:有意义的变量名 缩进:语句块 空格:二元运算符、括号两侧 可读性:单语句使用花括号等...

    微软.NET代码的编程风格指导规范PDF

    本文档描述了微软一站式代码示例库项目组所采纳的关于本地 C++ 和 .NET (C# 和VB.NET)代码的编程风格指导规范

Global site tag (gtag.js) - Google Analytics