CodeAnt AI home pagelight logodark logo
  • Support
  • Dashboard
  • Dashboard
  • Join Community
Start Here
  • What is CodeAnt?
Setup
  • Github
  • Bitbucket
  • Gitlab
  • Azure Devops
Pull Request Review
  • Features
  • Customize Review
  • Quality Gates
  • Integrations
Scan center
  • Code Security
  • Code Quality
  • Cloud Security
  • Engineering Productivity
Integrations
  • Jira
  • Test Coverage
  • CI/CD
IDE
  • Setup
  • Review
  • Enhancements
Rule Reference
  • Compliance
  • Anti-Patterns
    • Pyspark
    • Python
    • Java
    • C / CPP
    • C #
    • JavaScript
    • Jcl
    • Kotlin
    • Kubernetes
    • Abap
    • Apex
    • Azure Source Manager
    • Php
    • Pli
    • Plsql
    • Secrets
    • Swift
    • Terraform
    • Text
    • Tsql
    • Rpg
    • Ruby
    • Scala
    • Vb6
    • Vbnet
    • Xml
    • Flex
    • Go
    • Html
    • Docker
    • Css
    • Cobol
    • Common
  • Code Governance
  • Infrastructure Security Database
  • Application Security Database
Resources
  • Open Source
  • Blogs
Anti-Patterns

Flex

public static fields should be constant

There is no good reason to declare a field “public” and “static” without also declaring it “const”. Most of the time this is a kludge to share a state among several objects. But with this approach, any object can do whatever it wants with the shared state, such as setting it to null.

Copy
public class Greeter {
public static var foo:Foo = new Foo(...);
...
}

Classes that extend Event should override Event.clone()

Overriding Event.clone() is a required part of the API contract:

Copy
public class MyEvent extends Event {...}

Alert.show(...) should not be used

Alert.show(…) can be useful for debugging during development, but in production mode this kind of pop-up could expose sensitive information to attackers, and should never be displayed.

Copy
if (unexpectedCondition)
{
Alert.show("Unexpected Condition");
}

The element type of an array field should be specified

Quoted from the Flex documentation :

Copy
public var newStringProperty:Array;
public var newNumberProperty:Array;

Only while, do and for statements should be labelled

Any statement or block of statements can be identified by a label, but those labels should be used only on while, do-while and for statements. Using labels in any other context leads to unstructured, confusing code.

Copy
myLabel:if (i % 2 == 0) {  // Noncompliant
if (i == 12) {
print("12");
break myLabel;
}
print("Odd number, but not 12");
}

Statements should end with semicolons

In Flex, the semicolon is optional as a statement separator, but omitting semicolons can be confusing.

Copy
function fun() {
return   // Noncompliant
   5   // Noncompliant
}
print(fun());  // prints "undefined", not "5"

The flash.system.Security.exactSettings property should never be set to false

The Security.exactSettings value should remain set at the default value of true. Setting this value to false could make the SWF vulnerable to cross-domain attacks.

Copy
Security.exactSettings = false;

The special star type should not be used

According to the ActionScript language reference, the star type:

But deferring type checking to runtime can highly impact the robustness of the application because the compiler is unable to assist the developer.

Copy
var obj:*;  // Noncompliant
var foo:* = new Something();  // Noncompliant

Function call arguments should not start on new lines

Because semicolons at the ends of statements are optional, starting function call arguments on a separate line makes the code confusing. It could lead to errors and most likely will lead to questions for maintainers.

What was the initial intent of the developer?

  1. Define a function and then execute some unrelated code inside a closure ?

  2. Pass the second function as a parameter to the first one ?

The first option will be the one chosen by the JavaScript interpreter.

By extension, and to improve readability, any kind of function call argument should not start on new line.

Copy
var fn = function () {
//...
}

(function () { // Noncompliant
//...
})();

Event names should not be hardcoded in event listeners

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.

Copy
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); 
}

Method visibility should be explicitly declared

Access modifiers define which classes can access properties, variables, methods, and other classes. If an access modifier is not specified, the access level defaults to `internal, which grants access to all classes in the same package. This may be what is intended, but it should be specified explicitly to avoid confusion.

Available access modifiers are:

  • internal - access allowed within the same package

  • private - access allowed only within the same class

  • protected - access allowed to the class and its child classes

  • public` - unfettered access by all

Copy
function checkResources():Boolean { 
...
return true;
}

ManagedEvents tags should have companion Event tags

The “ManagedEvents” metadata tag allows you to flag an event as being managed. By definition this “ManagedEvents” metadata tag should be used in pair with an “Event” metadata tag.

Copy
[Event(name="message", type="my.package.MyEvemt")]
[ManagedEvents("mes")]       //This "mes" event is not defined with the "Event" metadata tag
public class MyClass {...}

with statements should not be used

Never use with statements, since they decrease readability. When you do not specify a variable’s scope, you do not always know where you are setting properties, so your code can be confusing.

Copy
with (foo) { // Noncompliant
return x;  // is it a property of foo or local variable ?
}

Objects should not be instantiated inside a loop

It can be expensive to instantiate a new object, and doing so inside a loop is typically an error. Instead, create the object once, before the loop.

Copy
for (var i:int = 0; i < 10; i++) {
var temp:MyObj = new MyObject();  // Noncompliant
//...  
}

The trace function should not be used

The trace() function outputs debug statements, which can be read by anyone with a debug version of the Flash player. Because sensitive information could easily be exposed in this manner, trace() should never appear in production code.

Copy
var val:Number = doCalculation();
trace("Calculation result: " + val);  // Noncompliant

Package definition should be separate from Class definition

Declaring the package and class together has been deprecated since ActionScript 3. The package definition should be declared outside of the class definition even if the old syntax is still supported.

Copy
class P.A {...}

Loggers should be private static const and should share naming convention

Loggers should be:

  • `private: not accessible outside of their parent classes. If another class needs to log something, it should instantiate its own logger.

  • static: not dependent on an instance of a class (an object). When logging something, contextual information can of course be provided in the messages but the logger should be created at class level to prevent creating a logger along with each object.

  • const`: created once and only once per class.

Copy
public const logger:ILogger = LogUtil.getLogger(MyClass);

Function names should comply with a naming convention

For example, with the default provided regular expression ^[a-z][a-zA-Z0-9]*$, the function:

Copy
function DoSomething(){...} /* Noncompliant */

Multiple ++ or -- unary operators should not be used in a single arithmetic expression

Using several ”—” or ”++” unary operators in the same arithmetic expression can quickly make the expression unreadable.

Copy
var j:int = foo++ - --bar;

Control flow statements if, for, while and switch should not be nested too deeply

Nested control flow statements if, for, while, do while and switch are often key ingredients in creating what’s known as “Spaghetti code”. This code smell can make your program difficult to understand and maintain.

When numerous control structures are placed inside one another, the code becomes a tangled, complex web. This significantly reduces the code’s readability and maintainability, and it also complicates the testing process.

Copy
if (condition1) {                  // Compliant - depth = 1
/* ... */
if (condition2) {                // Compliant - depth = 2
  /* ... */
  for(int i = 0; i < 10; i++) {  // Compliant - depth = 3, not exceeding the limit
    /* ... */
    if (condition4) {            // Noncompliant - depth = 4
      if (condition5) {          // Depth = 5, exceeding the limit, but issues are only reported on depth = 4
        /* ... */
      }
      return;
    }
  }
}
}

Overriding methods should do more than simply call the same method in the super class

Overriding a method just to call the same method from the super class without performing any other actions is useless and misleading.

Copy
override public function doSomething() : void
{ 
super.doSomething(); 
}

override public function isLegal(action:Action) : Boolean 
{      
return super.isLegal(action);
}

Constructors should not dispatch events

A listener can be attached to an object only after it has been constructed. So dispatching an event in a constructor is useless and error prone.

Copy
public class MyClass 
{
public function MyClass()
{ 
dispatchEvent( new Event( "uselessEvent" ) );
}
}

Constructor bodies should be as lightweight as possible

In ActionScript 3, constructor code is always interpreted rather than compiled by the JIT at runtime, which is why the body of a constructor should be as lightweight as possible. As soon as a constructor contains branches (“if”, “for”, “switch”, …​) an issue is logged.

Copy
public class Foo
{
public function Foo()
{
if (condition) {  // Noncompliant
  // ...
}
}
}

Statements, operators and keywords specific to ActionScript 2 should not be used

Usage of statements, operators and keywords specific to ActionScript 2 does not allow to migrate to ActionScript 3. This includes “intrinsic” keyword, set variable statement and following list of operators:

  • `<> (inequality) - use != instead

  • add (concatenation (strings)) - use + instead

  • eq (equality (strings)) - use == instead

  • ne (not equal (strings)) - use != instead

  • lt (less than (strings)) - use < instead

  • le (less than or equal to (strings)) - use <= instead

  • gt (greater than (strings)) - use > instead

  • ge (greater than or equal to (strings)) - use >= instead

  • and (logical and) - use && instead

  • or (logical or) - use || instead

  • not (logical not) - use !` instead

Copy
if (true != false) { // Compliant
}

if (true <> false) { // Noncompliant
}

set("varName", value); // Noncompliant
varName = value; // Compliant

Cases in a switch should not have the same condition

Having multiple cases in a switch with the same condition is confusing at best. At worst, it’s a bug that is likely to induce further bugs as the code is maintained.

If the first case ends with a break, the second case will never be executed, rendering it dead code. Worse there is the risk in this situation that future maintenance will be done on the dead case, rather than on the one that’s actually used.

On the other hand, if the first case does not end with a break, both cases will be executed, but future maintainers may not notice that.

Copy
switch(i) {
case 1:
//...
break;
case 5:
//...
break;
case 3:
//...
break;
case 1:  // Noncompliant
//...
break;
}

Variables of the Object type should not be used

Creating a new variable with the type “Object” means that it may be used to store any kind of object. This feature may be required in some specific contexts, but it leaves the compiler unable to do any kind of type checking, and is therefore a hazardous practice.

Copy
var obj:Object = new String(); // Noncompliant; Object used explicitly
var foo = new Object(); // Noncompliant; Object used explicitly
var bar = {name:String, age:int};  // Noncompliant; Object implicitly created

LocalConnection should be configured to narrowly specify the domains with which local connections to other Flex application are allowed

A LocalConnection object is used to invoke a method in another LocalConnection object, either within a single SWF file or between multiple SWF files. This kind of local connection should be authorized only when the origin (domain) of the other Flex applications is perfectly defined.

Copy
localConnection.allowDomain("*");

Event types should be defined in metadata tags

According to the Flex documentation :

In this example, the “enableChange” event must be considered part of the API. Therefore, it should be strongly typed.

Copy
[Event(name="enableChange")] 
public class ModalText extends TextArea {...}

Constructors should not have a void return type

Even though this is syntactically correct, the void return type should not be used in the signature of a constructor. Indeed some developers might be confused by this syntax, believing that the constructor is in fact a standard function.

Copy
public class Foo   
{
public function Foo() : void
{...}      
}

MovieClip.onEnterFrame event handler should not be used

The onEnterFrame event handler is continually invoked at the frame rate of the SWF file, regardless of which individual movie frame it is set for. Having too many onEnterFrame handlers can seriously degrade performance.

If the use of this event handler cannot be avoided entirely, then it should be created as close to its use as possible, and then destroyed as soon as possible afterward.

Copy
movieClip.onEnterFrame = function () {   // Noncompliant
// ...
}

Public constants and fields initialized at declaration should be const static rather than merely const

Making a public constant just const as opposed to static const leads to duplicating its value for every instance of the class, uselessly increasing the amount of memory required to execute the application.

Copy
public class Myclass 
{
public const THRESHOLD:int = 3;   
}

Dynamic classes should not be used

A dynamic class defines an object that can be altered at run time by adding or changing properties and methods. This extremely powerful mechanism should be used very carefully, and only in very limited use cases.

Indeed, by definition dynamic classes make refactoring difficult and prevent the compiler from raising potential errors at compile time.

Copy
dynamic public class DynamicFoo
{...}

Security.allowDomain(...) should only be used in a tightly focused manner

Calling Security.allowDomain(”*”) lets any domain cross-script into the domain of this SWF and exercise its functionality.

Copy
Security.allowDomain("*");

A function should have a single point of exit at the end of the function

This is required by IEC 61508, under good programming style.

Copy
function func1() { // Noncompliant - there are two points of exit
if (false) {
return;
}
}

function func2() { // Noncompliant - there are two points of exit
if (a > 0) {
return 0;
}
return -1;
}

Octal values should not be used

Integer literals starting with a zero are octal rather than decimal values. While using octal values is fully supported, most developers do not have experience with them. They may not recognize octal values as such, mistaking them instead for decimal values.

Copy
var myNumber:int = 010;  // Noncompliant. myNumber will hold 8, not 10 - was this really expected?

Mergeable if statements should be combined

Nested code - blocks of code inside blocks of code - is eventually necessary, but increases complexity. This is why keeping the code as flat as possible, by avoiding unnecessary nesting, is considered a good practice.

Merging if statements when possible will decrease the nesting of the code and improve its readability.

Copy
if (condition1) {
if (condition2) {             // Noncompliant
...
}
}

Methods should not be empty

An empty {operationName} is generally considered bad practice and can lead to confusion, readability, and maintenance issues. Empty {operationName}s bring no functionality and are misleading to others as they might think the {operationName} implementation fulfills a specific and identified requirement.

There are several reasons for a {operationName} not to have a body:

  • It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.

  • It is not yet, or never will be, supported. In this case an exception should be thrown.

  • The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.

Copy
public function shouldNotBeEmpty():void {  // Noncompliant - method is empty
}

public function notImplemented():void {  // Noncompliant - method is empty
}

public override function emptyOnPurpose():void {  // Noncompliant - method is empty
}

Unused private fields should be removed

If a private field is declared but not used locally, its limited visibility makes it dead code.

This is either a sign that some logic is missing or that the code should be cleaned.

Cleaning out dead code decreases the size of the maintained codebase, making it easier to understand and preventing bugs from being introduced.

Copy
public class MyClass {
private var foo:int = 4;  // Noncompliant: foo is unused and should be removed

public function compute(a:int):int{
return a * 4;
}
}

Unused function parameters should be removed

A typical code smell known as unused function parameters refers to parameters declared in a function but not used anywhere within the function’s body. While this might seem harmless at first glance, it can lead to confusion and potential errors in your code. Disregarding the values passed to such parameters, the function’s behavior will be the same, but the programmer’s intention won’t be clearly expressed anymore. Therefore, removing function parameters that are not being utilized is considered best practice.

Copy
override function doSomething(a:int):void {    // ignored
compute(a);
}

...

class AbstractSomething {
public function doSomething(a:int) {  // ignored
throw new IllegalOperationError("doSomething() is abstract");
}

...

interface I {
function action(a:int, b:int);
}

class C extends I {
function action(a:int, b:int) { // ignored
return doSomethignWith(a);
}
}

function clickHandler(event:MouseEvent):void { // ignored
trace("click");
}

Package names should comply with a naming convention

Shared naming conventions improve readability and allow teams to collaborate efficiently. This rule checks that all package names match a provided regular expression.

Copy
package org.Example {  // Noncompliant
...
}

Class names should comply with a naming convention

Shared naming conventions allow teams to collaborate efficiently.

This rule raises an issue when a class name does not match a provided regular expression.

Copy
public class myClass {...} /* Noncompliant */

for loop stop conditions should be invariant

A `for loop stop condition should test the loop counter against an invariant value (i.e. one that is true at both the beginning and ending of every loop iteration). Ideally, this means that the stop condition is set to a local variable just before the loop begins.

Stop conditions that are not invariant are slightly less efficient, as well as being difficult to understand and maintain, and likely lead to the introduction of errors in the future.

This rule tracks three types of non-invariant stop conditions:

  • When the loop counters are updated in the body of the for` loop

  • When the stop condition depend upon a method call

  • When the stop condition depends on an object property, since such properties could change during the execution of the loop.

Copy
for (var i = 0; i < 10; i++) {
...
i = i - 1; // Noncompliant 
...
} 

for (var i = 0; i < getMaximumNumber(); i++) {...}

Functions should not contain too many return statements

Having too many return statements in a function increases the function’s essential complexity because the flow of execution is broken each time a return statement is encountered. This makes it harder to read and understand the logic of the function.

Copy
function myFunction():boolean { // Noncompliant as there are 4 return statements
if (condition1) {
return true;
} else {
if (condition2) {
  return false;
} else {
  return true;
}
}
return false;
}

switch case clauses should not have too many lines of code

The switch statement should be used only to clearly define some new branches in the control flow. As soon as a case clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated method.

Copy
switch (myVariable) {
case 0:       // Noncompliant - 6 lines till next case or default case
trace("");
trace("");
trace("");
trace("");
break;
case 1:
...
}

Track uses of TODO tags

Developers often use TODO tags to mark areas in the code where additional work or improvements are needed but are not implemented immediately. However, these TODO tags sometimes get overlooked or forgotten, leading to incomplete or unfinished code. This rule aims to identify and address unattended TODO tags to ensure a clean and maintainable codebase. This description explores why this is a problem and how it can be fixed to improve the overall code quality.

Copy
void doSomething() {
// TODO
}

Field names should comply with a naming convention

A naming convention in software development is a set of guidelines for naming code elements like variables, functions, and classes.

The goal of a naming convention is to make the code more readable and understandable, which makes it easier to maintain and debug. It also ensures consistency in the code, especially when multiple developers are working on the same project.

This rule checks that field names match a provided regular expression.

Copy
class MyClass {
public var my_field:int;
}

Unused private functions should be removed

This rule raises an issue when a {visibility} {operationName} is never referenced in the code.

Copy
public class Foo
{
public static function doSomething(): void  // Compliant - public function
{
var foo:Foo = new Foo();
...
}

private function unusedPrivateFunction(): void {...}  // Noncompliant
}

Useless if(true) {...} and if(false){...} blocks should be removed

`if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.

There are three possible causes for the presence of such code:

  • An if statement was changed during debugging and that debug code has been committed.

  • Some value was left unset.

  • Some logic is not doing what the programmer thought it did.

In any of these cases, unconditional if` statements should be removed.

Copy
if (true) {  
doSomething(); 
}
...
if (false) {  
doSomethingElse(); 
}

Empty statements should be removed

Empty statements represented by a semicolon ; are statements that do not perform any operation. They are often the result of a typo or a misunderstanding of the language syntax. It is a good practice to remove empty statements since they don’t add value and lead to confusion and errors.

Copy
function doSomething():void {
;                                                       // Noncompliant - was used as a kind of TODO marker
}

function doSomethingElse():void {
trace("Hello, world!");;                     // Noncompliant - double ;
...
for (var i:int = 0; i < 3; trace(i), i++);       // Noncompliant - Rarely, they are used on purpose as the body of a loop. It is a bad practice to have side-effects outside of the loop body
...
}

switch statements should have default clauses

The requirement for a final default clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken.

Copy
switch (param) { // Noncompliant - default clause is missing
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
}

switch (param) {
default: // Noncompliant - default clause should be the last one
doSomething();
break;
case 0:
doSomethingElse();
break;
}

switch statements should not be nested

Nested `switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.

Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch` to another function.

Copy
public function func(foo:Number, bar:Number):void
{
switch (foo)
{ 
case 1:
  // do something
  break;
case 2:
  switch (bar)  // Noncompliant
  {
    case 89:  // It's easy to lose sight of what's being tested; is it foo or bar?
      // ...
      break;
    case 90:
      // ...
      break;
  }
  break;
case 3:
  // do something
  break;
default:
  break;
}
}

Unused local variables should be removed

An unused local variable is a variable that has been declared but is not used anywhere in the block of code where it is defined. It is dead code, contributing to unnecessary complexity and leading to confusion when reading the code. Therefore, it should be removed from your code to maintain clarity and efficiency.

Copy
public function numberOfMinutes(hours:int):int
{
var seconds:int = 0;  // Noncompliant - seconds is unused 
return hours * 60;
}

Local variable and function parameter names should comply with a naming convention

A naming convention in software development is a set of guidelines for naming code elements like variables, functions, and classes. {identifier_capital_plural} hold the meaning of the written code. Their names should be meaningful and follow a consistent and easily recognizable pattern. Adhering to a consistent naming convention helps to make the code more readable and understandable, which makes it easier to maintain and debug. It also ensures consistency in the code, especially when multiple developers are working on the same project.

This rule checks that {identifier} names match a provided regular expression.

Copy
public function doSomething(my_param:int):void
{  
var LOCAL:int;
...
}

Public classes, methods, properties and metadata should be documented with ASDoc

Undocumented APIs pose significant challenges in software development for several reasons:

  • Lack of Clarity: developers struggling to understand how to use the API correctly. This can lead to misuse and unexpected results.

  • Increased Development Time: developers spending extra time reading and understanding the source code, which slows down the development process.

  • Error Prone: developers are more likely to make mistakes that lead to bugs or system crashes when the intent or the error handling of an API is not clear.

  • Difficult Maintenance and Updates: developers may not understand the existing functionality well enough to add new features without breaking the existing ones.

  • Poor Collaboration: collaboration, when there is lack of documentation, leads to confusion and inconsistencies.

Copy
/**
* @private  // This class and all its elements are ignored
*/
public class MyClass {  // Compliant

public var myLabel:String;   // Compliant
}

public class AnotherClass {  // Noncompliant; class not @private and not documented

/**
* @private
*/
public var name:String;  // Compliant
}

Local variables should not shadow class fields

Local variables should not shadow class fields

Copy
class Foo {
public var myField:int;

public function doSomething():String {
var myField:int = 0; // Noncompliant
//...
}
}
XmlGo
twitterlinkedin
Powered by Mintlify
Assistant
Responses are generated using AI and may contain mistakes.