Hardcoded property names break on refactoring. nameof() generates string from code symbol safely. ❌ Magic String (Breaks on Rename): public class User { public string Name { get; set; } } // Later in code: if (propertyName == “Name”) // Typo-prone, breaks if User.Name renamed! ✅ nameof (Refactor-Safe): if (propertyName == nameof(User.Name)) // Compile-time checked! […]
Author: ErcanOPAK
C#: Use async/await All The Way – Don’t Block
Mixing async and blocking (.Result, .Wait()) causes deadlocks. Go async all the way! ❌ Deadlock Prone: public void DoWork() { var result = GetDataAsync().Result; // DEADLOCK risk! } public async Task GetDataAsync() { return await httpClient.GetFromJsonAsync(url); } ✅ Proper Async: public async Task DoWorkAsync() { var result = await GetDataAsync(); // No blocking! } public […]
C#: Use using Statement for Automatic Resource Disposal
Forgetting to dispose resources causes memory leaks. using statement guarantees disposal even if exception occurs. ❌ Manual Disposal (Risky): var stream = File.OpenRead(“file.txt”); // If exception here, stream never closed! var data = ReadData(stream); stream.Dispose(); ✅ Automatic (Safe): using (var stream = File.OpenRead(“file.txt”)) { var data = ReadData(stream); } // stream.Dispose() called automatically, even on […]
C#: Use StringBuilder for String Concatenation in Loops
String concatenation in loops creates tons of objects. StringBuilder is 100x faster. ❌ Slow (String Concat): string result = “”; for (int i = 0; i < 10000; i++) { result += i.ToString(); // Creates new string each time! } // 10,000 string objects created = slow + GC pressure ✅ Fast (StringBuilder): var sb […]
SQL: Use EXISTS Instead of IN for Better Performance
IN processes entire subquery. EXISTS stops at first match (faster). Slow (IN): SELECT * FROM Customers WHERE CustomerId IN ( SELECT CustomerId FROM Orders WHERE Total > 1000 ); — Processes ALL matching orders Fast (EXISTS): SELECT * FROM Customers c WHERE EXISTS ( SELECT 1 FROM Orders o WHERE o.CustomerId = c.CustomerId AND o.Total […]
SQL: Use UNION ALL Instead of UNION When Duplicates Don’t Matter
UNION removes duplicates (expensive operation). UNION ALL keeps them (fast). UNION (Slow): SELECT Name FROM ActiveUsers UNION SELECT Name FROM InactiveUsers; — Removes duplicates: Sorts, scans, filters — Slow on large datasets! UNION ALL (Fast): SELECT Name FROM ActiveUsers UNION ALL SELECT Name FROM InactiveUsers; — Keeps duplicates: No sorting or filtering — Much faster! […]
.NET Core: Use HttpClientFactory to Prevent Socket Exhaustion
Creating new HttpClient instances exhausts sockets. HttpClientFactory manages client lifecycle properly. ❌ Wrong: using var client = new HttpClient(); // Socket exhaustion! var response = await client.GetAsync(url); ✅ Right: // Program.cs builder.Services.AddHttpClient(“MyAPI”, client => { client.BaseAddress = new Uri(“https://api.example.com”); }); // Service public class MyService { private readonly IHttpClientFactory _factory; public MyService(IHttpClientFactory factory) { _factory […]
.NET Core: Use ActionFilters for Cross-Cutting Concerns
Logging, validation, auth in every controller is repetitive. ActionFilters apply logic globally or per-controller. Create Filter: public class LoggingFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { // Before action Console.WriteLine($”Executing: {context.ActionDescriptor.DisplayName}”); } public void OnActionExecuted(ActionExecutedContext context) { // After action Console.WriteLine($”Executed: {context.ActionDescriptor.DisplayName}”); } } Apply Globally: builder.Services.AddControllers(options => { options.Filters.Add(); }); Or apply to […]
Git: Use git commit –amend to Fix Last Commit Without New Commit
Forgot to add file or typo in commit message? –amend fixes last commit without creating new one. Fix Commit Message: git commit –amend -m “Corrected message” Add Forgotten Files: git add forgotten_file.js git commit –amend –no-edit # Add to last commit, keep message ⚠️ Warning: Never amend commits that are already pushed! Rewrites history = […]
Git: Use git diff –staged to Review Changes Before Commit
Committing without review leads to mistakes. –staged shows exactly what will be committed. See Staged Changes: git diff –staged # Shows changes that are staged (git add-ed) for commit vs git diff: git diff (no flags) shows unstaged changes only. –staged shows what’s going into the commit. Review Workflow: git add . git diff –staged […]
AJAX: Use Response Type for Automatic Data Parsing
Manually parsing response JSON is error-prone. Set responseType to let fetch handle it. Manual Parsing: const response = await fetch(url); const text = await response.text(); const data = JSON.parse(text); // Error-prone! Automatic: const response = await fetch(url); const data = await response.json(); // Automatic! // Or for blob: const blob = await response.blob(); // Or […]
JavaScript: Use globalThis for Universal Global Object Access
Accessing global object is different everywhere: window (browser), global (Node), self (workers). globalThis works everywhere. The Problem: // Browser window.myVar = ‘test’; // Works // Node.js global.myVar = ‘test’; // Works // Web Worker self.myVar = ‘test’; // Works Universal Solution: globalThis.myVar = ‘test’; // Works everywhere! Write once, run in browser, Node, workers, Deno […]
HTML5: Use the dialog Element for Native Modal Dialogs
Building modals with divs and JavaScript is complex. HTML5 dialog element provides native modal functionality. Basic Usage: Modal Title Modal content here Close Open Modal Features: Automatic backdrop, ESC key closes, focus trap, accessible by default! Styling: dialog::backdrop for backdrop styling. Fully customizable with CSS. Native, accessible, no library needed!
CSS: Use :is() and :where() to Simplify Complex Selectors
Writing the same selector multiple times is verbose. :is() groups them cleanly. Old Way (Verbose): header h1, header h2, header h3, footer h1, footer h2, footer h3 { color: blue; } With :is(): :is(header, footer) :is(h1, h2, h3) { color: blue; } :where() vs :is(): Same syntax, but :where() has 0 specificity (won’t override other […]
Windows 11: Use Efficiency Mode to Limit Resource-Hungry Apps
Chrome eating all your RAM? Efficiency Mode throttles resource usage of specific processes. Enable: Task Manager → Processes tab → Right-click app → Efficiency Mode What It Does: Lowers process priority, reduces CPU usage, limits background activity. App still runs but uses fewer resources. Perfect For: Apps you keep open but rarely use actively (Slack, […]
Windows 11: Use Dynamic Refresh Rate for Better Battery Life
Running 120Hz constantly drains battery. Dynamic Refresh Rate adjusts automatically based on content. Enable: Settings → System → Display → Advanced Display → Choose Refresh Rate → Dynamic How It Works: Scrolling/gaming = 120Hz. Static content = 60Hz. Battery life improves 20-30% on laptops! Requirements: Display that supports variable refresh rate (VRR). Most modern gaming […]
AI Prompt: Optimize SQL Queries with Execution Plan Analysis
Slow query but don’t know why? AI analyzes execution plans and suggests optimizations. The Prompt: Optimize this SQL query: [Paste SQL query] Execution plan shows: [Paste execution plan or describe bottleneck] Database: [PostgreSQL/MySQL/SQL Server] Table row counts: [Approximate sizes] Provide: 1. Identified performance issues 2. Optimized query with explanation 3. Index recommendations 4. Query rewrite […]
AI Prompt: Create Regex Patterns with Explanations
Regex is cryptic. AI writes and explains patterns in plain English. The Prompt: Create a regex pattern for: [Describe what you want to match – e.g., “email addresses”, “phone numbers in format (XXX) XXX-XXXX”, “URLs with optional protocol”] Requirements: – Pattern for [language/tool – e.g., JavaScript, Python, grep] – Explain what each part means – […]
AI Prompt: Generate Comprehensive Test Cases from Requirements
Writing test cases manually is tedious. AI generates comprehensive test scenarios including edge cases. The Prompt: Generate test cases for this feature: [Paste feature requirements/user story] Include: 1. Happy path scenarios 2. Edge cases 3. Error handling scenarios 4. Boundary value tests 5. Negative test cases 6. Security test cases (injection, auth bypass) Format each […]
Docker: Use Build Cache Effectively with Layer Ordering
Dockerfile layer order dramatically affects build speed. Put changing layers last, stable layers first. Bad (Slow Rebuilds): FROM node:18 COPY . /app RUN npm install Every code change invalidates npm install cache! Good (Fast Rebuilds): FROM node:18 WORKDIR /app COPY package*.json ./ RUN npm install # Cached unless package.json changes! COPY . . # Code […]
Kubernetes: Use Kustomize for Environment-Specific Configurations
Maintaining separate YAML files for dev/staging/prod is messy. Kustomize manages variations without duplication. Base Configuration: # base/deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: myapp spec: replicas: 2 template: spec: containers: – name: app image: myapp:latest Production Override: # overlays/production/kustomization.yaml resources: – ../../base patchesStrategicMerge: – replicas.yaml # Sets replicas: 10 – image.yaml # Sets image: myapp:1.5.3 […]
WordPress: Use wp_cache API for Object Caching Without Plugin
Repeated database queries kill performance. wp_cache API provides in-memory object caching natively. Cache Expensive Query: $cache_key = ‘popular_posts’; $posts = wp_cache_get($cache_key); if ($posts === false) { // Cache miss – query database $posts = $wpdb->get_results(“SELECT * FROM wp_posts WHERE …..”); wp_cache_set($cache_key, $posts, ”, 3600); // Cache 1 hour } return $posts; Note: Works with persistent […]
WordPress: Use Custom Post Statuses Beyond Draft and Published
Stuck with just Draft/Published/Scheduled? Register custom post statuses for better editorial workflow. Register Status: register_post_status(‘in_review’, array( ‘label’ => ‘In Review’, ‘public’ => false, ‘show_in_admin_all_list’ => true, ‘show_in_admin_status_list’ => true )); Add to Quick Edit: add_filter(‘display_post_states’, function($states, $post) { if (get_post_status($post->ID) == ‘in_review’) { $states[] = ‘In Review’; } return $states; }, 10, 2); Perfect for […]
Photoshop: Use Camera Raw Filter for Non-Destructive Raw-Style Editing
Camera Raw isn’t just for RAW files. Use it as a filter on any layer for powerful non-destructive editing. Apply: Convert layer to Smart Object → Filter → Camera Raw Filter Why Smart Object: Filter becomes editable anytime. Double-click filter name in layers panel to re-adjust settings later! Powerful Controls: Exposure, contrast, highlights, shadows, whites, […]
Photoshop: Use Curves Adjustment for Professional Color Grading
Levels are basic. Curves give you surgical precision over color and tone. This is how professionals color grade. Access: Layer → New Adjustment Layer → Curves The RGB Curve: Drag middle upward = brighten midtones. Drag downward = darken. S-curve = increase contrast. Individual Color Channels: Switch from RGB to Red/Green/Blue channels. Pull red curve […]
Visual Studio: Use Live Unit Testing to See Test Results While Coding
Running tests manually after every change is slow. Live Unit Testing runs tests automatically as you type and shows results inline. Enable: Test → Live Unit Testing → Start Visual Indicators: Green checkmark = passing tests, Red X = failing tests, Blue dash = not covered by tests. Shows directly in code editor margin! Performance: […]
C#: Moving from Runtime Reflection to Build-Time Source Generators
Reflection is slow and not AOT-friendly. Source Generators allow you to generate code during the build process, making your apps faster and ready for Native AOT (Ahead-of-Time) compilation.
C#: Professional Dependency Injection – Avoiding Captive Dependencies
A ‘Captive Dependency’ happens when a Singleton service depends on a Scoped service. This can lead to memory leaks and incorrect state. Learn how to use IServiceScopeFactory to handle this correctly.
C#: Achieving Zero-Allocation Parsing with Span and ReadOnlySpan
If you process large strings or byte arrays, Substring() creates new objects on the heap. Span<T> provides a window into the memory without copying it. Impact: Massive reduction in Garbage Collection (GC) pressure for high-traffic apps.
SQL: Identifying and Preventing Deadlocks in High-Concurrency Systems
Deadlocks occur when two processes wait for each other to release locks. Learn how to use Extended Events to capture deadlock graphs and rewrite queries to avoid ‘Victim’ status.























