目的
- 简简单单,才能明明白白
- 用时与复杂度成反比
- 以下方法,面向函数级,已实测。
- 方法1:使用?:
namespace SimplifyCode
{
public class Choice
{
bool weekend = true;
// 常规
public string Complex()
{
if (weekend)
{
return "rest";
}
else
{
return "work";
}
}
// 卫函数,减少层次
public string Guard()
{
if (weekend) return "rest";
return "work";
}
// 条件操作符
public string Operator()
{
return weekend ? "rest" : "work";
}
// 表达式
public string Lambda()
=> weekend ? "rest" : "work";
}
}
using System.Windows.Forms;
namespace SimplifyCode
{
public class Validation
{
public void Complex()
{
if (IsWrongLicense()) return;
IsWrongPassword();
}
public void Simple()
{
var result =
IsWrongLicense() ||
IsWrongPassword();
}
private bool IsWrongLicense()
{
bool result = true; // 省略具体判定
if (result)
{
MessageBox.Show("Not right license!");
}
return result;
}
private bool IsWrongPassword()
{
bool result = true; // 省略具体判定
if (result)
{
MessageBox.Show("Not right password!");
}
return result;
}
}
}
using System;
using System.Windows.Forms;
namespace SimplifyCode
{
public delegate void ClickContent(string content);
public class UserCtrl
{
public event ClickContent ContentClicked;
public void Complex_Click(object sender, EventArgs e)
{
if (ContentClicked == null) return;
ContentClicked.Invoke((sender as TextBox).Text);
}
public void Simple_Click(object sender, EventArgs e)
{
ContentClicked?.Invoke((sender as TextBox).Text);
}
}
public class SomeForm
{
private UserCtrl ctrl = new UserCtrl();
public SomeForm()
{
ctrl.ContentClicked += OnContentClicked;
}
private void OnContentClicked(string content) { }
}
}
namespace SimplifyCode
{
public class Info
{
public string ServerIP { get; set; }
public string DefaultServerIP { get; set; }
}
public class App
{
public Info info = new Info();
public string Complex_GetServerIP()
{
string serverIP = info.ServerIP;
if (info.ServerIP != null)
{
return serverIP;
}
return info.DefaultServerIP;
}
public string Simple_GetServerIP()
=> info.ServerIP ?? info.DefaultServerIP;
}
}
namespace SimplifyCode
{
public class Sql
{
private string schema, table;
public Sql(string schema, string table)
{
this.schema = schema;
this.table = table;
}
public string Complex_GetMaxID()
{
return string.Format($"use {0};"
+ $"\n select max(id) from {1};",
schema, table);
}
public string Simple_GetMaxID()
{
return $"use {schema};"
+ $"\n select max(id) from {table};";
}
}
}
网友评论