Document directory
- Topic 1: the smaller the function, the better!
- Topic 2: simplify code with Linq
- Topic 4: application? : And ??
- Topic 5: Use
- Topic 6: Use using
I recently discussed with some friends how to write elegant code. We like C # very much, so C # is used as an example. A total of three programmers are discussing this. For simplicity, I use ABC to represent the three of us.
Sometimes we will discuss some code, sometimes we will put forward some ideas, sometimes we will learn some existing blogs on the Internet, in order to make it easier for everyone to reference, I will compile a number for each topic.
In many cases, our opinions are unified, so I will show you our conclusions. However, in some cases, we have differences.
You can join our discussion. I hope you can get your opinions and let us grow together!
Okay, let's start today.
Topic 1: the smaller the function, the better!
I believe that most programmers will agree with this, and maintaining a function with more than 100 rows will make people crazy.
I remember I used to modify a program written in cobol. A file contains more than 0.1 million lines. It took me three days to make an extremely small modification, in the end, I don't know if it will cause any serious consequences. -- The code has been running well for the past eight years.
In an ideal state, how many rows should our function have? The answer for the three of us is:
A: 10 rows
B: 15 rows
C: 20 rows
Topic 2: simplify code with Linq
Sometimes, Linq can help us write some very "human" statements.
The following function inserts a new comment into the database:
public static void Create(IEnumerable<CommentData> Comments, SqlConnection cn) { // validate params if (null == cn) throw new ArgumentNullException("cn"); if (cn.State != ConnectionState.Open) throw new ArgumentException("Invalid parameter: connection is not open.", "cn"); if (null == Comments) throw new ArgumentNullException("Comments"); foreach (CommentData data in Comments) { if (data.CommentId.HasValue) throw new ArgumentNullException("Create is only for saving new data. Call save for existing data.", "data"); }....
The foreach part can be simplified
if (Comments.Any(data => data.CommentId.HasValue)) { throw new ArgumentNullException("Create is only for saving new data. Call save for existing data.", "data"); }
At this point, we have differences. A thinks that there is no need to simplify it, because it is already clear. But B thinks that the simplified code is more readable and looks more direct.
Topic 3: set initial values
I hope everyone knows the usage of C # And directly add some code:
3.1
Original code:
List<int> idsToFind = new List<int>();idsToFind.Add(1);idsToFind.Add(2);
After modification:
List<int> idsToFind = new List<int> {1, 2};
3.2
Original code:
var startingPoint = new Point();startingPoint.X = 5;startingPoint.Y = 13;
After modification:
var startingPoint = new Point() { X = 5, Y = 13 };Topic 4: application? : And ??
It is said that some companies will use this to test the beginners of programmers:
4.1
Original code:
if (c != null) System.Console.WriteLine(c.Name);else System.Console.WriteLine("List element has null value.");
After modification:
System.Console.WriteLine(c != null ? c.Name : "List element has null value.");
4.2
Original code:
string name = value; if (value == null){name = string.Empty;}After modification:
string name = (value != null) ? value : string.Empty;
It can also be simpler:
string name = value ?? string.Empty;
Topic 5: UseOriginal code:
if (employee is SalariedEmployee){ var salEmp = (SalariedEmployee)employee; pay = salEmp.WeeklySalary; // ...}After modification:
var salEmployee = employee as SalariedEmployee;if (salEmployee != null){ pay = salEmployee.WeeklySalary; // ...}Topic 6: Use usingUsing first appeared in visual studio 2005. Before that, many programmers fainted in the logic of releasing resources.
The IL code generated using the using statement is actually a try, finally code block, releasing resources in the finally code block.
Original code:
public IEnumerable<Order> GetOrders(){ var orders = new List<Order>(); var con = new SqlConnection("some connection string"); var cmd = new SqlCommand("select * from orders", con); var rs = cmd.ExecuteReader(); while (rs.Read()) { // ... } rs.Dispose(); cmd.Dispose(); con.Dispose(); return orders;} This is a very ugly piece of code. We are completely lost in the dispose group. When will we call the dispose? God? If we use finally, we can write the code as follows:
Public IEnumerable <Order> GetOrders ()
{
SqlConnection con = null;
SqlCommand cmd = null;
SqlDataReader rs = null;
Var orders = new List <Order> ();
Try
{
Con = new SqlConnection ("some connection string ");
Cmd = new SqlCommand ("select * from orders", con );
Rs = cmd. ExecuteReader ();
While (rs. Read ())
{
//...
}
}
Finally
{
Rs. Dispose ();
Cmd. Dispose ();
Con. Dispose ();
}
Return orders;
}
Let's see what using brings to us:
public IEnumerable<Order> GetOrders(){ var orders = new List<Order>(); using (var con = new SqlConnection("some connection string")) { using (var cmd = new SqlCommand("select * from orders", con)) { using (var rs = cmd.ExecuteReader()) { while (rs.Read()) { // ... } } } } return orders;} Much better, right? You don't need to use that bunch of try/finally code at all, or use a bunch of null values. To make the code lighter, let's make a small modification:
public IEnumerable<Order> GetOrders(){ var orders = new List<Order>(); using (var con = new SqlConnection("some connection string")) using (var cmd = new SqlCommand("select * from orders", con)) using (var rs = cmd.ExecuteReader()) { while (rs.Read()) { // ... } } return orders;} Pending... Related reading:Topic set for writing elegant and concise code-Csharp (C #) [2]