A new code review item: Initializers in Alphabetical Order
I’ve been using MZTools Visual Studio add-in for a few years. The original reason I acquired it was because of it’s sorting of code ability:
- Sorting a collection of lines
- Sorting the elements in a class by type and then alphabetical.
I had gotten frustrated by manual re-organizing of code and fighting the random dropping of code where it fell into the file. I love the use of initializers – it keeps code cleaner and easier to read (visually chunking), but with rapid evolution of code, we can often end up with something like:
1: deposit.CreditCard.AccountHolder = new AccountHolderDetail()
2: {
3: AddressLine1 = GetString(CreditCardAddressLine1),
4: AddressLine2 = GetString(CreditCardAddressLine2),
5: Company = GetString(CreditCardCompany),
6: FirstName = GetString(CreditCardFirstName),
7: LastName = GetString(CreditCardLastName),
8: PostalCode = GetString(CreditCardPostalCode),
9: AddressLine3 = GetString(CreditCardAddressLine3),
10: City = GetString(CreditCardCity),
11: NumericCountryIsoCode = UnneededCallForIso(GetGuid(CreditCardCountryId)),
12: MiddleName = GetString(CreditCardMiddleName),
13: StateProvince = GetString(CreditCardStateProvinceId)
14: };
If you are cross-checking two chunks of code, the random sequence becomes a pain and thus decreases code quality. With two clicks the code is transformed into alphabetical order and the code is a lot easier to review or cross-checking.
So properly reviewed code would be:
1: deposit.CreditCard.AccountHolder = new AccountHolderDetail()
2: {
3: AddressLine1 = GetString(CreditCardAddressLine1),
4: AddressLine2 = GetString(CreditCardAddressLine2),
5: AddressLine3 = GetString(CreditCardAddressLine3),
6: City = GetString(CreditCardCity),
7: Company = GetString(CreditCardCompany),
8: FirstName = GetString(CreditCardFirstName),
9: LastName = GetString(CreditCardLastName),
10: MiddleName = GetString(CreditCardMiddleName),
11: NumericCountryIsoCode = UnneededCallForIso(GetGuid(CreditCardCountryId)),
12: PostalCode = GetString(CreditCardPostalCode),
13: StateProvince = GetString(CreditCardStateProvinceId)
14: };
I would advocate that this be made a part of your regular code review standards, that is:
- Initializers must be used when appropriate (most of the add-in tools will suggest/prompt you to do so and automatically refactor for you).
- Initializers are in alphabetical order
Comments
Post a Comment