The next pattern is an answer to a specific pain point??”the irritation and fluff that
can be present when writing multitiered comparisons.
4.4.2 Painless comparisons with the null coalescing operator
I suspect you dislike writing the same code over and over again as much as I do. Refactoring
can often get rid of duplication, but there are some cases that resist refactoring
surprisingly effectively. Code for Equals and Compare often falls firmly into this category
in my experience.
Suppose you are writing an e-commerce site and have a list of products. You may
wish to sort them by popularity (descending), then price, then name??”so that the fivestar-
rated products come first, but the cheapest within those come before the more
expensive ones. If there are multiple products with the same price, products beginning
with A are listed before products beginning with B. This isn??™t a problem specific
to e-commerce sites??”sorting data by multiple criteria is a fairly common requirement
in computing.
Assuming we have a suitable Product type, we can write the comparison with code
like this in C# 1:
public int Compare(Product first, Product second)
{
// Reverse comparison of popularity to sort descending
int ret = second.Popularity.CompareTo(first.Popularity);
134 CHAPTER 4 Saying nothing with nullable types
if (ret != 0)
{
return ret;
}
ret = first.
Pages:
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280