@Test public void addPermissionToDatabase() { new UserAuthorizer(mockUserService, mockPermissionDb).grantPermission(USER, READ_ACCESS);
// The test will fail if any of these methods is not called. verify(mockUserService).isUserActive(USER); verify(mockPermissionDb).getPermissions(USER); verify(mockPermissionDb).isValidPermission(READ_ACCESS); verify(mockPermissionDb).addPermission(USER, READ_ACCESS); }
// Verify only the state-changing method. verify(mockPermissionDb).addPermission(USER, READ_ACCESS); }
vector<pair<int, int>> polygon = ... pair<pair<int, int>, pair<int, int>> bounding_box = GetBoundingBox(polygon); int area = (bounding_box.second.first - bounding_box.first.first) * (bounding_box.second.second - bounding_box.first.second);
pair
first
second
Polygon polygon = ... int area = polygon.GetBoundingBox().GetArea();
map<UserId, string> id_to_name; map<UserId, int> id_to_age;
map<UserId, Person> id_to_person;
person_data[kName] = "Foo";
person.SetName("Foo");
Date
GetMonth
string date = "01-02-03";
Date date(Month::Feb, Day(1), Year(2003));
int timeout_secs = 5;
Duration timeout = Seconds(5);
// Bad, the type tells us what these variables are: String nameString; List<datetime> holidayDateList; // Better: String name; List<datetime> holidays;
// Overly specific names are hard to read: Monster finalBattleMostDangerousBossMonster; Payments nonTypicalMonthlyPayments; // Better, if there's no other monsters or payments that need disambiguation: Monster boss; Payments payments;
// Bad, repeating the context: class AnnualHolidaySale {int annualSaleRebate; boolean promoteHolidaySale() {...}} // Better: class AnnualHolidaySale {int rebate; boolean promote() {...}}
Add Frobber to the list of available widgets. This allows consumers to easily discover the new Frobber widget and add it to their application.
class Mammal { ... virtual Status Sleep(bool hibernate) = 0; }; class Human : public Mammal { ... virtual Status Sleep(bool hibernate) { age += hibernate ? kSevenMonths : kSevenHours; return OK; } };
class Human { ... void Sleep() { age += kSevenHours; } };
// Subtract discount from price. finalPrice = (numItems * itemPrice) - min(5, numItems) * itemPrice * 0.1;
price = numItems * itemPrice; discount = min(5, numItems) * itemPrice * 0.1; finalPrice = price - discount;
// Filter offensive words. for (String word : words) { ... }
filterOffensiveWords(words);
int width = ...; // Width in pixels.
int widthInPixels = ...;
// Safe since height is always > 0. return width / height;
checkArgument(height > 0); return width / height;
// Compute once because it’s expensive.
// Create a new Foo instance because Foo is not thread-safe.
// Note that order matters because...
@SuppressWarnings("unchecked") // The cast is safe because...
// Get all users. userService.getAllUsers();
// Check if the name is empty. if (name.isEmpty()) { ... }