Skip to content

Instantly share code, notes, and snippets.

@tuannguyenssu
Created July 14, 2019 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuannguyenssu/050182bc37baa14edc476c873ffdd715 to your computer and use it in GitHub Desktop.
Save tuannguyenssu/050182bc37baa14edc476c873ffdd715 to your computer and use it in GitHub Desktop.
//--------------------------------------------------------------------------------------
// 2. Variables - Biến
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
// Return kết quả càng sớm càng tốt
// Bad
public bool IsShopOpen(string day)
{
if (!string.IsNullOrEmpty(day))
{
day = day.ToLower();
if (day == "friday")
{
return true;
}
else if (day == "saturday")
{
return true;
}
else if (day == "sunday")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public long Fibonacci(int n)
{
if (n < 50)
{
if (n != 0)
{
if (n != 1)
{
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
else
{
return 1;
}
}
else
{
return 0;
}
}
else
{
throw new System.Exception("Not supported");
}
}
// Good
public bool IsShopOpen(string day)
{
if (string.IsNullOrEmpty(day))
{
return false;
}
var openingDays = new[] { "friday", "saturday", "sunday" };
return openingDays.Any(d => d == day.ToLower());
}
public long Fibonacci(int n)
{
if (n == 0)
{
return 0;
}
if (n == 1)
{
return 1;
}
if (n > 50)
{
throw new System.Exception("Not supported");
}
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
//--------------------------------------------------------------------------------------
// Tránh đặt tên biến một cách chung chung không rõ nghĩa
// Bad
var l = new[] { "Austin", "New York", "San Francisco" };
for (var i = 0; i < l.Count(); i++)
{
var li = l[i];
DoStuff();
DoSomeOtherStuff();
// ...
// ...
// ...
// Wait, what is `li` for again?
Dispatch(li);
}
// Good
var locations = new[] { "Austin", "New York", "San Francisco" };
foreach (var location in locations)
{
DoStuff();
DoSomeOtherStuff();
// ...
// ...
// ...
Dispatch(location);
}
//--------------------------------------------------------------------------------------
// Tránh các magic string
// Bad
if (userRole == "Admin")
{
// logic in here
}
// Good
const string ADMIN_ROLE = "Admin";
if (userRole == ADMIN_ROLE)
{
// logic in here
}
//--------------------------------------------------------------------------------------
// Tránh việc lặp lại tên class trong tên các biến hoặc phương thức
// Bad
public class Car
{
public string CarMake { get; set; }
public string CarModel { get; set; }
public string CarColor { get; set; }
//...
}
// Good
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
public string Color { get; set; }
//...
}
//--------------------------------------------------------------------------------------
// Đặt tên biến một cách có ý nghĩa và có thể phát âm được
// Bad
var ymdstr = DateTime.UtcNow.ToString("MMMM dd, yyyy");
// Good
var currentDate = DateTime.UtcNow.ToString("MMMM dd, yyyy");
//--------------------------------------------------------------------------------------
// Sử dụng cùng một từ vựng cho cùng một loại biến
// Bad
GetUserInfo();
GetUserData();
GetUserRecord();
GetUserProfile();
// Good
GetUser();
//--------------------------------------------------------------------------------------
// Đặt tên biến có thể tìm kiếm được
// Bad
// What the heck is data for?
var data = new { Name = "John", Age = 42 };
var stream1 = new MemoryStream();
var ser1 = new DataContractJsonSerializer(typeof(object));
ser1.WriteObject(stream1, data);
stream1.Position = 0;
var sr1 = new StreamReader(stream1);
Console.Write("JSON form of Data object: ");
Console.WriteLine(sr1.ReadToEnd());
var data = new { Name = "John", Age = 42, PersonAccess = 4};
// What the heck is 4 for?
if (data.PersonAccess == 4)
{
// do edit ...
}
// Good
var person = new Person
{
Name = "John",
Age = 42
};
var stream2 = new MemoryStream();
var ser2 = new DataContractJsonSerializer(typeof(Person));
ser2.WriteObject(stream2, data);
stream2.Position = 0;
var sr2 = new StreamReader(stream2);
Console.Write("JSON form of Data object: ");
Console.WriteLine(sr2.ReadToEnd());
public enum PersonAccess : int
{
ACCESS_READ = 1,
ACCESS_CREATE = 2,
ACCESS_UPDATE = 4,
ACCESS_DELETE = 8
}
var person = new Person
{
Name = "John",
Age = 42,
PersonAccess= PersonAccess.ACCESS_CREATE
};
if (person.PersonAccess == PersonAccess.ACCESS_UPDATE)
{
// do edit ...
}
//--------------------------------------------------------------------------------------
// Đặt tên biến có sự hàm chứa giải thích trong đó
// Bad
const string Address = "One Infinite Loop, Cupertino 95014";
var cityZipCodeRegex = @"/^[^,\]+[,\\s]+(.+?)\s*(\d{5})?$/";
var matches = Regex.Matches(Address, cityZipCodeRegex);
if (matches[0].Success == true && matches[1].Success == true)
{
SaveCityZipCode(matches[0].Value, matches[1].Value);
}
// Good
const string Address = "One Infinite Loop, Cupertino 95014";
var cityZipCodeWithGroupRegex = @"/^[^,\]+[,\\s]+(?<city>.+?)\s*(?<zipCode>\d{5})?$/";
var matchesWithGroup = Regex.Match(Address, cityZipCodeWithGroupRegex);
var cityGroup = matchesWithGroup.Groups["city"];
var zipCodeGroup = matchesWithGroup.Groups["zipCode"];
if(cityGroup.Success == true && zipCodeGroup.Success == true)
{
SaveCityZipCode(cityGroup.Value, zipCodeGroup.Value);
}
//--------------------------------------------------------------------------------------
// Sử dụng các default parameters thay vì kiểm tra điều kiện
// Bad
public void CreateMicrobrewery(string name = null)
{
var breweryName = !string.IsNullOrEmpty(name) ? name : "Hipster Brew Co.";
// ...
}
// Good
public void CreateMicrobrewery(string breweryName = "Hipster Brew Co.")
{
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment