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 ...
随机推荐
- java_httpservice
http://blog.csdn.net/maosijunzi/article/details/41045181
- hdu 3498 whosyourdaddy 重复覆盖
题目链接 重复覆盖的入门题, 和精确覆盖不一样, 删除的时候只删除一行多列. #include<bits/stdc++.h> using namespace std; #define pb ...
- python使用mysql的三个模块:mysql.connector、sqlalchemy、MySQLdb
在python中使用mysql其实很简单,只要先安装对应的模块即可,那么对应的模块都有什么?官方也没指定也没提供,pcat就推荐自己遇到的3个模块:mysql.connector.sqlalchemy ...
- junit的安装和使用
一.junit的安装: junit-4.11.jar: http://www.java2s.com/Code/Jar/j/Downloadjunit411jar.htm hamcrest-core.j ...
- JS表格排序
var employees = [] employees[0] = { name: "George", age: 32, retiredate: "March 12, 2 ...
- python基础学习笔记4--抽象
抽象 1.函数: 1) 函数是可以调用,它执行某种行为并且返回一个值.可以通过callable函数来判断函数是否可调用. eg:>>> def hello(name): ...
- GC(Garbagecollection)垃圾回收
在前面向大家讲解FTL时,我们提到了GC的操作,所谓GC就是把一个闪存块里的‘有效’页数据复制到一个‘空白’块里,然后把这个块完全擦除.GC是SSD里的一个非常关键的操作,其效率对性能有决定性影响.闪 ...
- 传智播客C/C++各种开发环境搭建视频工具文档免费教程
传智播客作为中国IT培训的领军品牌,一直把握技术趋势,给大家带来最新的技术分享!传智播客C/C++主流开发环境免费分享视频文档中,就有写一个helloworld程序的示范.火速前来下载吧 所谓&quo ...
- Windows Azure 社区新闻综述(#72 版)
欢迎查看最新版本的每周综述,其中包含有关云计算和 Windows Azure的社区推动新闻.内容和对话. 以下是过去一周基于您的反馈汇集在一起的内容: 文章 · 在 Windows Azure 移 ...
- kbengine简单介绍(1)
什么是kbengine? 一款开源的游戏服务端引擎,客户端通过简单的约定协议就能与服务端通讯, 使用KBEngine插件能够快速与(Unity3D, OGRE, Cocos2d-x, HTML5, 等 ...