今天的应用是参考於 Improving C# Code Using Refactoring and Unit Testing ,本文在探讨的内容是如何把紧耦合的程序码经过重构与测试的手法把商业逻辑拆解成物件导向式的写法,符合 SOLID 原则。因此,作者在一开始提出了改善的流程图,如下:
那首先我们要先了解这次的故事情境,这次的程序码是在讲述输入学生的 ID、名字、数学与文学标记後选择 City 与 Country (两种模式的公式附在下方)点击计算後,则会去计算平均值。
Country:Average = (Math mark + Literal mark + 1) / 2
City:Average = (Math mark + Literal mark) / 2
因此,其撰写的程序码如下:
using System;
namespace HelloRefactor
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入学生ID:");
string inputTxtID = Console.ReadLine();
Console.WriteLine("请输入学生名称:");
string inputTxtName = Console.ReadLine();
Console.WriteLine("请输入数学数值:");
string inputTxtMath = Console.ReadLine();
Console.WriteLine("请输入文学数值:");
string inputLiteral = Console.ReadLine();
Console.WriteLine("Country 模式还是 City 模式 (Country 为 true/City 为 false):");
string inputIsCountry = Console.ReadLine();
//
DemoCalculate demoCal = new DemoCalculate(inputTxtID, inputTxtName, inputTxtMath, inputLiteral, inputIsCountry);
string demoResult = demoCal.Calculate();
Console.WriteLine("结果:" + demoResult);
}
}
public class DemoCalculate
{
private string txtID;
private string txtName;
private string txtMath;
private string txtLiteral;
private string isCountry;
double result;
public DemoCalculate(string inTxtID, string inTxtName, string inTxtMath, string inTxtLiteral, string inIsCountry)
{
txtID = inTxtID;
txtName = inTxtName;
txtMath = inTxtMath;
txtLiteral = inTxtLiteral;
isCountry = inIsCountry;
}
public string Calculate()
{
if (!double.TryParse(txtMath, out result))
{
return "发生错误!数学数值应该是个 numeric!";
}
if (((Convert.ToDouble(txtMath) > 10)) || (Convert.ToDouble(txtMath) < 0))
{
return "发生错误!数学数值应该介於 0 ~ 10 之间!";
}
if (!double.TryParse(txtLiteral, out result))
{
return "发生错误!文学数值应该是个 numeric!";
}
if (((Convert.ToDouble(txtLiteral) > 10)) || (Convert.ToDouble(txtLiteral) < 0))
{
return "发生错误!文学数值应该介於 0 ~ 10 之间!";
}
if (Convert.ToBoolean(isCountry))
{
return txtID + " " + txtName + " " + ((Convert.ToDouble(txtMath) + Convert.ToDouble(txtLiteral) + 1) / 2).ToString();
}
else
{
return txtID + " " + txtName + " " + ((Convert.ToDouble(txtMath) + Convert.ToDouble(txtLiteral)) / 2).ToString();
}
}
}
}
跑出的结果:
在参考文章中是采用 WinForm,为了方便让没接触过 WinForm 的读者可以观阅文章,我们改采用 Console 的写法,如此还可以练习检测 Console 输入的检测,而明天会开始讨论重构的内容。
<<: 卡夫卡的藏书阁【Book13】- KafkaJS 生产者 1
Hexo 虽然是静态网页产生器,因此不会像 WordPress 那样本身就内建内容储存在资料库的文章...
sudo apt install libappindicator3-1 sudo apt insta...
1.is 开头的大部分回传值是booling ex:isNaN() https://www.w3sc...
在上述change方法里,我们有以下方法可以使用: 对资料表做修改: create_table(na...
7年资深 iOS 开发工程师,5 道题全面考察候选人,看看你能过几招? 今天看到觉得好像蛮重要的,所...