DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Beginners Guide to Mocking in Scala
  • Cutting-Edge Object Detection for Autonomous Vehicles: Advanced Transformers and Multi-Sensor Fusion
  • Why Testing is a Long-Term Investment for Software Engineers
  • Writing DTOs With Java8, Lombok, and Java14+

Trending

  • Chaos Engineering for Microservices
  • Comparing SaaS vs. PaaS for Kafka and Flink Data Streaming
  • Scaling in Practice: Caching and Rate-Limiting With Redis and Next.js
  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  1. DZone
  2. Coding
  3. Languages
  4. Break Single Responsibility Principle

Break Single Responsibility Principle

By 
Peter Verhas user avatar
Peter Verhas
DZone Core CORE ·
May. 08, 15 · Interview
Likes (0)
Comment
Save
Tweet
Share
6.8K Views

Join the DZone community and get the full member experience.

Join For Free

Single Responsibility Principle (SRP) is not absolute. It exists to help the code maintainability and readability. But from time to time you may see solutions, patterns that break the SRP and are kind of OK. This is also true for other principles, but this time I would like to talk about SRP.

Singleton breaks SRP

The oldest and simplest pattern that breaks SRP is the singleton pattern. This pattern restricts the creation of an object so that there is a single instance of a certain class. Many thinks that singleton actually is an antipattern and I also tend to believe that this is better to use some container to manage the lifecycle of the objects than hard coding singletons or other home made factories. The anti pattern-ness of singleton generally comes from the fact that it breaks the SRP. A singleton has two responsibilities:

  1. Manage the creation of the instance of the class
  2. Do something that is the original responsibility of the class

You can easily create a singleton that does not violate SRP keeping the first responsibility and drop the second one

public class Singleton {
    private static final Singleton instance = new Singleton();
    public static Singleton getInstance() { return instance; }
    private Singleton() {}
}

but there is not much use of such a beast. Singletons are simple and discussed more than enough in blogs. Let me look at something more complex that breaks SRP.

Mockito breaks SRP

Mockito is a mocking framework, which we usually use in unit tests. I assume that you are familiar with mocking and mockito. A typical test looks like the following:

import static org.mockito.Mockito.*;
List mockedList = mock(List.class);
when(mockedList.get(0)).thenReturn("first");
System.out.println(mockedList.get(0));
mockedList.add("one");
mockedList.clear();
verify(mockedList).add("one");
verify(mockedList).clear();

(sample is taken from the Mockito page, actually mixing two examples). The mock object is created using the static call

1
List mockedList = mock(List.class);

and after it is used for three different things:

  1. Setup the mock object for its mocking task.
  2. Behave as a mock mocking the real life object during testing.
  3. Help verification of the mock usage.

The call

when(mockedList.get(0)).thenReturn("first");

sets up the mock object. The calls

System.out.println(mockedList.get(0));
mockedList.add("one");
mockedList.clear();

use the core responsibility of the mock object and finally the lines

verify(mockedList).add("one");
verify(mockedList).clear();

act as verification.

These are three different tasks not one. I get the point that they are closely related to each other. You can even say that they are just three aspects of a single responsibility. One could argue that verification only uses the mock object as a parameter and it is not the functionality of the mock object. The fact is that the mock object keeps track of its mock usage and acts actively in the verification process behind the scenes. Okay, okay: these all may be true, more or less. The real question is: does it matter?

So what?

Does the readability of the code of Mockito suffer from treating the SRP this way? Does the usability of the API of Mockito suffer from this?

The answer is definite NO for both of the questions. The code is as readable as it gets (imho it is more readable than many other open source projects) but it is not affected by the fact that the mock objects have multiple responsibilities. As for the API you can even say more. It is readable and usable even more with this approach. Former mocking frameworks used strings to specify the method calls like

mailer.expects(once()).method("send");
warehouse.expects(once()).method("hasInventory")

(fragment from the page), which is less readable and error prone. A typo in the name of the method is discovered test run time instead of compile time.

What is the morale? Don’t be dogmatic. Care programming principles, since they are there to help you to write good code. I do not urge anyone to ignore them every day. On the other hand if you feel that some of the principles restrict you and your code would be better without it, do not hesitate to consider writing a code that breaks the principles. Discuss it with your peers (programming is a team work anyway) and come to a conclusion. The conclusion will be that you were wrong considering to break SRP in 90% of the cases. In 10%, however, you may come up with brilliant ideas.

Mock object Object (computer science)

Published at DZone with permission of Peter Verhas, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Beginners Guide to Mocking in Scala
  • Cutting-Edge Object Detection for Autonomous Vehicles: Advanced Transformers and Multi-Sensor Fusion
  • Why Testing is a Long-Term Investment for Software Engineers
  • Writing DTOs With Java8, Lombok, and Java14+

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!