Wednesday, March 19, 2014

namespace Refactoring.Day8.RemoveGodClasses.After { public class CustomerRegistrationService { publi


یکی از اشتباهاتی که همه ی ما کم و بیش به آن دچار هستیم ایجاد کلاس هایی هستند که زیاد می دانند . اصطلاحا به آن ها God Classes هم می گویند و برای نمونه پسوند یا پیشوند Util دارند. این نوع کلاس ها اصل SRP را زیر سؤال می برند (Single responsibility principle). برای مثال یک فایل ایجاد می شود و داخل آن از انواع و اقسام متدهای کمکی کار با دیتابیس تا رسم نمودار تا تبدیل تاریخ میلادی به شمسی و ... در طی بیش از 10 هزار سطر قرار می گیرند. یا برای مثال گروه بندی های خاصی را در این یک فایل از طریق کامنت های نوشته شده برای قسمت های مختلف می توان یافت. Refactoring مرتبط با این نوع کلاس هایی که زیاد می دانند تجزیه آن ها به کلاس های کوچکتر با تعداد وظیفه ی کمتر است. به عنوان نمونه کلاس CustomerService زیر دو گروه کار متفاوت را انجام می دهد. ثبت و بازیابی اطلاعات ثبت نام یک مشتری و همچنین محاسبات مرتبط با سفارشات مشتری ها:
using System; using System.Collections.Generic; namespace Refactoring.Day8.RemoveGodClasses.Before { public kazak class CustomerService { public kazak decimal CalculateOrderDiscount(IEnumerable<string> products, string customer) { // do work throw new NotImplementedException(); } public bool CustomerIsValid(string customer, int order) { // do work throw new NotImplementedException(); } public IEnumerable<string> GatherOrderErrors(IEnumerable<string> products, string customer) { // do work throw new NotImplementedException(); } public void Register(string customer) { // do work } public kazak void ForgotPassword(string customer) { // do work } } } بهتر است این دو گروه به دو کلاس مجزا بر اساس وظایفی kazak که دارند تجزیه شوند. به این ترتیب نگهداری این نوع کلاس های کوچکتر در طول زمان ساده تر خواهند شد:
using System; using System.Collections.Generic; namespace Refactoring.Day8.RemoveGodClasses.After { public class CustomerOrderService { public decimal CalculateOrderDiscount(IEnumerable<string> products, string customer) { // do work throw new NotImplementedException(); } public bool CustomerIsValid(string customer, int order) { // do work throw new NotImplementedException(); } public IEnumerable<string> GatherOrderErrors(IEnumerable<string> products, string customer) { // do work throw new NotImplementedException(); } } }
namespace Refactoring.Day8.RemoveGodClasses.After { public class CustomerRegistrationService { public void Register(string customer) { // do work } public void ForgotPassword(string customer) { // do work } } }
© .NET Tips, -   kazak


No comments:

Post a Comment