The Coding Principles
π‘ The Coding Principles β The Secret Sauce Behind Every Great Developer! π
Coding isnβt just about making things work β itβs about making them beautiful, efficient, and maintainable. β¨ Whether youβre a beginner or an experienced developer, understanding the core coding principles is like mastering the grammar of software craftsmanship.
In this blog, weβll uncover all the major principles β from SOLID to DRY, KISS, and beyond β with examples to help you write clean, scalable, and professional code. π§ π»
π§± 1. SOLID Principles β The Foundation of Object-Oriented Design
The SOLID principles are a set of five golden rules coined by Robert C. Martin (Uncle Bob). They help developers build software that is easy to maintain, extend, and refactor.
π§© S β Single Responsibility Principle (SRP)
A class should have one and only one reason to change.
Each class or module should focus on one specific functionality.
Example (Bad β):
class Report
def generate_pdf
# logic to generate PDF
end
def send_email
# logic to send email
end
end
Better β :
class ReportGenerator
def generate_pdf
# logic for PDF generation
end
end
class EmailSender
def send_email
# logic for email
end
end
π Benefit: Easier testing and better code organization.
π O β Open/Closed Principle
Software entities should be open for extension, but closed for modification.
You should be able to add new functionality without changing existing code.
Example β (Using inheritance):
class Payment
def pay
raise NotImplementedError
end
end
class CreditCardPayment < Payment
def pay
puts "Paid via Credit Card"
end
end
class PayPalPayment < Payment
def pay
puts "Paid via PayPal"
end
end
π Now, you can add a new payment type without altering existing classes.
π L β Liskov Substitution Principle
Subclasses should be replaceable with their parent classes without breaking the app.
This ensures consistency in behavior when child classes are used in place of their parent.
Example β:
class Bird
def fly
puts "I can fly"
end
end
class Penguin < Bird
def fly
raise "I can't fly!"
end
end
Better β :
class Bird; end
class FlyingBird < Bird
def fly
puts "I can fly"
end
end
class Penguin < Bird
def swim
puts "I can swim"
end
end
π§ I β Interface Segregation Principle
No client should be forced to depend on methods it does not use.
Break big interfaces into smaller, more specific ones.
Example β :
module Printer
def print; end
end
module Scanner
def scan; end
end
class MultiFunctionPrinter
include Printer
include Scanner
end
class SimplePrinter
include Printer
end
π D β Dependency Inversion Principle
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Example β :
class Notification
def initialize(messenger)
@messenger = messenger
end
def send_message
@messenger.send
end
end
class EmailMessenger
def send
puts "Sending Email..."
end
end
notification = Notification.new(EmailMessenger.new)
notification.send_message
π§Ό 2. DRY β Donβt Repeat Yourself
Avoid duplication of logic. Repetition leads to inconsistency.
Example β:
def calculate_area_of_square(side)
side * side
end
def calculate_area_of_rectangle(length, width)
length * width
end
Better β :
def calculate_area(shape)
shape.area
end
π One method can now handle multiple shapes through polymorphism!
π‘ 3. KISS β Keep It Simple, Stupid
Complexity is the enemy of execution. Write code that is simple, readable, and direct.
Example β:
def check_even(num)
if num % 2 == 0
return true
else
return false
end
end
Better β :
def check_even(num)
num.even?
end
πͺ 4. YAGNI β You Arenβt Gonna Need It
Donβt add functionality until itβs necessary.
Adding extra features βjust in caseβ leads to wasted effort and complexity.
Example β:
class Order
def apply_discount
# not used yet, maybe in future?
end
end
Better β : Only implement when thereβs a real requirement.
π§° 5. Separation of Concerns
Divide your program into distinct sections, each handling a specific concern.
In Rails, this is a core principle:
- Models β Handle data
- Views β Handle presentation
- Controllers β Handle logic
Example β :
# Controller
class UsersController
def show
@user = User.find(params[:id])
end
end
π§© 6. Composition Over Inheritance
Prefer using composition (mixing smaller classes/modules) rather than deep inheritance chains.
Example β :
module Flyable
def fly
puts "Flying high"
end
end
class Bird
include Flyable
end
π Flexible, reusable, and avoids βdiamond inheritanceβ problems.
π§ 7. Law of Demeter (LoD) β Talk to Friends, Not Strangers
A method should only call methods of:
- Itself
- Its parameters
- Its own fields
Example β:
customer.order.payment.process
Better β :
customer.process_payment
Encapsulate internal details β keep code loosely coupled!
βοΈ 8. Clean Code Practices
- Use meaningful names (
user_count>x1) - Write small, focused methods
- Avoid long parameter lists
- Comment why, not what
- Refactor regularly π
π¬ Final Thoughts
These principles are not rules β theyβre guides π§ that lead you to elegant, robust, and maintainable software. The more you follow them, the more your code becomes an art rather than a task. π¨
π¬ βAny fool can write code that a computer can understand. Good programmers write code that humans can understand.β β Martin Fowler
Keep learning, keep refining, and keep coding clean. ππ»
© Lakhveer Singh Rajput - Blogs. All Rights Reserved.