1. Nếu có thể viết if single line => Hãy dùng ngay
// Before
if (condition) {
any_number_of_statements;
}
// After
if(condition)
single_compact_statement;
Tham khảo: https://softwareengineering.stackexchange.com/questions/16528/single-statement-if-block-braces-or-no
2. Tránh Poor If condition
Một poor if condition là một câu lệnh if mà người đọc vào chả hiểu gì. Vì vậy bạn nên tránh viết câu lệnh if phức tạp. Cách tốt nhất là tạo 1 biến với tên phù hợp & sử dụng nó trong lệnh if
// Before
if (((ageTires > 15 || gapOpponent >= 22 || lowGrip) && (pitStopsRemaining > 0)) &&
(tireWear == TireWear.High) && (lapTime < (avgLapTime * 0.98)))
{
Console.WriteLine("Notify the driver. It's time for a pit stop to get new tires.");
}
// After
var isExpiredTire = ((ageTires > 15 || gapOpponent >= 22 || lowGrip) && (pitStopsRemaining > 0));
var isWearLimit = (tireWear == TireWear.High) && (lapTime < (avgLapTime * 0.98));
if(isExpiredTire && isWearLimit){
Console.WriteLine("Notify the driver. It's time for a pit stop to get new tires.");
}
2. Tránh if else nhiều nhất nếu có thể
2.1 Nếu có thể dùng switch case => Just do it
// Before
if(condition1)
else if(condition2)
else if(condition3)
else
// After
swith(condition)
case 1:
case 2:
case 3:
default:
2.1 Tận dụng Early return
Nếu bạn có thể early return trong 1 method => just do it now
Việc code như thế này sẽ làm cho:
- code bạn dễ đọc hiểu và độc lập hơn rất nhiều
- tránh if else làm câu lệnh rẽ nhánh nhiều
// Before
bool TryDo(Class1 obj, SomeEnum type)
{
if (obj.CanDo(type))
{
return Do(obj);
}
else
{
return false;
}
}
// After
bool TryDo(Class1 obj, SomeEnum type)
{
if (obj.CanDo(type))
{
return Do(obj);
}
return false;
}
Combine lệnh if lại thành một lệnh
Nếu câu if của bạn có duy nhất một if lồng bên trong => Bạn có thể dùng toán tử &&
để gom lại thành 1 if
Việc này sẽ có 2 lợi ích
- Giúp class của chúng ta giảm line of code
- Dễ đọc hiểu hơn
// Before
if(isHaveData){
if(isValidId){
}
}
// After
if(isHaveData && isValidId){ }