当前位置:  编程技术>.net/c#/asp.net

C#的编码规范详细说明

    来源: 互联网  发布时间:2014-10-22

    本文导语:  首先我们要明白一下几点,1.代码写出来除了让他跑起来还有个非常非常重要的作用是维护,因为没有一成不变的代码,需求变化代码就不可避免的要变化。2.你不是一个人在写代码,你身后有一个团队,这个团队中任何一个...

首先我们要明白一下几点,
1.代码写出来除了让他跑起来还有个非常非常重要的作用是维护,因为没有一成不变的代码,需求变化代码就不可避免的要变化。
2.你不是一个人在写代码,你身后有一个团队,这个团队中任何一个人都有可能会改你的代码,你如果写的不规范,后面的人会跟着写。举一个例子,最初的代码可能是这样的,
代码如下:

if (OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "CZ-SP")
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e = ReGetFlight.GetDirectFlightHighWeightEntity(OrderInfo.O_FlightEntity, "", e.FlightAgency);
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    regetFlightInitData.TicketType = "0001";
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }
                else
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e.CostRate1 = 1.0M;
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }

但是过一时间又来个需求,对于“MU-WS”也需要走上面的逻辑,你会怎么写,如果你只是完成任务可能会像下面这样写
代码如下:

if (OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "CZ-SP" || OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-WS")
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e = ReGetFlight.GetDirectFlightHighWeightEntity(OrderInfo.O_FlightEntity, "", e.FlightAgency);
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    regetFlightInitData.TicketType = "0001";
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }
                else
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e.CostRate1 = 1.0M;
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }

如果真的这么写你就是始作俑者,后面的人如果都和你一样就都会朝着葫芦画瓢,最后代码可能会是这样的
代码如下:

if (OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "CZ-SP" || OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-WS" || OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-WS" || OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-SP" || OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "CZ-WS" || OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "XT-WS")
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e = ReGetFlight.GetDirectFlightHighWeightEntity(OrderInfo.O_FlightEntity, "", e.FlightAgency);
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    regetFlightInitData.TicketType = "0001";
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }
                else
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e.CostRate1 = 1.0M;
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }

看到效果了么,你需要脱一下下面的那个长条才能看到全部代码,这就是你的“因”种下后得到的果实。所以我们需要改进,常见的改进是回车换行,保证所有的代码都在你一眼能够看到的范围之内。改进后代码如下:
代码如下:

if (OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "CZ-SP" ||
                    OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-WS" ||
                    OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-WS" ||
                    OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "MU-SP" ||
                    OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "CZ-WS" ||
                    OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper() == "XT-WS")
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e = ReGetFlight.GetDirectFlightHighWeightEntity(OrderInfo.O_FlightEntity, "", e.FlightAgency);
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    regetFlightInitData.TicketType = "0001";
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;
                }
                else
                {
                    OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                    e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                    e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                    e.CostRate1 = 1.0M;
                    regetFlightInitData.HighCostAndWeightEntity = e;
                    //如果是海航,则不需要政策倒查验证
                    regetFlightInitData.ReSearchNoFlight = false;

是不是清爽一点,好看一点,如果你在第一次修改代码的时候这样写后面的人就会跟着这样写,他们可能会想,前面一个人这样写这样写应该不会有问题,虽然代码看起来有点别扭,这时候我们可以带着鉴赏的眼光看这段代码,如果再想一想还有更好的方法,为何不用switch呢?
代码如下:

switch (OrderInfo.O_OrdersEntity.DirectFlightChannel.Trim().ToUpper())
                {
                    case "CZ-SP":
                    case "MU-SP":
                    case "XT-WS":
                        {
                            OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                            e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                            e = ReGetFlight.GetDirectFlightHighWeightEntity(OrderInfo.O_FlightEntity, "", e.FlightAgency);
                            e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                            regetFlightInitData.HighCostAndWeightEntity = e;
                            regetFlightInitData.TicketType = "0001";
                            //如果是海航,则不需要政策倒查验证
                            regetFlightInitData.ReSearchNoFlight = false;
                            break;
                        }
                    default:
                        {
                            OrderCostAndWeightEntity e = new OrderCostAndWeightEntity();
                            e.Sendticketcity = int.Parse(ConfigurationManager.AppSettings["SendticketcityOfDirectFlights_HU"].ToString());
                            e.FlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(OrderInfo.O_OrdersEntity.DirectFlightChannel);
                            e.CostRate1 = 1.0M;
                            regetFlightInitData.HighCostAndWeightEntity = e;
                            //如果是海航,则不需要政策倒查验证
                            regetFlightInitData.ReSearchNoFlight = false;
                            break;
                        }
                }

是不是更加简单,如果你这样写,后面的人会毫不犹豫地在后面加一个case “”:因为这个是大家再熟悉不过的语法了,丝毫不用怀疑这种写法的正确性,于是我们可以带着欣赏的眼光来看这段代码了。
3.要承认我们的心智就这么多,脑袋就这么大,我们既不能一目十行也不能出口成章,所以不要写一言看不出什么意思的代码。
以上的想法都是建立在维护别人代码的痛苦,失落,沮丧,各种不爽,各种吐槽之上,所以代码规范是需要我们时刻关注的,在这里自己总结一些规范,告诫自己不要做始作俑者。
1.一个文件中只放一个类,类名同文件名,不要在一个文件中写好几个类,这样看的清楚。
2.不要在一个文件中写多于1000行的代码,除了那些比较大的实体类。其实我还想说超过500行看起来就有点累,但是在我们的系统中超过10000行的代码比比皆是。
3.一个方法的代码不要超过100行,其实我想说超过50行的方法看起来就有点累。但是在我们的系统中超过200行代码的方法比比皆是。
4.存储过程的代码也不要超过100行,不要在存储过程中写过多的业务逻辑,那是找死,但是在我们的系统中我还真他妈的见过10000多行的存储过程,好宏伟啊!
5.避免写超过5个参数的方法,如果有请使用一个类或者结构来传。
6.一个方法只有一个return result; ,不要多次return结果,最好给返回结果赋值,最后return result;
7.不要给很简单的代码加注释,会有噪音的,会让人误解的,因为你写的大多数情况下很片面。
8.记录日志的时候不要到处都记,有条件的情况下针对客户一次操作(比如下单)只记录一条日志。
另外再这里列举自己对代码做的一些改进,不足之处欢迎大家指出。
1.参数过长使用缩进
代码如下:

a.
                    //获得保险策略信息
                    insuranceStrategy = InsuranceCommon.GetStrategyInsurance(appFltEntity.ProductSource.ToString(), strategyFlightAgency.ToString(), "", appFltEntity.Price.ToString(), appFltEntity.DirectFlightChannel, appFltEntity.Airline.DibitCode, appFltEntity.Flight, appFltEntity.DepartAirport.Code, appFltEntity.ArriveAirport.Code, appFltEntity.SubClass, appFltEntity.DepartTime, appFltEntity.DepartTime.Date, null);
b.
                    //获得保险策略信息
                    insuranceStrategy = InsuranceCommon.GetStrategyInsurance(appFltEntity.ProductSource.ToString(),
                                                                             strategyFlightAgency.ToString(),
                                                                             "",
                                                                             appFltEntity.Price.ToString(),
                                                                             appFltEntity.DirectFlightChannel,
                                                                             appFltEntity.Airline.DibitCode,
                                                                             appFltEntity.Flight,
                                                                             appFltEntity.DepartAirport.Code,
                                                                             appFltEntity.ArriveAirport.Code,
                                                                             appFltEntity.SubClass,
                                                                             appFltEntity.DepartTime,
                                                                             appFltEntity.DepartTime.Date,
                                                                             null);

2.if条件过长中使用缩进
代码如下:

a.
                if (IsDirectFlight && (this.CorpPayType == ExpenseType.OWN || this.AccountInfo.DirectOrdersQuoteMode == "I"))
                {
                    strategyFlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(appFltEntity.DirectFlightChannel);
                    //根据票台获得票台对应的城市
                    strategyCityID = InsuranceCommon.GetFlightAgencyCity(strategyFlightAgency);
                 }
b.
                if (IsDirectFlight &&
                    (this.CorpPayType == ExpenseType.OWN ||
                    this.AccountInfo.DirectOrdersQuoteMode == "I"))
                {
                    strategyFlightAgency = InsuranceCommon.GetStrategyFlightAgencyNew(appFltEntity.DirectFlightChannel);
                    //根据票台获得票台对应的城市
                    strategyCityID = InsuranceCommon.GetFlightAgencyCity(strategyFlightAgency);
                 }

3.使用三元表达式
代码如下:

a.
                        if (InsuranceInfoList != null && InsuranceInfoList.Count > 0 && InsuranceInfoList[0].GeneralDescription.Contains("e路泰康"))
                            collections.Set("IsElderCanBuyInsurance", "T");
                        else
                            collections.Set("IsElderCanBuyInsurance", "F");
b.
collections.Set("IsElderCanBuyInsurance", InsuranceInfoList != null && InsuranceInfoList.Count > 0 && InsuranceInfoList[0].GeneralDescription.Contains("e路泰康") ? "T" : "F");

4.使用蓝不大表达式
代码如下:

a.
                        InsuranceInfoList = InsuranceInfoList.FindAll(delegate(BookingInsuranceInfo iInfo)
                        {
                            return iInfo.TypeID == "C2C30";
                        });
b.
InsuranceInfoList = InsuranceInfoList.FindAll(a => a.TypeID == "C2C30");

5.使用switch表达式,见上面。
6.使用数组包含
代码如下:

a.
            if (wsFlt.ProductSource == 4 && !string.IsNullOrEmpty(wsFlt.DirectFlightChannel) && (wsFlt.DirectFlightChannel.ToUpper() == "HO-WS" or wsFlt.DirectFlightChannel.ToUpper() == "ZH-WS" or wsFlt.DirectFlightChannel.ToUpper() == "XT-WS")
                && directFlightCorporationList != null && directFlightCorporationList.Count > 0 && !directFlightCorporationList.Contains(corporationid))
            {
                return false;
            }
b.
            if (wsFlt.ProductSource == 4 &&
                new List() { "HO-WS", "CZ-WS", "XT-WS" }.Contains(wsFlt.DirectFlightChannel.Trim().ToUpper()) &&
                directFlightCorporationList != null &&
                directFlightCorporationList.Count > 0 &&
                !directFlightCorporationList.Contains(corporationid))
            {
                return false;
            }

可以看到代码中也使用了缩进。
欢迎大家也列举自己遇到的代码简洁之道。

    
 
 
 
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • java命名空间javax.print类docflavor的类成员方法:默认编码和平台编码定义及介绍
  • 求救:JAVA 中汉字编码怎样变成 VC 下的汉字编码?
  • 中文汉字编码知识及各种中文编码对应的编码区间总结
  • aix socket进程为何收到客户端的编码都是ISO-8859-1编码?
  • Python获取网页编码的方法及示例代码
  • iconv可以用来转换文字编码,有没有可以用来识别编码的?
  • MyEclipse如何查看和设置文件编码格式相关操作
  • 怎么把字符串转为:unicode 编码?又如何把unicode编码转为字符串(有中文)?
  • Base64编码原理详解及c++编码解码实现
  • 谁能给我讲讲UNIX下编码与编码设置与编码转化问题。。。
  • Python3中内置类型bytes和str用法及byte和string之间各种编码转换
  • 在jsp中如何判断传来的字符串是8859-1编码还是gb2312编码方式
  • Linux/CentOS/fedora下vim显示的字符编码设置
  • python处理中文编码和判断编码示例
  • 文件编码及UTF-8、BOM、0XFEFF相关问题
  • 网页的编码问题!或者java的编码问题,由此引出一条解决中文问题的思路
  • 广告系统中weak-and算法原理及编码验证
  • php字符串编码转换函数 可以自动识别原编码
  • Java读写包括中文的txt文件时不同编码格式问题解决
  • 修改mysql5.5默认编码(图文步骤修改为utf-8编码)
  • windows平台 vs2008进行c++编码的相关设置介绍
  • linux查看系统编码和修改系统编码的方法


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3