提高可读性,3 个让代码更简洁的小技巧
MichalYMU
8年前
<p>在完成代码重构之后,我总是会获得一种莫名的成就感。其实,不仅是大规模的代码重构能给我带来这种感觉,一些小的修改也能让我感到很高兴。以下3个简单的重构技巧就能帮你改善代码的可读性。</p> <h3>1. 清理格式</h3> <p>代码的整体格式最能影响代码的可读性,让你迅速找到需要的代码。正确的缩进、分行和模式能帮助开发者省去大量的无用代码。你可以看看下面两种格式的比较。先看第一个格式:</p> <pre> Inventory inventory = new Inventory(); for (int i = 0; i < cars.Count; i++){ inventory.Cars.Add(cars[i]); var owner = owners.Where(x => x.VIN == cars[i].VIN).OrderByDescending(x => x.PurchaseDate).FirstOrDefault(); inventory.PreviousOwners.Add(new Owner { VIN = cars[i].VIN, Name = owner.Name}); }</pre> <p>再和下面这种格式比较一下:</p> <pre> Inventory inventory = new Inventory(); for (int i = 0; i < cars.Count; i++) { inventory.Cars.Add(cars[i]); var owner = owners.Where(x => x.VIN == cars[i].VIN) .OrderByDescending(x => x.PurchaseDate) .FirstOrDefault(); inventory.PreviousOwners.Add(new Owner { VIN = cars[i].VIN, Name = owner.Name }); }</pre> <p>第二种格式使用了正确的缩进、分行和模式,提高了代码的可读性。</p> <p>书籍有章节、标题和正文,这种格式让我们可以快速找到需要的内容。代码其实也一样,好的格式可以提高可读性。</p> <h3>2.对类、方法和变量进行重命名</h3> <p>类、方法和变量的命名,应该可以帮助开发者更好的了解代码作用。对象的范围越短,其名字也可以更短一些。</p> <p>在编写项目的第一稿时,我们总是喜欢使用一些信息量不足的名称,但是这样的命名方式在后期并不是最好的选择。</p> <p>请看下面的代码:</p> <pre> public IEnumerable<string> GetData(int year) { var result = CallApi("/Cars", year); IEnumerable<string> output = new IEnumerable<string>(); foreach(var c in result) { output.Add(c.Make); } }</pre> <p>对比:</p> <pre> public IEnumerable<string> RetrieveCarMakes(int year) { var inventory = CallApi("/Cars", year); IEnumerable<string> carMakes = new IEnumerable<string>(); foreach(var car in inventory) { carMakes.Add(car.Make); } }</pre> <p>使用有实际意义的名称,能让其他人以及你自己更好的理解代码的作用。</p> <h3>3. 拆分较长的表达式</h3> <p>在写代码的时候,一些人很容易为了追求速度使用连锁命令,或是使用单行句法。很多时候,我在回看之前写的代码的时候,我就会发现很多这样的长表达式。看看下面两段代码的区别:</p> <pre> bool hasHighSaleProbability = (daysOnLot < 60) ? true : (color == "Red" ? true : false); var highSaleProbabilityVehicles = Inventory.Where(x => x.DaysOnLot < 60 or x.Color == "Red").Select(x => new { Make = x.Make, Model = x.Model, Year = x.Year }).Distinct().Select(x => new RecentInventoryView { YearDropdown = new SelectListItem { Text = x.Year, Value = x.Year }, MakeModelDropdown = new SelectListItem { Text = x.Make + " " + x.Model, Value = x.Make + " " + x.Model } });</pre> <p>拆分后:</p> <pre> bool hasHighSaleProbability = false; if (daysOnLot < 60 || color == "Red") { hasHighSaleProbability = true; } var distinctMakesModelsYears = Inventory .Where(x => x.DaysOnLot < 60 or x.Color == "Red") .Select(x => new { Make = x.Make, Model = x.Model, Year = x.Year }) .Distinct() .ToList(); var recentInventoryView = distinctMakesModelsYears .Select(x => new RecentInventoryView { YearDropdown = new SelectListItem { Text = x.Year, Value = x.Year }, MakeModelDropdown = new SelectListItem { Text = x.Make + " " + x.Model, Value = x.Make + " " + x.Model } });</pre> <p>虽然第一段代码更短,行数也更少,但是其可读性非常差。而第二段代码由于拆分了if逻辑,并且将所有连锁方法也进行了拆分,结果就是让其变得更好理解。</p> <p> </p> <p> </p> <p>来自:https://www.oschina.net/news/82928/3-insanely-make-to-clean-up-your-code</p> <p> </p>