Have you ever used a tool, but then discovered that you were using it incorrectly? Maybe you saw someone else using the tool less than optimally?
Hammers come in a variety of types, all suited for specific purposes. Most people will be familiar with the claw hammer, a hammer with one side with a flat plane that is pretty much perpendicular to the central axis of the handle, and the other side has a curved piece of metal that is split: the claw. The claw is useful for pulling nails out of the wood
There are also many other types of hammers such as, ball peen, chipping, sledge. Each has been designed for a specific use case. While you could drive a nail in with a sledgehammer, you may be better reaching for a claw hammer.
But what if, you reach for the claw hammer, and use the claw to hit the nails in?
Well, in a specific scenario, I observed a dev using the claw hammer but hitting the nails in with the claw. Now this is quite impressive, but seemingly significantly harder. In this situation, the developer knew of LINQ and Entity Framework, but didn’t completely understand the use of LINQ.
Claw Side of the Hammer – Contrived LINQ Usage
using (var context = new QualityControlContext())
{
var allEquipment = context.Equipment.ToList();
var expiredCertifications = new List<Equipment>();
foreach (var equipment in allEquipment)
{
bool hasExpiredCertification = false;
foreach (var qc in equipment.QualityCertifications)
{
if (qc.ExpiryDate < DateTime.UtcNow)
{
hasExpiredCertification = true;
break; // Found an expired certification, no need to check further
}
}
if (hasExpiredCertification)
{
expiredCertifications.Add(equipment);
}
}
foreach (var equipment in expiredCertifications)
{
Console.WriteLine($"Equipment ID: {equipment.Id} has expired certifications.");
}
}C#Why is this like using the claw to drive the nail?
- Unnecessary effort: Pulls all equipment into memory first, rather than filtering at the database.
- Overly complex: Uses loops and extra variables (
hasExpiredCertification) when LINQ could have done it in one line. - Still works, but painfully: Just like using the hammer’s claw to drive a nail—technically possible but ridiculously inefficient.
Flat Face of the Hammer – Correct LINQ Usage
using (var context = new QualityControlContext())
{
var expiredCertifications = context.Equipment
.Where(e => e.QualityCertifications.Any(qc => qc.ExpiryDate < DateTime.UtcNow))
.ToList();
foreach (var equipment in expiredCertifications)
{
Console.WriteLine($"Equipment ID: {equipment.Id} has expired certifications.");
}
}C#🔹 Why is this like using the hammer correctly?
- Direct, efficient filtering: It checks each piece of equipment at the database level before pulling results into memory.
- Simple and readable: Uses
Any()for checking expired certifications inline, making the query concise. - Minimal effort, maximum impact: Just like using the hammer’s flat face, this approach gets the job done with minimal steps.
