Some Quick Coding Tips
Stuff that's helped me out over the years. Hopefully it helps you too...
I’ve been coding for a long time - I’m talking Blockbuster Video, floppy discs, VHS tapes, FIVE tv channels, baggy trousers, LinkIn Park, Limp Bizkit, Nu Metal old. Heartbeat, Brookside, Woolworths old. Remember when they buried Trevor under the patio? Nah, you probably don’t.
Yep. I’m old as shit. Luckily for you though, I’m wise and I’ve picked up a few tips. So, before I settle into my slippers and place yet another order for Just for Men, I thought I’d share a few things I’ve picked up along the way.
So yeah, here’s some tips:
Avoid premature optimisations
Don’t write code for features you "might" need in the future. Focus on what’s required now - future needs will evolve, and unnecessary code only adds complexity.
❌ Bad Example (Premature Optimisation)
class ReportGenerator
{
public function generate(string $format = 'pdf'): void
{
if ($format === 'pdf') {
$this->generatePDF();
}
// More formats planned...
}
}✅ Good Example (Keep It Lean)
class ReportGenerator
{
public function generatePDF(): void
{
// Only implements what's needed now
}
}Avoid unnecessary complexity
Simple code is easier to read, maintain, and debug.
❌ Bad Example (Over Engineered)
class DiscountCalculator
{
public function __construct(
private float $price,
bool $isMember
) {
}
public function getDiscountRate(): float
{
if ($this->isMember) {
if ($this->price > 100) {
return 0.8; // 20% discount
} else {
return 0.9; // 10% discount
}
}
return 1; // No discount
}
public function getPrice(): float
{
return $this->price * $this->getDiscountRate();
}
}
// Usage:
$calculator = new DiscountCalculator(120, true);
$finalPrice = $calculator->getDiscount();✅ Good Example (Sometimes, it really doesn’t need to be complex)
function getDiscount(float $price, bool $isMember)
{
return $isMember ? $price * ($price > 100 ? 0.8 : 0.9) : $price;
}
// Usage:
$finalPrice = getPrice(120, true);Return early
Deeply nested if statements make code harder to read and maintain. Instead of wrapping everything in layers of conditions, return as soon as you can to reduce nesting and improve clarity.
❌ Bad Example (deep nested conditional)
function processOrder(Order $order): string {
if ($order) {
if ($order->isPaid()) {
if (!$order->isShipped()) {
shipOrder($order);
return 'Order shipped!';
} else {
return 'Order already shipped.';
}
} else {
return 'Payment required.';
}
} else {
return 'Invalid order.';
}
}✅ Good Example (return early)
function processOrder(Order $order): string {
if (!$order) {
return 'Invalid order.';
}
if (!$order->isPaid()) {
return 'Payment required.';
}
if ($order->isShipped()) {
return 'Order already shipped.';
}
shipOrder($order);
return 'Order shipped!';
}Else statements, do you need them?
I rarely use else statements, how about you? If you’re using early returns, do you REALLY need them?
❌ Bad Example (redundant else)
function getUserRole(User $user): string
{
if ($user->isAdmin()) {
return 'admin';
} else {
return 'guest';
}
}✅ Good Example (No else required)
function getUserRole(User $user): string
{
if ($user->isAdmin()) {
return 'admin';
}
return 'guest';
}Avoid global states
Global states make debugging a nightmare because they can be modified from anywhere in your application, leading to unpredictable behaviour. They also make functions less pure, harder to test, and can create hidden dependencies.
❌ Bad Example (global variable)
$discount = 10; // Global variable
function calculatePrice(float $price): float
{
global $discount;
return $price - ($price * $discount / 100);
}
echo calculatePrice(100); // Output depends on global variable✅ Good Example (pass explicitly)
function calculatePrice(float $price, float $discount): float
{
return $price - ($price * $discount / 100);
}
echo calculatePrice(100, 10); // Output: 90Code comments lie
Comments are supposed to help, but they often become outdated, misleading, or just plain wrong. Code changes over time, and comments rarely get updated. Instead of relying on comments, write clear, self-explanatory code that doesn’t need them.
❌ Bad Example (outdated comment)
// Apply a 10% discount to the total price
function calculateTotal(float $price): float
{
return $price - ($price * 0.15); // Actually applies a 15% discount
}✅ Good Example (remove comment and use clear code)
function calculateTotalWithDiscount(float $price, float $discount = 0.15): float
{
return $price - ($price * $discount);
}Add breathing space
Code should be easy on the eyes, like Scarlett Johansson. Walls of tightly packed text make it harder to read, understand, and maintain. Adding whitespace (blank lines, indentation, and spacing) improves readability and reduces cognitive strain.
❌ Bad Example (your eyes?!)
function calculateTotal(array $items, float $taxRate): float{
$total=0;
foreach($items as $item){$total+=$item->price;}
return $total+($total*$taxRate);
}✅ Good Example (Scarlett edition)
function calculateTotal(array $items, float $taxRate): float {
$total = 0;
foreach ($items as $item) {
$total += $item->price;
}
return $total + ($total * $taxRate);
}Group related class variables
Scattering variables all over a class makes it difficult to understand its structure. Instead, group related variables together logically.
❌ Bad Example (scattered variables)
class Order
{
public $total;
public $customerName;
public $shippingAddress;
public $taxRate;
public $orderItems = [];
public $discount;
}✅ Good Example (grouped)
class Order
{
// Customer details
public $customerName;
public $shippingAddress;
// Order details
public $orderItems = [];
// Pricing
public $total;
public $taxRate;
public $discount;
}Group boolean return values
Scattering boolean return values throughout a function makes it hard to follow the logic. Either flip the conditionals so they’re group (i.e false, false, false, true) or restructure the order of the returns.
❌ Bad Example (scattered boolean returns)
function processOrder($order)
{
if (!$order->isPaid()) {
return false;
}
if ($order->hasStock()) { // we're returning true in-between false's
return true;
}
if ($order->isBlacklisted()) {
return false;
}
return true;
}✅ Good Example (booleans are grouped)
function processOrder($order)
{
if (!$order->isPaid()) {
return false;
}
if (!$order->hasStock()) { // we're flipped the conditional
return false;
}
if ($order->isBlacklisted()) {
return false;
}
return true;
}Order functions logically
A messy function order in a class makes it harder to navigate and understand. Functions should be grouped and ordered logically - from high-level public methods down to low-level private helpers. Think of it like an outline: the most important things first, details later.
❌ Bad Example (messy, private function at top)
class OrderProcessor
{
private function validateStock(Order $order): bool
{
return $order->hasStock();
}
public function process(Order $order): bool
{
if (!$this->validatePayment($order)) {
return false;
}
if (!$this->validateStock($order)) {
return false;
}
return $this->finaliseOrder($order);
}
private function finaliseOrder(Order $order): bool
{
return true;
}
private function validatePayment(Order $order): bool
{
return $order->isPaid();
}
}✅ Good Example (ordered by when they’re called)
class OrderProcessor
{
public function process(Order $order): bool
{
if (!$this->validatePayment($order)) {
return false;
}
if (!$this->validateStock($order)) {
return false;
}
return $this->finaliseOrder($order);
}
private function validatePayment(Order $order): bool
{
return $order->isPaid();
}
private function validateStock(Order $order): bool
{
return $order->hasStock();
}
private function finaliseOrder(Order $order): bool
{
return true;
}
}Put variables close to where they are used
Scattering variables throughout a function makes code harder to read and maintain. Declaring them just before they’re needed improves clarity and prevents unnecessary allocations.
Your code commits will also be clearer, instead of changes to several lines, you’d simply see one block of changes.
❌ Bad Example (declared too early)
function processOrder(Order $order): float|string
{
$discount = 0; // Declared early, but not used until much later
$total = $order->calculateTotal();
if (!$order->isPaid()) {
return 'Payment required';
}
if ($order->hasDiscount()) {
$discount = $order->getDiscountAmount();
}
return $total - $discount;
}✅ Good Example (Declared right before use)
function processOrder(Order $order): float|string
{
$total = $order->calculateTotal();
if (!$order->isPaid()) {
return 'Payment required';
}
$discount = $order->hasDiscount() ? $order->getDiscountAmount() : 0;
return $total - $discount;
}Convert comments to functions
If you find yourself writing comments to explain a block of code, it's often a sign that the code should be extracted into a well-named function instead. This improves readability and reusability while reducing the need for outdated or misleading comments.
❌ Bad Example (comments explaining code)
function processPayment(float $amount, User $user): string
{
// Check if user has enough balance
if ($user->balance < $amount) {
return 'Insufficient funds';
}
// Deduct the amount from user's balance
$user->balance -= $amount;
// Log the transaction
Transaction::create([
'user_id' => $user->id,
'amount' => $amount,
'status' => 'completed',
]);
return 'Payment successful';
}✅ Good Example (promoted to methods)
function processPayment(float $amount, User $user): string
{
if (!hasSufficientFunds($user, $amount)) {
return 'Insufficient funds';
}
$this->deductBalance($user, $amount);
$this->logTransaction($user, $amount);
return 'Payment successful';
}Use method name prefixes
Method name prefixes improve clarity by signaling intent. They help developers quickly understand what a function does without needing to inspect its implementation.
Common prefixes include get, set, is, has, should, fetch, and calculate.
❌ Bad Example (vague method names)
You can probably assume what they’re doing…
class Order
{
public function total($discount): float;
public function status(): string;
public function payment(): void;
}✅ Good Example (clear methods with prefixes)
But why not just be super clear?
class Order
{
public function getTotal($discount): float;
public function getStatus(): string;
public function makePayment(): void;
}And finally, enjoy it while it lasts….
Imagine being old, sitting in a quiet room, looking back on your career. The years you spent chasing the next big thing, the latest technology, the latest project - all of it flashes before your eyes.
You recall the long nights, the endless debugging, and the excitement of launching something new. But as the memories settle, it's not the code or the technology that stands out. What lingers are the people - the colleagues you worked alongside, the junior developers you mentored, the teams you led or were a part of.
You remember the conversations, the shared laughs, and even the mishaps: the time someone brought their dog into the office and it shit all over, the day someone decided to microwave salmon, or that one time when a colleague got hilariously stuck in the revolving door.
The legacy you leave behind isn’t written in the lines of code that will eventually be outdated or replaced. It’s written in the hearts and minds of the people you interacted with, the ones you helped grow, the ones you treated with kindness and respect.
Listen to Dottie..
Oh and by the way, that totally doesn’t say ANAL. Merry anal bright?! How would that work?
P.S - I’ve got a book, which offers 99 essential tips to not just survive, but thrive in this crazy mixed-up dev world. If you’re feeling generous and want to support me, go buy it.
More information can be found by visiting https://techsurvivaltips.com



