search
HomeWeb Front-endJS TutorialSOLID principles using some fun analogies with Vehicle Example

SOLID principles using some fun analogies with Vehicle Example

SOLID is an acronym for a group of five good principles (rules) in computer programming. SOLID allows programmers to write code that is easier to understand and change later on. SOLID is often used with systems that use an object-oriented design.
Let's explain the SOLID principles using the vehicle example. Imagine we're designing a system to manage different types of vehicles, like cars and electric cars, for a transportation service.

S - Single Responsibility Principle (SRP)

Vehicle Example: Imagine you have a car. It's responsible for driving, but it shouldn't be responsible for handling its own maintenance (like oil changes or tyre rotations). Instead, a separate mechanic is responsible for that.
Explanation: In our code, the Vehicle class should only handle things related to the vehicle itself, like storing its make and model. If we need to manage maintenance, we create a separate Maintenance class for that. This way, each class has one job or responsibility, making the code easier to manage.

class Vehicle
  def initialize(make, model)
    @make = make
    @model = model
  end
end

class Maintenance
  def initialize(vehicle)
    @vehicle = vehicle
  end

  def perform_maintenance
    puts "Performing maintenance on #{@vehicle.make} #{@vehicle.model}"
  end
end

O - Open/Closed Principle (OCP)

Vehicle Example: Suppose you have a basic car, and now you want to add an electric car to your system. You shouldn't have to modify the existing car class to add features for electric cars. Instead, you can extend the existing functionality by creating a new class for electric cars.
Explanation: The Vehicle class is open for extension (you can create new types of vehicles like ElectricVehicle), but it's closed for modification (you don't need to change the Vehicle class itself to add new types).

class Vehicle
  def initialize(make, model)
    @make = make
    @model = model
  end

  def description
    "#{@make} #{@model}"
  end
end

class ElectricVehicle 




<hr>

<h2>
  
  
  L - Liskov Substitution Principle (LSP)
</h2>

<p><strong>Vehicle Example</strong>: Imagine you have a fleet of vehicles, and you can replace any regular car with an electric car without any issues. Both should be able to perform their basic function - driving - without breaking the system.<br>
<strong>Explanation</strong>: Any subclass (like ElectricVehicle) should be able to replace its parent class (Vehicle) without altering the behaviour of the program. This ensures that our code can handle different types of vehicles in the same way.<br>
</p>

<pre class="brush:php;toolbar:false">class Vehicle
  def initialize(make, model)
    @make = make
    @model = model
  end

  def drive
    puts "Driving the #{@make} #{@model}"
  end
end

class ElectricVehicle 




<hr>

<h2>
  
  
  I - Interface Segregation Principle (ISP)
</h2>

<p><strong>Vehicle Example</strong>: Imagine you have different types of vehicles: some can be charged (like electric cars), and some can only be driven (like gas cars). You don't want a gas car to have to deal with charging-related methods.<br>
<strong>Explanation</strong>: Classes should only implement the interfaces (or behaviours) they need. For example, an ElectricVehicle might implement both Drivable and Chargeable interfaces, while a regular Vehicle only implements Drivable.<br>
</p>

<pre class="brush:php;toolbar:false">module Drivable
  def drive
    raise NotImplementedError, "This #{self.class} cannot drive"
  end
end

module Chargeable
  def charge
    raise NotImplementedError, "This #{self.class} cannot be charged"
  end
end

class Vehicle
  include Drivable

  def initialize(make, model)
    @make = make
    @model = model
  end

  def drive
    puts "Driving the #{@make} #{@model}"
  end
end

class ElectricVehicle 




<hr>

<h2>
  
  
  D - Dependency Inversion Principle (DIP)
</h2>

<p><strong>Vehicle Example</strong>: Imagine a car can have different types of engines: a gas engine or an electric engine. Instead of directly depending on a specific engine type, the car should depend on a more general Engine interface so it can use any type of engine.<br>
<strong>Explanation</strong>: High-level modules (like the Vehicle) should not depend on low-level modules (like GasEngine or ElectricEngine). Both should depend on abstractions (like an Engine interface). This makes the system more flexible and easier to change.<br>
</p>

<pre class="brush:php;toolbar:false">class Engine
  def start
    raise NotImplementedError, "This #{self.class} cannot start"
  end
end

class GasEngine 



<p>By following the SOLID principles in this vehicle example, we can build a system that is easy to maintain, extend, and adapt to new requirements.</p>

<p>LinkedIn: https://www.linkedin.com/in/anandsoni11/</p>


          

            
        

The above is the detailed content of SOLID principles using some fun analogies with Vehicle Example. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

jQuery Check if Date is ValidjQuery Check if Date is ValidMar 01, 2025 am 08:51 AM

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

jQuery get element padding/marginjQuery get element padding/marginMar 01, 2025 am 08:53 AM

This article discusses how to use jQuery to obtain and set the inner margin and margin values ​​of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values ​​can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

10 jQuery Accordions Tabs10 jQuery Accordions TabsMar 01, 2025 am 01:34 AM

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

10 Worth Checking Out jQuery Plugins10 Worth Checking Out jQuery PluginsMar 01, 2025 am 01:29 AM

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

HTTP Debugging with Node and http-consoleHTTP Debugging with Node and http-consoleMar 01, 2025 am 01:37 AM

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

jquery add scrollbar to divjquery add scrollbar to divMar 01, 2025 am 01:30 AM

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools