Design Patterns: Refactor a Class to Follow SRP

Level : Beginner
Mentor: Shailendra Chauhan
Type : GuidedLab
Points : 10
Duration : 00:25:00

Lab Details

Problem Statement

A lab to follow the SRP principle while doing your code in C#.

  • Do refer to the below UserService class that handles user authentication, user data management, and email notifications.
  • Refactor the UserService class into separate classes to handle the different responsibilities.
  • Ensure each class has a single responsibility and update the main program to use the new classes: UserService, AuthenticationService, UserDataService, EmailNotificationService.

UserService Class:

using System;

public class UserService

{

    private readonly AuthenticationService _authenticationService;

    private readonly UserDataService _userDataService;

    private readonly EmailNotificationService _emailNotificationService;

    public UserService(AuthenticationService authenticationService, UserDataService userDataService, EmailNotificationService emailNotificationService)

    {

        _authenticationService = authenticationService;

        _userDataService = userDataService;

        _emailNotificationService = emailNotificationService;

    }

    public void ProcessUser(string username, string password, string emailAddress)

    {

        // Authenticate user

        if (_authenticationService.AuthenticateUser(username, password))

        {

            // If authenticated, manage user data

            _userDataService.ManageUserData(username);

            // Send email notification

            string message = "Your account has been accessed.";

            _emailNotificationService.SendNotification(emailAddress, message);

        }

        else

        {

            Console.WriteLine("Authentication failed.");

        }

    }

}

Lab Objective:

Upon completion of this lab, you will be able to:

  • Understand and use the Single Responsibility Principle (SRP) in class design.
  • Refactor a monolithic class into numerous classes, each with its own responsibility.
  • Update and integrate a refactored class structure into an existing program to increase code maintainability and clarity.

Prerequisites

You should install the following software on your machine:

  • VS Code or Visual Studio
  • .NET SDK

Self-paced Membership
  • 24+ Video Courses
  • 825+ Hands-On Labs
  • 400+ Quick Notes
  • 50+ Skill Tests
  • 10+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Still have some questions? Let's discuss.
CONTACT US
Accept cookies & close this