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的更多相关文章

  1. C# Best Practices - Creating Good Properties

    Coding Properties Code in the Getter Check the user's credentials Check application state Format the ...

  2. 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 ...

  3. zookeeper kazoo Basic Usage

    http://kazoo.readthedocs.org/en/latest/basic_usage.html Basic Usage Connection Handling To begin usi ...

  4. 转: angular编码风格指南

    After reading Google's AngularJS guidelines, I felt they were a little too incomplete and also guide ...

  5. [转]JavaScript Namespaces and Modules

    Namespaces In most programming languages we know the concept of namespaces (or packages).Namespaces ...

  6. SAP HANA学习资料大全[非常完善的学习资料汇总]

    Check out this SDN blog if you plan to write HANA Certification exam http://scn.sap.com/community/ha ...

  7. Sonar 常用代码规则整理(一)

    更多原创测试技术文章同步更新到微信公众号 :三国测,敬请扫码关注个人的微信号,感谢! 摘要:公司部署了一套sonar,经过一段时间运行,发现有一些问题出现频率很高,因此有必要将这些问题进行整理总结和分 ...

  8. 单元测试系列之九:Sonar 常用代码规则整理(一)

    更多原创测试技术文章同步更新到微信公众号 :三国测,敬请扫码关注个人的微信号,感谢! 摘要:公司部署了一套sonar,经过一段时间运行,发现有一些问题出现频率很高,因此有必要将这些问题进行整理总结和分 ...

  9. Mocks Aren't Stubs

    Mocks Aren't Stubs The term 'Mock Objects' has become a popular one to describe special case objects ...

随机推荐

  1. python request模块学习

    安装: pip install requests 使用: import requests HTTP请求:GET.POST.PUT.DELETE.HEAD.OPTIONS 1) get res = re ...

  2. Garbage

    垃圾回收 http://journal.stuffwithstuff.com/2013/12/08/babys-first-garbage-collector/ http://blog.jobbole ...

  3. CAD教程/视频教程/软件类专题资料免费下载整理合集

    CAD教程&视频教程类专题资料免费下载 资源列表:http://www.xiaodianlv.com/group/cad/ [1] <AUTOCAD2012中文版全套视频教程大合集> ...

  4. css table 布局

    使用CSS表格 CSS表格能够解决所有那些我们在使用绝对定位和浮动定位进行多列布局时所遇到的问题.例如,“display:table;”的CSS声明能够让一个HTML元素和它的子节点像table元素一 ...

  5. 解决libc.so.6: version `GLIBC_2.14' not found问题, 升级glibc,glibc-2.15

    0.以下在系统CentOS 6.3 x86_64上操作 1.试图运行程序,提示"libc.so.6: version `GLIBC_2.14' not found",原因是系统的g ...

  6. MyEclipse启动时报 Unable to acquire application service. Ensure that the org.eclips

    今天MyEclipse启动时报如下错误: !SESSION 2012-02-12 11:32:55.198 ---------------------------------------------- ...

  7. Android应用开发基础篇(14)-----自定义标题栏

    一.概述 每一个应用程序默认的标题栏(注意与状态栏的区别)只有一行文字(新建工程时的名字),而且颜色.大小等都是固定的,给人的感觉比较单调.但当程序需要美化的时候,那么修改标题栏是就是其中一项内容,虽 ...

  8. 今天研究了下webservice 终于OK了

    今天研究了下webservice 终于OK了,所以把它写到自己的博客来,因为网上说的都很复杂     而在这里,我会很简单的说明,一看就懂     首先在进行webservice  一定要下载包    ...

  9. 解决iOS7中UITableView在使用autolayout时layoutSubviews方法导致的crash

    近期公司项目上线后,出现了大量的crash,发生在iOS7系统上,和UITableView相关: Auto Layout still required after executing -layoutS ...

  10. ajax联动

    1.编写html代码,引入ajax文件 <script type="text/javascript" src="js/ajax.js"></s ...