Details
-
Type:
Code Smell Detection
-
Status: Active
-
Resolution: Unresolved
-
Labels:
-
Message:The event name "XXXX" should be defined in a constant variable.
-
Default Severity:Critical
-
Impact:High
-
Likelihood:Low
-
Default Quality Profiles:Sonar way
-
Covered Languages:Flex
-
Remediation Function:Constant/Issue
-
Constant Cost:5min
Description
Using plain string event names in even listeners is an anti-pattern; if the event is renamed, the application can start behaving unexpectedly. A constant variable should be used instead.
Noncompliant Code Example
import flash.display.Sprite; import flash.events.MouseEvent; class ChildSprite extends Sprite { public function ChildSprite() { ... addEventListener("CustomEvent", clickHandler); // Noncompliant } } function clickHandler(event:CustomEvent):void { trace("clickHandler detected an event of type: " + event.type); trace("the this keyword refers to: " + this); }
Compliant Solution
import flash.display.Sprite; import flash.events.MouseEvent; class ChildSprite extends Sprite { public const CUSTOM_EVENT:String = "CustomEvent"; public function ChildSprite() { ... addEventListener(CUSTOM_EVENT, clickHandler); } } function clickHandler(event:CustomEvent):void { trace("clickHandler detected an event of type: " + event.type); trace("the this keyword refers to: " + this); }