Reference
Cross-Language Patterns
Same operation, different spelling.
20+ years across 15 languages means thinking in patterns, not syntax. This maps the patterns to their language-specific implementations.
Collection Transform
C#
items
.Where(x => x.IsActive)
.Select(x => x.Name)
.ToList();Java
items.stream()
.filter(x -> x.isActive())
.map(x -> x.getName())
.collect(Collectors.toList());Python
[x.name for x in items if x.is_active]
JavaScript
items
.filter(x => x.isActive)
.map(x => x.name);Group By
C#
items
.GroupBy(x => x.Category)
.ToDictionary(g => g.Key, g => g.ToList());Java
items.stream()
.collect(Collectors.groupingBy(
Item::getCategory));Python
{k: list(v) for k, v in
itertools.groupby(
sorted(items, key=lambda x: x.category),
key=lambda x: x.category)}JavaScript
items.reduce((acc, x) => {
(acc[x.category] ??= []).push(x);
return acc;
}, {});Async / Await
C#
async Task<string> GetDataAsync() {
var result = await httpClient.GetAsync(url);
return await result.Content.ReadAsStringAsync();
}Java
CompletableFuture<String> getData() {
return httpClient.sendAsync(request,
BodyHandlers.ofString())
.thenApply(HttpResponse::body);
}Python
async def get_data() -> str:
async with aiohttp.ClientSession() as session:
resp = await session.get(url)
return await resp.text()JavaScript
async function getData() {
const resp = await fetch(url);
return await resp.text();
}Parallel Execution
C#
var results = await Task.WhenAll(
GetUsersAsync(),
GetOrdersAsync(),
GetStatsAsync());Java
try (var exec = Executors.newVirtualThreadPerTaskExecutor()) {
var futures = tasks.stream()
.map(t -> exec.submit(t))
.toList();
}Python
results = await asyncio.gather(
get_users(),
get_orders(),
get_stats())JavaScript
const [users, orders, stats] = await Promise.all([
getUsers(),
getOrders(),
getStats()
]);Lambda / Closure
C#
Func<int, int> square = x => x * x; var names = users.Select(u => u.Name);
Java
Function<Integer, Integer> square = x -> x * x;
var names = users.stream()
.map(User::getName);Python
square = lambda x: x * x names = [u.name for u in users]
JavaScript
const square = x => x * x; const names = users.map(u => u.name);
Null Safety
C#
var name = user?.Profile?.Name ?? "Unknown"; user ??= new User(); string? nullable = null;
Java
String name = Optional.ofNullable(user)
.map(User::getProfile)
.map(Profile::getName)
.orElse("Unknown");Python
name = (user and user.profile
and user.profile.name) or "Unknown"
# 3.8+ walrus
if (n := get_name()) is not None:
print(n)JavaScript
const name = user?.profile?.name ?? "Unknown"; user ??= new User();
Pattern Matching
C#
var label = shape switch {
Circle c when c.Radius > 10 => "big",
Square { Side: > 5 } => "medium",
_ => "small"
};Java
String label = switch (shape) {
case Circle c when c.radius() > 10 -> "big";
case Square s when s.side() > 5 -> "medium";
default -> "small";
};Python
match shape:
case Circle(radius=r) if r > 10:
label = "big"
case Square(side=s) if s > 5:
label = "medium"
case _:
label = "small"JavaScript
// destructuring (no native match yet)
const { type, radius, side } = shape;
const label = type === "circle" && radius > 10
? "big" : side > 5 ? "medium" : "small";Record / Data Class
C#
public record User(
string Name,
string Email,
int Age);Java
public record User(
String name,
String email,
int age) {}Python
@dataclass
class User:
name: str
email: str
age: intTypeScript
type User = {
readonly name: string;
readonly email: string;
readonly age: number;
};String Interpolation
C#
var msg = $"Hello {name}, you have {count} items";
var raw = $$"""Total: {{price:C2}}""";Java
// String.format (classic)
var msg = String.format(
"Hello %s, you have %d items", name, count);
// 21+ template
var msg = STR."Hello \{name}";Python
msg = f"Hello {name}, you have {count} items"
raw = f"Total: {price:.2f}"JavaScript
const msg = `Hello ${name}, you have ${count} items`;
const tag = html`<p>${escaped}</p>`;Iteration
C#
foreach (var item in items) { }
// with index
foreach (var (item, i) in items.Select((x, i) => (x, i))) { }Java
for (var item : items) { }
// with index
for (int i = 0; i < items.size(); i++) {
var item = items.get(i);
}Python
for item in items:
pass
# with index
for i, item in enumerate(items):
passJavaScript
for (const item of items) { }
// with index
items.forEach((item, i) => { });Generics / Constraints
C#
public T Find<T>(List<T> items)
where T : IComparable<T>
=> items.Min()!;Java
public <T extends Comparable<T>>
T find(List<T> items) {
return Collections.min(items);
} // type erasure at runtimePython
from typing import TypeVar
T = TypeVar('T', bound=Comparable)
def find(items: list[T]) -> T:
return min(items)TypeScript
function find<T extends Comparable>(
items: T[]): T {
return items.reduce((a, b) =>
a.compareTo(b) < 0 ? a : b);
}Error Handling
C#
try {
await ProcessAsync();
} catch (HttpRequestException ex) {
logger.LogError(ex, "Request failed");
} finally {
connection.Dispose();
}Java
try {
process();
} catch (IOException | SQLException ex) {
logger.error("Failed", ex);
} finally {
connection.close();
} // checked exceptions enforcedPython
try:
process()
except (IOError, ValueError) as ex:
logger.error(f"Failed: {ex}")
finally:
connection.close()JavaScript
try {
await process();
} catch (error) {
console.error("Failed:", error.message);
} finally {
connection.close();
} // no typed catchesInterface / Protocol
C#
public interface IRepository<T> {
Task<T?> GetByIdAsync(int id);
Task<IEnumerable<T>> GetAllAsync();
Task SaveAsync(T entity);
}Java
public interface Repository<T> {
Optional<T> findById(int id);
List<T> findAll();
void save(T entity);
}Python
class Repository(Protocol[T]):
def get_by_id(self, id: int) -> T | None: ...
def get_all(self) -> list[T]: ...
def save(self, entity: T) -> None: ...TypeScript
interface Repository<T> {
getById(id: number): Promise<T | null>;
getAll(): Promise<T[]>;
save(entity: T): Promise<void>;
}Dependency Injection
C#
builder.Services.AddScoped<IUserService, UserService>();
// constructor injection
public class Controller(IUserService users) { }Java
@Service
public class UserService { }
// constructor injection (Spring)
@RestController
public class Controller {
private final UserService users;
Controller(UserService users) {
this.users = users;
}
}Python
# FastAPI
def get_db():
db = SessionLocal()
try: yield db
finally: db.close()
@app.get("/users")
def list_users(db: Session = Depends(get_db)):
return db.query(User).all()JavaScript
// manual / factory pattern
const createService = (db, logger) => ({
getUsers: () => db.query("SELECT ..."),
log: (msg) => logger.info(msg)
});Decorator / Attribute
C#
[HttpGet("/users")]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> GetUsers()
=> Ok(await _service.GetAllAsync());Java
@GetMapping("/users")
@PreAuthorize("hasRole('ADMIN')")
public List<User> getUsers() {
return service.findAll();
}Python
@app.get("/users")
@require_role("admin")
async def get_users(
db: Session = Depends(get_db)
) -> list[User]:
return db.query(User).all()TypeScript
// stage 3 decorators
@Controller("/users")
class UserController {
@Get() @Auth("admin")
getUsers() {
return this.service.findAll();
}
}Destructuring
C#
var (name, age) = GetPerson();
// positional pattern
if (point is (> 0, > 0)) { }
var (x, y, _) = coords;Java
// record deconstruction (21+)
if (obj instanceof Point(int x, int y)) {
System.out.println(x + ", " + y);
}Python
name, age = get_person() first, *rest = items x, y, _ = coords # nested ((a, b), c) = nested_tuple
JavaScript
const { name, age } = person;
const [first, ...rest] = items;
const { data: { users } } = response;
// defaults
const { port = 3000 } = config;