Singleton design vs. automated testing and teardown

I will post a generic code exemplifying two code patterns; this question is generic but I still think it’s best fitted to code review even though it concerns abstract notions that would be pointless to express at large with code.

We have a CMS framework. This is important in the sense that the framework manages everything concerning a request – from class loading to DB connection management to error handling.

In order to do this, a number of system singletons are used – either system state singletons or factories.

Most singletons are ATM implemented using abstract classes with static vars. Note, none of the singletons in discussion are ever persisted, serialized or otherwise need an actual object instance – our question doesn’t regard functionality, they work fine like this.

We are setting in place automatic testing: unit, functional, acceptance. We are using Codeception (which uses PHPUnit), but please take abstraction of the testing platform, let’s use it just as example. We ask about generic automated testing at large.

The problem we are facing is supporting decent teardown to test some of the system functions. For instance, it is apparent to us class loading is irreversible because PHP doesn’t support unloading classes, so only process isolation provides decent teardown for the class loading. However, apart from this, the other singletons could/should be tested.

The abstract class-based singleton pattern seems more awkward to tear down, but PHPUnit makes a decent effort to “rewind” class static properties between tests, so it kindof works.

The single-instance singleton pattern looks more suited because it allows explicit teardown (just unset the single instance reference). It also would allow, in theory, multiple “context” singletons – so we can preinitialize a number of singletons to be reused for various test contexts.

Question: what are THE singleton and teardown patterns to be used to make your life easy for automated testing? What are the common advantages and pitfalls of various such patterns?

    /*  Pattern 1: abstract singleton; teardown is done          by the testing framework by resetting static properties */     abstract class Singleton1 {         protected static $  singletonProperty1;    // Protected - allow singleton emancipation         protected static $  singletonProperty2;         public static function init(){             self::$  singletonProperty1='Hello';             self::$  singletonProperty2='World';         }         public static function use(){             echo implode(' ',[self::$  singletonProperty1,self::$  singletonProperty2]);         }     }      Singleton1::init();     Singleton1::use();      /*  Pattern 2: single-instance singleton w/ explicit teardown */     class Singleton2 {         private static $  instance;          protected $  singletonProperty1;    // Protected - allow singleton emancipation         protected $  singletonProperty2;          protected function __construct(){             $  this->singletonProperty1='Hello';             $  this->singletonProperty2='World';         }         public function use(){             echo implode(' ',[$  this->singletonProperty1,$  this->singletonProperty2]);         }          public static function getInstance(){             if(!self::$  instance){                 $  class=get_called_class();    // Backwards PHP compatibility of "static"                 self::$  instance=new $  class();             }             return self::$  instance;         }         public static function tearDown(){             self::$  instance=null;    // Backwards PHP compatibility: do NOT use unset on class/object properties, inconsistent behavior         }     }      Singleton2::getInstance()->use();  ``` 

Object Oriented Design: Repositories and Inheritance

I have an OO design concern: let’s say in my model I have a base class – eg. class Account {} – and two subclasses that extend it – eg. class LocalAccount extends Account {} and class SocialAccount extends Account {}.

These Account entities are persisted, and I could retrieve them (or do more operations on them) through a typical Repository. Let’s say I have the following interface:

AccountRepository:

interface AccountRepository {     getAll(): Array<Account> ; } 

And I have some use-cases where I need to work with Accounts where I basically would inject the AccountRepository, eg.

class FooUseCase {      private AccountRepository accountRepository;      constructor(AccountRepository accountRepository) {         this.accountRepository = accountRepository;     }      public execute(): void {         // Use case logic where I would call accountRepository.getAll()     }  } 

And at this point is where I am actually struggling. After some analysis, I thought about having specific AccountRepository implementations:

LocalAccountRepository:

class LocalAccountRepository implements AccountRepository {      public getAll(): Array<LocalAccount> { /* implementation */ }  } 

SocialAccountRepository:

class SocialAccountRepository implements AccountRepository {      public getAll(): Array<SocialAccount> { /* implementation */ }  } 

This would be alright, as far as a use-case would just need to work with LocalAccount or SocialAccount entities. But, what would happen if I would just needed to work with Account entities?

I feel I could implement an AccountRepository, generic enough that could just return a list of Accounts, eg.

AccountRepositoryImpl:

class AccountRepositoryImpl implements AccountRepository {      public getAll(): Array<Account> { /* implementation */ }  } 

but I feel that at the public getAll(): Array<Account> I would somehow have to add some kind of switch/if-else statement to be able to create each type of Account object:

AccountRepositoryImple.getAll():

public getAll(): Array<Account> {     // Database access, query, etc.      // results iteration      let account: Account;      if (result.type === AccountType.Local) {         account = new LocalAccount(/* params */);     } else if (result.type === AccountType.Social) {         account = new SocialAccount(/* params */);     }      accounts.add(account);      // iteration end      return accounts; } 

Which clearly violates some design principles (every time a new Account is added would have to extend the if-else, etc.).

Any design improvement suggestions to my issues?

Create Full E-Commerce Website Design With Development for $500

I am experienced web developer So if you are looking for a responsive eCommerce website on a WordPress premium theme and plugins of your choice then you are on the right page. What i will offer? Complete eCommerce website on WordPress. Fully SEO Optimized to rank in Search Engines (Google, Yahoo, Bing, etc) Responsive Design for Mobile and Tablet Devices Stock & Inventory Management Discount coupons Free Shipping or flat rate shipping Payment Gateways – COD – P’a’y’P”a’l Supports unlimited categories, products and images. Social Media Integration Adding up-to 5 Pages And more All these services includes Excellent Communication in English 24/7 Customer Support 100% Satisfaction Guaranteed Unlimited Revisions So what are you waiting for? Lets start the work on your dream eCommerce website and market it Thanks & Regards

by: Michael58
Created: —
Category: WordPress
Viewed: 351


Advice for course homepage design

I would love some input on the UX of the website that I’ve been designing.

The webpage can be found at https://www.math180.coursehome.page/ — it’s purpose is to serve as the homepage for a mathematics course (not specifically calculus; this is just a placeholder course).

In particular, I am anticipating that a large portion of the users will be mobile users.

Any input and criticism (typography, navigation, etc) is appreciated!

How to design a reassignable global instance that can be referenced by many other classes

I have a DeviceManager class which can handle different physical devices, and to say there are Classes A,B,C, which require a DeviceManager instance as dependency. They should always use the same instance of DeviceManager, however, at some point of time this DeviceManager should create a new instance in order to wrap a different physical device. So in this case, in terms of maintainability and testability, should I use a static wrapper or dependency injection? I have two solutions, but don’t know which is better, or maybe there is a way better solution.

Static Wrapper:

    public static class DeviceService     {         static IDeviceManager _deviceManager;          public static void Handle() { _deviceManager.Handle(); }          public static void Reset()         {             _deviceManager = new Container.Resolve<IDeviceManager>();         }     } 

ClassA,B,C instances then can use DeviceService.Handle() and at some point of time to use DeviceService.Reset() to reassign a new instance.

Dependency Injection

public ClassA(IDeviceManager dm);

public ClassB(IDeviceManager dm);

public ClassC(IDeviceManager dm);

Assume that if I reassign the DeviceManager, then I will also create new Class A,B,C instances.

Static wrapper is handy, and easy to manage the state, but it relies on Service Locator, which is an implicit dependency since it is not passed and referenced by parameters, would it be a pain in unit testing? And I need to call Reset() explicitly before I use/reuse it. Dependency Injection seems to have lower coupling and it is code agnostic, it can even handle using various DeviceManager instances in the future, but my project has many classes and instances relying on DeviceManager, I need to pass an instance to each of them additionally.

I still cannot decide on which one is better, and why. I need you helps.