C# Best Practices - Creating Good Methods
How to Define a Method
Identify the problem => Define the single purpose => Specify the inputs and outputs => State any assumptions => Consider the error that could occur
Build a Method
Signature
public bool PlaceOrder(Product product, int quantity)
Optional accessibility modifier (Default is private)
Return type (void if no value)
Method name
Parameter list (Empty parenthesis if no parameters)
XML Document Comment
Use ///
Summary for method purpose
param for a description of each parameter
Signature Best Practices
Do:
Use a verb
Define the most restricted accessibility possible
Keep the number of parameters to a minimum
Define an XML document comment
Avoid:
Vague terms
Abbreviations
Conjunctions (and/or)
Inconsistent naming
Method Body
public bool PlaceOrder(Product product, int quantity)
{
// Guard Clause (garbage in,not garbage out)
if (product == null) throw new ArgumentNullException(nameof(product));
if (quantity <= ) throw new ArgumentOutOfRangeException(nameof(quantity));
}
Best Practices
Do:
Keep methods short (less than 20 lines)
Use white space
Use guard clause
Return an expected result (Use an object to return multiple values)
Implement exception handling
Avoid:
void methods
Property or Method
Property example:
ProductName, Description, InventoryCount?, SuggestedPrice?
Method example:
PlaceOrder(), CalculateInventoryCount()?, CalculateSuggestedPrice()?
Property:
Does it describe data?
Does it execute quickly?
Method:
Does it describe processing?
Does it produce side effects?
Does it require parameters?
Method Overloading
public bool PlaceOrder(Product product, int quantity) public bool PlaceOrder(Product product, int quantity, DateTimeOffset deliveryBy) public bool PlaceOrder(Product product, int quantity, DateTimeOffset deliberyBy, string instructions) public void PlaceOrder(Product prouct, int quantity) ** Not a valid overloading
Best Practices
Do:
Keep the number of parameters to a minimum
Keep the order of the parameters consistent
Define a XML document comment for each overload
Consider optional parameters
Avoid:
Confusing overloads
Overloads that differ in purpose
(Example: OrderItems. One overload get the ordered items, the second overload orders a set of items)
Duplicating code
Method chaining
public OperationResult PlaceOrder(Product product, int quantity)
{
return PlaceOrder(product, quantity, null, null);
} public OperationResult PlaceOrder(Product product, int quantity, DateTimeOffset? deliverBy)
{
return PlaceOrder(product, quantity, deliverBy, null);
} public OperationResult PlaceOrder(Product product, int quantity, DateTimeOffset? deliverBy)
{
// All of the code here
}
Method Chaining Best Practices
Do:
Use to minimize repeated code in method overloads
Consider optional parameters
Avoid:
If it adds complexity
Method Overriding
We can override ToString() for each entity class to make debug easy
FAQ
1.What's the primary purpose of a method?
To implement the logic required for specific behavior or functionality in a class
2.What is the difference between a parameter and an argument?
A parameter is part of the method signature
An argument is part of the method call
3.What is method overloading?
Methods with the same name and purpose but different signatures.
4.What is method chaining?
One method overload calls another overload to prevent repeated code.
5.When is it the best to use method overloading vs. method overriding?
Use overloading when one method requires multiple signatures. Such as GetCustomer(id) to get a customer by id and GetCustomer(name) to get a customer by name.
Use overriding when replacing a method defined high up the object hierarchy. Such as replacing the ToString() method.
C# Best Practices - Creating Good Methods的更多相关文章
- C# Best Practices - Creating Good Properties
Coding Properties Code in the Getter Check the user's credentials Check application state Format the ...
- OOP in JS Public/Private Variables and Methods
Summary private variables are declared with the 'var' keyword inside the object, and can only be acc ...
- zookeeper kazoo Basic Usage
http://kazoo.readthedocs.org/en/latest/basic_usage.html Basic Usage Connection Handling To begin usi ...
- 转: angular编码风格指南
After reading Google's AngularJS guidelines, I felt they were a little too incomplete and also guide ...
- [转]JavaScript Namespaces and Modules
Namespaces In most programming languages we know the concept of namespaces (or packages).Namespaces ...
- SAP HANA学习资料大全[非常完善的学习资料汇总]
Check out this SDN blog if you plan to write HANA Certification exam http://scn.sap.com/community/ha ...
- Sonar 常用代码规则整理(一)
更多原创测试技术文章同步更新到微信公众号 :三国测,敬请扫码关注个人的微信号,感谢! 摘要:公司部署了一套sonar,经过一段时间运行,发现有一些问题出现频率很高,因此有必要将这些问题进行整理总结和分 ...
- 单元测试系列之九:Sonar 常用代码规则整理(一)
更多原创测试技术文章同步更新到微信公众号 :三国测,敬请扫码关注个人的微信号,感谢! 摘要:公司部署了一套sonar,经过一段时间运行,发现有一些问题出现频率很高,因此有必要将这些问题进行整理总结和分 ...
- Mocks Aren't Stubs
Mocks Aren't Stubs The term 'Mock Objects' has become a popular one to describe special case objects ...
随机推荐
- C语言2
函数是C语言的基本单位,类是java,c#,c++的基本单位 int abs(int x); double fabs(double x); 按变量的存储方式:静态变量.自动变量.寄存器变量 指针就 ...
- Jsoup代码解读之一-概述
Jsoup代码解读之一-概述 今天看到一个用python写的抽取正文的东东,美滋滋的用Java实现了一番,放到了webmagic里,然后发现Jsoup里已经有了…觉得自己各种不靠谱啊!算了,静下心来学 ...
- MFC 动态创建控件
动态控件是指在需要时由Create()创建的控件,这与预先在对话框中放置的控件是不同的. 一.创建动态控件: 为了对照,我们先来看一下静态控件的创建. 放置静态控件时必须先建立一个容器,一 ...
- iOS开发之AsyncSocket使用教程
用socket可以实现像QQ那样发送即时消息的功能.客户端和服务端需要建立长连接,在长连接的情况下,发送消息.客户端可以发送心跳包来检测长连接. 在iOS开发中使用socket,一般都是用第三方库As ...
- 图片剪切之Croppic插件
前几天做图片上传时需要进行图片的剪切和缩放,上网查找时找到了这个插件.样式很好看,功能也很OK.但是网上都是php进行后台处理图片的例子,然后只好慢慢琢磨C#的处理.插件地址是:http://www. ...
- JS 获取浏览器窗口大小clientWidth、offsetWidth、scrollWidth
常用: JS 获取浏览器窗口大小 // 获取窗口宽度 if (windows.innerWidth) winWidth = windows.innerWidth; else if ((docume ...
- java 实现 一个账号只能在一个地方登陆,其他地方被下线
其实方法有很多的,我这献丑了. 使用理解java 四大作用域. 思路:理解java 四大作用域的关键. 第一个地方登陆: 1.得到请求的SessionId 和 登陆的 用户名 2.把SessionId ...
- Bootstrap第一天
1.代码引入: 第一步:在html5文档 <meta name="viewport" content="width=device-width, initial-sc ...
- HTML+CSS笔记 CSS进阶
文字排版 字体 我们可以使用css样式为网页中的文字设置字体.字号.颜色等样式属性. 语法: body{font-family:"宋体";} 这里注意不要设置不常用的字体,因为如果 ...
- ASP.Net MVC3 - The easier to run Unit Tests by moq #Reprinted#
From: http://www.cnblogs.com/techborther/archive/2012/01/10/2317998.html 前几天调查完了unity.现在给我的任务是让我调查Mo ...