This slides will explain you how to use SOLID principles, its benefit with Ruby code example. SOLID principle helps for designing your code in more better way.
This document discusses object-oriented design principles and patterns. It introduces the SOLID principles: single responsibility, open-closed, Liskov substitution, interface segregation, and dependency inversion. These principles aim to create flexible, reusable, and extensible code. Other principles discussed include composition over inheritance and least knowledge. Common design patterns are inspired by these principles to provide solutions for recurring problems. The document emphasizes that applying object-oriented principles leads to software that can easily adapt to changing requirements.
Ruby on Rails is a web application framework written in Ruby that emphasizes convention over configuration and rapid development. It includes modules for modeling data with ActiveRecord, handling requests and responses with ActionController and ActionView, and additional features like routing and internationalization. The document then provides more details on the history, philosophy, main components, and features of Rails.
This document discusses object-oriented design principles including encapsulation, abstraction, inheritance, polymorphism, and decoupling. It then introduces the SOLID principles of object-oriented design: single responsibility principle, open/closed principle, Liskov substitution principle, interface segregation principle, and dependency inversion principle. Code examples are provided to demonstrate how to apply these principles and improve code maintainability, reusability, and testability.
This document discusses design principles including the SOLID principles. It describes the Single Responsibility Principle, Open-Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle. For each principle, it provides an example to illustrate how to apply that principle and why it is important for writing high-quality code. It also discusses framework patterns like inversion of control and dependency injection.
The document provides information about fully solved assignments for the winter 2013 semester in the BCA program. It lists the subject code and name as BCA2030 - Object Oriented Programming - C++. It provides 6 questions related to the subject and asks students to send their semester and specialization details to the provided email ID or call the given phone number to get the solved assignments. It provides answers to the 6 questions related to topics like objects and classes, friend functions, constructors vs destructors, operator overloading, virtual functions and polymorphism, and exception handling models.
The summary highlights that the document discusses getting fully solved winter 2013 semester assignments for the BCA program's subject on Object Oriented Programming - C
The document provides an overview of Java fundamentals concepts including:
- What a computer program and high/low level languages are
- An introduction to Java and how Java programs are executed
- Key concepts like variables, data types, operators, control statements, functions, classes, objects, and OOP principles like encapsulation, inheritance and polymorphism.
The document also discusses IDEs, arrays, scopes, constants and constructors to provide a comprehensive overview of core Java programming concepts.
C# coding standards, good programming principles & refactoringEyob Lube
The document discusses C# coding standards and principles of good programming. It covers topics such as the importance of coding standards, principles like KISS and SOLID, general naming conventions, and refactoring code for better design. Specific points made include that coding standards create consistency, enable quicker understanding of code, and facilitate collaboration. The SOLID principles of single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion are explained. Meaningful naming is also emphasized, with examples of how intention-revealing names can greatly improve readability and maintainability of code.
This document discusses object-oriented design principles and patterns. It introduces the SOLID principles: single responsibility, open-closed, Liskov substitution, interface segregation, and dependency inversion. These principles aim to create flexible, reusable, and extensible code. Other principles discussed include composition over inheritance and least knowledge. Common design patterns are inspired by these principles to provide solutions for recurring problems. The document emphasizes that applying object-oriented principles leads to software that can easily adapt to changing requirements.
Ruby on Rails is a web application framework written in Ruby that emphasizes convention over configuration and rapid development. It includes modules for modeling data with ActiveRecord, handling requests and responses with ActionController and ActionView, and additional features like routing and internationalization. The document then provides more details on the history, philosophy, main components, and features of Rails.
This document discusses object-oriented design principles including encapsulation, abstraction, inheritance, polymorphism, and decoupling. It then introduces the SOLID principles of object-oriented design: single responsibility principle, open/closed principle, Liskov substitution principle, interface segregation principle, and dependency inversion principle. Code examples are provided to demonstrate how to apply these principles and improve code maintainability, reusability, and testability.
This document discusses design principles including the SOLID principles. It describes the Single Responsibility Principle, Open-Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, and Dependency Inversion Principle. For each principle, it provides an example to illustrate how to apply that principle and why it is important for writing high-quality code. It also discusses framework patterns like inversion of control and dependency injection.
The document provides information about fully solved assignments for the winter 2013 semester in the BCA program. It lists the subject code and name as BCA2030 - Object Oriented Programming - C++. It provides 6 questions related to the subject and asks students to send their semester and specialization details to the provided email ID or call the given phone number to get the solved assignments. It provides answers to the 6 questions related to topics like objects and classes, friend functions, constructors vs destructors, operator overloading, virtual functions and polymorphism, and exception handling models.
The summary highlights that the document discusses getting fully solved winter 2013 semester assignments for the BCA program's subject on Object Oriented Programming - C
The document provides an overview of Java fundamentals concepts including:
- What a computer program and high/low level languages are
- An introduction to Java and how Java programs are executed
- Key concepts like variables, data types, operators, control statements, functions, classes, objects, and OOP principles like encapsulation, inheritance and polymorphism.
The document also discusses IDEs, arrays, scopes, constants and constructors to provide a comprehensive overview of core Java programming concepts.
C# coding standards, good programming principles & refactoringEyob Lube
The document discusses C# coding standards and principles of good programming. It covers topics such as the importance of coding standards, principles like KISS and SOLID, general naming conventions, and refactoring code for better design. Specific points made include that coding standards create consistency, enable quicker understanding of code, and facilitate collaboration. The SOLID principles of single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion are explained. Meaningful naming is also emphasized, with examples of how intention-revealing names can greatly improve readability and maintainability of code.
There are many design principles that have become best practices over the years. Using these principles we can develop scalable and maintainable enterprise application with time tested approaches.
This document provides answers to 15 questions from a final exam on Angular. The questions cover topics like the defer attribute, comparison operators, variable scoping, strict mode, the DOM, adding events, event bubbling, timeouts vs intervals, JSON parsing, AJAX calls, coding style guidelines, and more. For each question, a concise answer is provided explaining the key concept or resolving the example code provided.
Writing clean code using test-driven development (TDD) involves:
1. Writing small, focused unit tests before writing the code to make them pass;
2. Iteratively writing just enough code to pass each test, then refactoring the code;
3. Following principles of clean code like using meaningful names, short functions that do one thing well, and formatting for readability.
The presentation demonstrated converting Roman numerals to Arabic using TDD, highlighting benefits like producing readable, maintainable code with test coverage and living documentation.
Why should we use TDD to develop in Elixir? When we are applying it correctly? What are the differences that we can find in a code developed with TDD and in code not developed with it? Is it TDD about testing? Really? In this talk, I'll show what is TDD and how can be used it in functional programming like Elixir to design the small and the big parts of your system, showing what are the difference and the similarities between an OOP and FP environment. Showing what is the values of applying a technique like TDD in Elixir and what we should obtain applying it.
This document contains answers to 10 interview questions for Dynamics 365 CE/CRM developers. It discusses OOP concepts in .NET like classes, objects, abstraction, encapsulation, inheritance and polymorphism. It also defines sealed classes, access specifiers, design patterns, namespaces, assemblies, WEB APIs, boxing and unboxing, DLLs and EXEs, signing assemblies, abstract classes and interfaces. Key differences between abstract classes and interfaces are provided. The document is for training purposes to help prepare for Dynamics 365 CE/CRM developer interviews.
This document summarizes a presentation on leveraging object-oriented programming techniques in LotusScript. It introduces object-oriented concepts like classes, objects, and encapsulation. It then walks through building an application to monitor news sites for company mentions using a class to represent each site and a nested class to represent individual news items. The presentation demonstrates encapsulating the news item class within the site class and using inheritance by extending all classes from a base class. It shows how to make the application more robust by adding logging through the base class.
Spring boot is a suite, pre-configured, pre-sugared set of frameworks/technologies to reduce boilerplate configuration providing you the shortest way to have a Spring web application up and running with smallest line of code/configuration out-of-the-box.
From August 30, 2010 presentation at ZF NYC Meetup. I gave a presentation on why to use Doctrine, the problems it can solve, how to use it, and some basics of integrating it with the Zend Framework.
This document discusses potential updates to the Web Server Gateway Interface (WSGI) specification and some of the challenges involved. It notes that WSGI 1.0 has limitations for asynchronous systems and middleware. The author explored ideas for WSGI 2.0 like making requests and responses objects and adding context managers for resource management, but concluded it may be too late since so much code relies on the current specification.
The document discusses object-oriented programming (OOP) concepts including encapsulation, abstraction, inheritance, polymorphism, and classes. It explains that OOP is a programming paradigm that uses objects which contain both data and code. Classes define the data and behavior of objects, and can be reused, extended, and abstracted to simplify programming and code maintenance. Inheritance allows new classes to inherit attributes and behaviors from existing classes. Polymorphism enables the same function to operate in different ways depending on the object it is acting upon.
Top 100-php-interview-questions-and-answers-are-below-120816023558-phpapp01Tekblink Jeeten
This document contains summaries of 100 PHP interview questions and their answers. It discusses topics such as:
1. The differences between procedural and object-oriented programming in PHP.
2. Common PHP functions like include, require, urlencode, unlink, and image manipulation functions.
3. How to retrieve data from MySQL databases, submit forms, encrypt data, and get browser/server properties in PHP.
4. The major differences between PHP versions 3, 4, and 5.
5. How to configure aspects like upload file sizes and time zones in PHP applications.
This document discusses using Scala and functional programming concepts like the cake pattern and validation in Goozy, a social networking application. It describes how Goozy's API uses Scala for its performance, conciseness and advanced object-oriented features. It also discusses issues with using Lift and how the cake pattern improved organization by encapsulating dependencies. Validation is implemented using Scalaz to catch errors and exceptions are converted to a common error type for reporting. In summary, functional programming brought organization and error handling benefits but also increased complexity compared to exceptions.
Constructors cannot be made final as they are needed to create object instances and initialize class data. Constructors are similar to methods but cannot be directly invoked via method calls. The APK file format is an Android application package used for distribution and installation of Android apps. It is a zip file containing compiled code, resources, manifest, and other assets. Java is a popular object-oriented programming language that is portable and platform independent due to its compile-once-run-anywhere nature.
The document discusses the SOLID principles of object-oriented design, which are a set of five design principles aimed at making software designs more understandable, flexible and maintainable. It defines each principle - Single Responsibility Principle (SRP), Open-Closed Principle (OCP), Liskov Substitution Principle (LSP), Interface Segregation Principle (ISP), and Dependency Inversion Principle (DIP). For each principle, it provides an example of how to apply the principle correctly and how to avoid violating it. The document emphasizes that following these principles helps produce code that is easier to maintain and extend over time.
This document discusses an automatic code generation tool called UJECTOR that can generate executable Java code from UML diagrams, including class diagrams, sequence diagrams, and activity diagrams. It notes the benefits of automatic code generation in reducing errors compared to manual coding. The paper also discusses some related work, including Enterprise Architect, Eclipse UML Generators, Rhapsody, and dCode - other tools that can generate code from UML models. Overall, the document examines challenges in ensuring consistency, accuracy, maintainability and efficiency when automatically generating code from UML models.
The document discusses the SOLID principles of object-oriented design:
1. Single Responsibility Principle (SRP) states that a class should have one and only one responsibility. Having multiple capabilities in a class makes the code difficult to maintain.
2. Open-Closed Principle (OCP) states that a class should be open for extension but closed for modification. New features can be added by inheriting from the class or extending its behavior without changing the original code.
3. Liskov Substitution Principle (LSP) states that subclasses should not break the behavior of the parent class and any program using the parent class should work the same way if the parent is substituted with the child
SOLID Design Principles for Test AutomaionKnoldus Inc.
The document summarizes the SOLID design principles for test automation. It begins by introducing the five SOLID principles - Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. Each principle is then defined individually and examples are provided for how they could be applied to test automation. The benefits of applying each SOLID principle to test automation are discussed, including improved testability, lower coupling, organization, code maintenance, reusability, and overall architectural stability and flexibility.
- Ruby is an interactive, object-oriented programming language created by Yukihiro Matsumoto in 1995.
- Ruby on Rails is a web application framework built on Ruby that emphasizes convention over configuration and is optimized for programmer happiness.
- The document discusses Ruby and Ruby on Rails, providing an overview of their history, key principles like MVC, REST, and conventions used in Rails. It also provides examples of modeling data with classes and ActiveRecord in Rails.
There are many design principles that have become best practices over the years. Using these principles we can develop scalable and maintainable enterprise application with time tested approaches.
This document provides answers to 15 questions from a final exam on Angular. The questions cover topics like the defer attribute, comparison operators, variable scoping, strict mode, the DOM, adding events, event bubbling, timeouts vs intervals, JSON parsing, AJAX calls, coding style guidelines, and more. For each question, a concise answer is provided explaining the key concept or resolving the example code provided.
Writing clean code using test-driven development (TDD) involves:
1. Writing small, focused unit tests before writing the code to make them pass;
2. Iteratively writing just enough code to pass each test, then refactoring the code;
3. Following principles of clean code like using meaningful names, short functions that do one thing well, and formatting for readability.
The presentation demonstrated converting Roman numerals to Arabic using TDD, highlighting benefits like producing readable, maintainable code with test coverage and living documentation.
Why should we use TDD to develop in Elixir? When we are applying it correctly? What are the differences that we can find in a code developed with TDD and in code not developed with it? Is it TDD about testing? Really? In this talk, I'll show what is TDD and how can be used it in functional programming like Elixir to design the small and the big parts of your system, showing what are the difference and the similarities between an OOP and FP environment. Showing what is the values of applying a technique like TDD in Elixir and what we should obtain applying it.
This document contains answers to 10 interview questions for Dynamics 365 CE/CRM developers. It discusses OOP concepts in .NET like classes, objects, abstraction, encapsulation, inheritance and polymorphism. It also defines sealed classes, access specifiers, design patterns, namespaces, assemblies, WEB APIs, boxing and unboxing, DLLs and EXEs, signing assemblies, abstract classes and interfaces. Key differences between abstract classes and interfaces are provided. The document is for training purposes to help prepare for Dynamics 365 CE/CRM developer interviews.
This document summarizes a presentation on leveraging object-oriented programming techniques in LotusScript. It introduces object-oriented concepts like classes, objects, and encapsulation. It then walks through building an application to monitor news sites for company mentions using a class to represent each site and a nested class to represent individual news items. The presentation demonstrates encapsulating the news item class within the site class and using inheritance by extending all classes from a base class. It shows how to make the application more robust by adding logging through the base class.
Spring boot is a suite, pre-configured, pre-sugared set of frameworks/technologies to reduce boilerplate configuration providing you the shortest way to have a Spring web application up and running with smallest line of code/configuration out-of-the-box.
From August 30, 2010 presentation at ZF NYC Meetup. I gave a presentation on why to use Doctrine, the problems it can solve, how to use it, and some basics of integrating it with the Zend Framework.
This document discusses potential updates to the Web Server Gateway Interface (WSGI) specification and some of the challenges involved. It notes that WSGI 1.0 has limitations for asynchronous systems and middleware. The author explored ideas for WSGI 2.0 like making requests and responses objects and adding context managers for resource management, but concluded it may be too late since so much code relies on the current specification.
The document discusses object-oriented programming (OOP) concepts including encapsulation, abstraction, inheritance, polymorphism, and classes. It explains that OOP is a programming paradigm that uses objects which contain both data and code. Classes define the data and behavior of objects, and can be reused, extended, and abstracted to simplify programming and code maintenance. Inheritance allows new classes to inherit attributes and behaviors from existing classes. Polymorphism enables the same function to operate in different ways depending on the object it is acting upon.
Top 100-php-interview-questions-and-answers-are-below-120816023558-phpapp01Tekblink Jeeten
This document contains summaries of 100 PHP interview questions and their answers. It discusses topics such as:
1. The differences between procedural and object-oriented programming in PHP.
2. Common PHP functions like include, require, urlencode, unlink, and image manipulation functions.
3. How to retrieve data from MySQL databases, submit forms, encrypt data, and get browser/server properties in PHP.
4. The major differences between PHP versions 3, 4, and 5.
5. How to configure aspects like upload file sizes and time zones in PHP applications.
This document discusses using Scala and functional programming concepts like the cake pattern and validation in Goozy, a social networking application. It describes how Goozy's API uses Scala for its performance, conciseness and advanced object-oriented features. It also discusses issues with using Lift and how the cake pattern improved organization by encapsulating dependencies. Validation is implemented using Scalaz to catch errors and exceptions are converted to a common error type for reporting. In summary, functional programming brought organization and error handling benefits but also increased complexity compared to exceptions.
Constructors cannot be made final as they are needed to create object instances and initialize class data. Constructors are similar to methods but cannot be directly invoked via method calls. The APK file format is an Android application package used for distribution and installation of Android apps. It is a zip file containing compiled code, resources, manifest, and other assets. Java is a popular object-oriented programming language that is portable and platform independent due to its compile-once-run-anywhere nature.
The document discusses the SOLID principles of object-oriented design, which are a set of five design principles aimed at making software designs more understandable, flexible and maintainable. It defines each principle - Single Responsibility Principle (SRP), Open-Closed Principle (OCP), Liskov Substitution Principle (LSP), Interface Segregation Principle (ISP), and Dependency Inversion Principle (DIP). For each principle, it provides an example of how to apply the principle correctly and how to avoid violating it. The document emphasizes that following these principles helps produce code that is easier to maintain and extend over time.
This document discusses an automatic code generation tool called UJECTOR that can generate executable Java code from UML diagrams, including class diagrams, sequence diagrams, and activity diagrams. It notes the benefits of automatic code generation in reducing errors compared to manual coding. The paper also discusses some related work, including Enterprise Architect, Eclipse UML Generators, Rhapsody, and dCode - other tools that can generate code from UML models. Overall, the document examines challenges in ensuring consistency, accuracy, maintainability and efficiency when automatically generating code from UML models.
The document discusses the SOLID principles of object-oriented design:
1. Single Responsibility Principle (SRP) states that a class should have one and only one responsibility. Having multiple capabilities in a class makes the code difficult to maintain.
2. Open-Closed Principle (OCP) states that a class should be open for extension but closed for modification. New features can be added by inheriting from the class or extending its behavior without changing the original code.
3. Liskov Substitution Principle (LSP) states that subclasses should not break the behavior of the parent class and any program using the parent class should work the same way if the parent is substituted with the child
SOLID Design Principles for Test AutomaionKnoldus Inc.
The document summarizes the SOLID design principles for test automation. It begins by introducing the five SOLID principles - Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. Each principle is then defined individually and examples are provided for how they could be applied to test automation. The benefits of applying each SOLID principle to test automation are discussed, including improved testability, lower coupling, organization, code maintenance, reusability, and overall architectural stability and flexibility.
- Ruby is an interactive, object-oriented programming language created by Yukihiro Matsumoto in 1995.
- Ruby on Rails is a web application framework built on Ruby that emphasizes convention over configuration and is optimized for programmer happiness.
- The document discusses Ruby and Ruby on Rails, providing an overview of their history, key principles like MVC, REST, and conventions used in Rails. It also provides examples of modeling data with classes and ActiveRecord in Rails.
Similar to "S"OLID Principles - Single responsibility principle (20)
3rd International Conference on Artificial Intelligence Advances (AIAD 2024)GiselleginaGloria
3rd International Conference on Artificial Intelligence Advances (AIAD 2024) will act as a major forum for the presentation of innovative ideas, approaches, developments, and research projects in the area advanced Artificial Intelligence. It will also serve to facilitate the exchange of information between researchers and industry professionals to discuss the latest issues and advancement in the research area. Core areas of AI and advanced multi-disciplinary and its applications will be covered during the conferences.
Properties of Fluids, Fluid Statics, Pressure MeasurementIndrajeet sahu
Properties of Fluids: Density, viscosity, surface tension, compressibility, and specific gravity define fluid behavior.
Fluid Statics: Studies pressure, hydrostatic pressure, buoyancy, and fluid forces on surfaces.
Pressure at a Point: In a static fluid, the pressure at any point is the same in all directions. This is known as Pascal's principle. The pressure increases with depth due to the weight of the fluid above.
Hydrostatic Pressure: The pressure exerted by a fluid at rest due to the force of gravity. It can be calculated using the formula P=ρghP=ρgh, where PP is the pressure, ρρ is the fluid density, gg is the acceleration due to gravity, and hh is the height of the fluid column above the point in question.
Buoyancy: The upward force exerted by a fluid on a submerged or partially submerged object. This force is equal to the weight of the fluid displaced by the object, as described by Archimedes' principle. Buoyancy explains why objects float or sink in fluids.
Fluid Pressure on Surfaces: The analysis of pressure forces on surfaces submerged in fluids. This includes calculating the total force and the center of pressure, which is the point where the resultant pressure force acts.
Pressure Measurement: Manometers, barometers, pressure gauges, and differential pressure transducers measure fluid pressure.
Build the Next Generation of Apps with the Einstein 1 Platform.
Rejoignez Philippe Ozil pour une session de workshops qui vous guidera à travers les détails de la plateforme Einstein 1, l'importance des données pour la création d'applications d'intelligence artificielle et les différents outils et technologies que Salesforce propose pour vous apporter tous les bénéfices de l'IA.
This study Examines the Effectiveness of Talent Procurement through the Imple...DharmaBanothu
In the world with high technology and fast
forward mindset recruiters are walking/showing interest
towards E-Recruitment. Present most of the HRs of
many companies are choosing E-Recruitment as the best
choice for recruitment. E-Recruitment is being done
through many online platforms like Linkedin, Naukri,
Instagram , Facebook etc. Now with high technology E-
Recruitment has gone through next level by using
Artificial Intelligence too.
Key Words : Talent Management, Talent Acquisition , E-
Recruitment , Artificial Intelligence Introduction
Effectiveness of Talent Acquisition through E-
Recruitment in this topic we will discuss about 4important
and interlinked topics which are
Determination of Equivalent Circuit parameters and performance characteristic...pvpriya2
Includes the testing of induction motor to draw the circle diagram of induction motor with step wise procedure and calculation for the same. Also explains the working and application of Induction generator
2. What’s SOLID Principle?
It’s a set of 5 principles which when followed will result into a program which is
being much more easy to maintain, is bug free, and faster to develop.
SOLID consist of the following principles:
1. Single responsibility
2. Open-closed
3. Liskov substitution
4. Interface segregation
5. and Dependency inversion
3. When SOLID principle emerge?
- Programming is all about breaking problems down into parts.
- There's lots of ways to break down code
- For example, The close button - Object that’s responsible for close button vs
The object that’s responsible for all read buttons. Which one is more relevant?
- Programmers worked out rules for how to organize their code so it would be
easy to reuse or change. One set of rules is called "SOLID". Every letter stands
for a different principle.
- SOLID is a set of rules that's probably a good idea to follow, but you won't
instantly get into trouble if you break it. You'll see a lot of these as you grow
up.
4. Why should we care about “SOLID”?
Benefits of using SOLID in your programming.
1. Easy to maintain
2. Easy to extend
3. Robust code
5. Coupling and Cohesion
Remember two relevant concepts in the development of any software
1. Coupling - The degree to which a class, method or any other software entity, is
directly linked to another, Dependency.
Example: If two classes are tightly coupled then changes in one class may
require lots of changes in another class.
1. Cohesion - Cohesion is a degree (quality) to which a component / module
focuses on the single thing.
Example : A well focused class, Use of modules, packages, libraries
6.
7. The “S” of SOLID - Single Responsibility
Our objects should only solve one problem. When they do too many things they get
confused, so let's keep them as simple as possible.
Benefits:
● Coupling reduced.
● Code easier to understand and maintain
A class should have only a single responsibility.
OR
A class should have only one reason to change.
8.
9. Let’s understand “S” by example
Usage of APIs are very common now. Let's say we need to call BlogService to get
list of blog posts.
So two corresponding classes here:
BlogService and Post
Let’s see some code now..
15. Let's try to follow this rule and refactor the code
16. Extract configuration part into separate class:
class BlogServiceConfig
def initialize(env:)
@env = env
end
def base_url
return 'https://prod.myserver.com' if @env == 'production'
'https://jsonplaceholder.typicode.com'
end
end
17. Now we can use this class in BlogService:
class BlogService
# ...
def posts
url = "#{config.base_url}/posts"
puts "[BlogService] GET #{url}"
response = Net::HTTP.get_response(URI(url))
# ...
end
private
# ...
def config
@config ||= BlogServiceConfig.new(env: @env)
end
end
18. Let's move forward and extract logging
module RequestLogger
def log_request(service, url, method = 'GET')
puts "[#{service}] #{method} #{url}"
end
end
19. class BlogService
include RequestLogger
# ...
def posts
url = "#{config.base_url}/posts"
log_request('BlogService', url)
response = Net::HTTP.get_response(URI(url))
# ...
end
end
20. We've extracted 2 classes so far. Now we need to
figure out how to handle HTTP layer and
response processing.
21. Implementing HTTP request handler
class RequestHandler
ResponseError = Class.new(StandardError)
def send_request(url, method = :get)
response = Net::HTTP.get_response(URI(url))
raise ResponseError if response.code != '200'
JSON.parse(response.body)
end
end
22. Let's send API call using RequestHandler:
class BlogService
# ...
def posts
url = "#{config.base_url}/posts"
log_request('BlogService', url)
posts = request_handler.send_request(url)
# ...
end
private
# ...
def request_handler
@request_handler ||= RequestHandler.new
end
end
23. ResponseProcessor to process response
class ResponseProcessor
def process(response, entity)
return entity.new(response) if response.is_a?(Hash)
if response.is_a?(Array)
response.map { |h| entity.new(h) if h.is_a?(Hash) }
end
end
end
24. Now, we can use the processor in our main class:
class BlogService
# ...
def posts
url = "#{config.base_url}/posts"
log_request('BlogService', url)
posts = request_handler.send_request(url)
response_processor.process(posts, Post)
end
private
# ...
def response_processor
@response_processor ||= ResponseProcessor.new
end
end
25. Method posts looks much smaller now and we can read some boring code there:
1. Construct url
2. Log request
3. Send request
4. Process response
26. Still one problem!
In initial implementation we had sort of mapping between fields:
Post.new(
id: params['id'],
user_id: params['userId'],
body: params['body'],
title: params['title']
)
27. Let’s make it more flexible!
class ResponseProcessor
def process(response, entity, mapping = {})
return entity.new(map(response, mapping)) if response.is_a?(Hash)
if response.is_a?(Array)
response.map { |h| entity.new(map(h, mapping)) if h.is_a?(Hash) }
end
end
def map(params, mapping = {})
return params if mapping.empty?
params.each_with_object({}) do |(k, v), hash|
hash[mapping[k] ? mapping[k] : k] = v
end
end
end
29. Let’s add another method and see how it works!
def post(id)
url = "#{config.base_url}/posts/#{id}"
log_request('BlogService', url)
posts = request_handler.send_request(url)
response_processor.process(posts, Post, mapping)
end
30. As you see without any significant change, We
are able to add a method easily.!!!
This is the beauty of Single Responsibility Rule!
31. “Your actions become your habits,
Your habits become your values,
Your values become your destiny.”
- Mahatma Gandhi
32. My point is to always strive to be better by challenging
yourself. At some point, you will ask, but you will know already
the answer…
Editor's Notes
As you can see fat interfaces lead to inadvertent coupling between classes and you should avoid them. When designing interfaces you should always ask yourself the question “Do really need all the methods on this interface I’m using? If not how can I break them into smaller interfaces?”.
If you do the right thing every and allow only the good patterns to emerge from your architecture, it will become a habit. And that it will become your values or principles. If you keep doing that it will become your destiny, which is to always produce sound solutions or whatever your idea of a software engineer is.