Rule Definition
If singleton is invoked in a multi-threaded program, you could end up creating multiple instances of the class which will make the application unstable.
Remediation
Make sure that you have only one instance created in class constructor and it has been frozen to avoid any changes.
Violation Code Sample
class UserStore {
constructor(){
if(! UserStore.instance){
UserStore.instance = this;
}
return UserStore.instance;
}
// VIOLATION, THIS IS NOT ENOUGH
}
Fixed Code Sample
class UserStore {
constructor(){
if(! UserStore.instance){
UserStore.instance = this;
}
return UserStore.instance;
}
}
const instance = new UserStore();
Object.freeze(instance);
export default instance;
Reference
OMG CISQ
Related Technologies
Technical Criterion
CWE-1096 - Singleton Class Instance Creation without Proper Locking or Synchronization
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.