From 93d476b4ffb02bba31b0cdb256a9ca436f9741ce Mon Sep 17 00:00:00 2001 From: jycr Date: Fri, 14 Apr 2023 18:26:42 +0200 Subject: [PATCH] refactor: convert rule description from HTML to ASCIIDOC --- .../src/main/rules/EC1/java/EC1.asciidoc | 39 +- .../src/main/rules/EC10/python/EC10.asciidoc | 54 +-- .../src/main/rules/EC2/java/EC2.asciidoc | 53 +-- .../main/rules/EC203/python/EC203.asciidoc | 151 +++---- .../src/main/rules/EC22/php/EC22.asciidoc | 22 +- .../src/main/rules/EC27/java/EC27.asciidoc | 52 +-- .../src/main/rules/EC28/java/EC28.asciidoc | 57 +-- .../src/main/rules/EC3/java/EC3.asciidoc | 35 +- .../src/main/rules/EC3/php/EC3.asciidoc | 189 ++++---- .../src/main/rules/EC32/java/EC32.asciidoc | 40 +- .../src/main/rules/EC34/php/1GB.etsdiff.csv | 3 + .../src/main/rules/EC34/php/EC34.asciidoc | 114 ++--- .../src/main/rules/EC34/python/EC34.asciidoc | 22 +- .../src/main/rules/EC4/java/EC4.asciidoc | 71 +-- .../src/main/rules/EC4/php/EC4.asciidoc | 42 +- .../src/main/rules/EC4/python/EC4.asciidoc | 24 +- .../main/rules/EC404/python/EC404.asciidoc | 25 +- .../src/main/rules/EC5/java/EC5.asciidoc | 38 +- .../src/main/rules/EC53/java/EC53.asciidoc | 33 +- .../src/main/rules/EC63/java/EC63.asciidoc | 19 +- .../src/main/rules/EC66/php/1GB.etsdiff.csv | 3 + .../src/main/rules/EC66/php/EC66.asciidoc | 116 ++--- .../src/main/rules/EC66/python/EC66.asciidoc | 58 +-- .../src/main/rules/EC67/java/EC67.asciidoc | 18 +- .../src/main/rules/EC67/php/1GB.etsdiff.csv | 3 + .../src/main/rules/EC67/php/EC67.asciidoc | 112 ++--- .../src/main/rules/EC69/java/EC69.asciidoc | 39 +- .../src/main/rules/EC69/php/1GB.etsdiff.csv | 3 + .../src/main/rules/EC69/php/EC69.asciidoc | 110 +---- .../src/main/rules/EC69/python/EC69.asciidoc | 18 +- .../src/main/rules/EC7/python/EC7.asciidoc | 18 +- .../src/main/rules/EC72/java/EC72.asciidoc | 73 ++-- .../src/main/rules/EC72/php/1GB.etsdiff.csv | 3 + .../src/main/rules/EC72/php/2GB.etsdiff.csv | 3 + .../src/main/rules/EC72/php/4GB.etsdiff.csv | 3 + .../src/main/rules/EC72/php/8GB.etsdiff.csv | 3 + .../src/main/rules/EC72/php/EC72.asciidoc | 408 ++++-------------- .../src/main/rules/EC72/python/EC72.asciidoc | 40 +- .../src/main/rules/EC74/java/EC74.asciidoc | 34 +- .../src/main/rules/EC74/php/1GB.etsdiff.csv | 3 + .../src/main/rules/EC74/php/EC74.asciidoc | 129 ++---- .../src/main/rules/EC74/python/EC74.asciidoc | 34 +- .../src/main/rules/EC75/java/EC75.asciidoc | 57 ++- .../src/main/rules/EC76/java/EC76.asciidoc | 62 ++- .../src/main/rules/EC77/java/EC77.asciidoc | 88 ++-- .../src/main/rules/EC78/java/EC78.asciidoc | 60 +-- .../src/main/rules/EC79/java/EC79.asciidoc | 40 +- .../main/rules/etsdiff-methodology.asciidoc | 11 + 48 files changed, 1075 insertions(+), 1557 deletions(-) create mode 100644 ecocode-rules-specifications/src/main/rules/EC34/php/1GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC66/php/1GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC67/php/1GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC69/php/1GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC72/php/1GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC72/php/2GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC72/php/4GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC72/php/8GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/EC74/php/1GB.etsdiff.csv create mode 100644 ecocode-rules-specifications/src/main/rules/etsdiff-methodology.asciidoc diff --git a/ecocode-rules-specifications/src/main/rules/EC1/java/EC1.asciidoc b/ecocode-rules-specifications/src/main/rules/EC1/java/EC1.asciidoc index c7bc959b3..91ae3f7f0 100644 --- a/ecocode-rules-specifications/src/main/rules/EC1/java/EC1.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC1/java/EC1.asciidoc @@ -1,20 +1,23 @@ -

The use of Spring repository in a loop induces unnecessary calculations by the CPU and therefore superfluous energy consumption.

-

Noncompliant Code Example

-
-		private final List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
+The use of Spring repository in a loop induces unnecessary calculations by the CPU and therefore superfluous energy consumption.
 
-		List<Employee> employees = new ArrayList<>();
-		
-		for (Integer id: ids) {
-            Optional<Employee> employee = employeeRepository.findById(id); // Noncompliant
-            if (employee.isPresent()) {
-                employees.add(employee.get());
-            }
-        }
+## Noncompliant Code Example
 
-
-

Compliant Solution

-
-		private final List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
-		List<Employee> employees = employeeRepository.findAllById(ids);
-
+```java +private final List ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); + +List employees = new ArrayList<>(); + +for (Integer id: ids) { + Optional employee = employeeRepository.findById(id); // Noncompliant + if (employee.isPresent()) { + employees.add(employee.get()); + } +} +``` + +## Compliant Solution + +```java +private final List ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); +List employees = employeeRepository.findAllById(ids); +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC10/python/EC10.asciidoc b/ecocode-rules-specifications/src/main/rules/EC10/python/EC10.asciidoc index 131ab21f8..cf2483171 100644 --- a/ecocode-rules-specifications/src/main/rules/EC10/python/EC10.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC10/python/EC10.asciidoc @@ -1,8 +1,10 @@ -

SVG images generated by common drawing softwares contains unnecessary data: calc layer, metadata, namespaces and comments.

-

Noncompliant Code Example

-
-<!-- Created with Inkscape (http://www.inkscape.org/) -->
-<svg
+SVG images generated by common drawing softwares contains unnecessary data: calc layer, metadata, namespaces and comments.
+
+## Noncompliant Code Example
+
+```xml
+
+
+    
+        
-

Compliant Solution

-
-<svg
-    width="210mm"
-    height="297mm"
-    viewBox="0 0 210 297"
-    xmlns="http://www.w3.org/2000/svg"
-    xmlns:svg="http://www.w3.org/2000/svg">
-    <g>
-        <circle
-            style="fill:#ff00ff;stroke-width:0.264583"
-            id="path111"
-            cx="104.02724"
-            cy="152.19028"
-            r="73.177132" />
-    </g>
-</svg>
-
+ r="73.177132" /> + + +``` + +## Compliant Solution + +```xml + + + +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc b/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc index 7e5fcc2a0..0e56f2845 100644 --- a/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC2/java/EC2.asciidoc @@ -1,31 +1,32 @@ -

If we are using too many conditional if-else statements it will impact performance since JVM will have to compare the conditions. We can think of using a switch statement instead of multiple if-else if possible. Switch statement has a performance advantage over if – else.

+If we are using too many conditional `if` – `else` statements it will impact performance since JVM will have to compare the conditions. We can think of using a switch statement instead of multiple `if` – `else` if possible. `switch` statement has a performance advantage over `if` – `else`. -

Non-compliant Code Example

-
-		int index = 1;
-        int nb = 2;
+## Non-compliant Code Example
 
-        if (nb > index) {
-            nb = nb + index;
-        } else {
-            nb = nb - 1;
-        }
-        if (nb != index + 1) {
-            nb = nb + index;
-        } else {
-            nb = nb - 1;
-        }
+```java
+int index = 1;
+int nb = 2;
 
+if (nb > index) {
+    nb = nb + index;
+} else {
+    nb = nb - 1;
+}
+if (nb != index + 1) {
+    nb = nb + index;
+} else {
+    nb = nb - 1;
+}
+```
 
-
-

Compliant Code Example

-
-        int index = 1;
-        int nb = 2;
+## Compliant Code Example
 
-        if (nb > index) {
-            nb = nb + index;
-        } else {
-            nb = nb - 1;
-        }
-
+```java +int index = 1; +int nb = 2; + +if (nb > index) { + nb = nb + index; +} else { + nb = nb - 1; +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc b/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc index 7f9e458fd..85d38acb6 100644 --- a/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC203/python/EC203.asciidoc @@ -1,73 +1,78 @@ -

If possible, the utilisation of svg image format (or <svg/> html tag) is recommended over other image format.

-

Because SVGs are generally smaller than other image format, they’re less taxing on your server despite needing to render on load.

-

When to use SVG : -

    -
  • Your image is used for decorative website graphics, logos, icons, graphs and diagrams, and other simple images.
  • -
  • You image require animation.
  • -
  • You image need to be responsive and scale without lack of quality.
  • -
-

-

Some advantages of using SVG: -

    -
  • SVGs are scalable and will render pixel-perfect at any resolution whereas JPEGs, PNGs and GIFs will not.
  • -
  • SVGs are vector images and therefore are usually much smaller in file-size than bitmap-based images.
  • -
  • SVGs can be embedded into the HTML which means they can be cached, edited directly using CSS and indexed for greater accessibility.
  • -
  • SVGs can be animated directly or by using CSS or JavaScript making it easy for web designers to add interactivity to a site.
  • -
-

- - -

Noncompliant Code Example

-
-    ...
-    img_jpg = "image.jpg"
-    ...
-
-

Compliant Solution

-
-    ...
-    img_svg = "image.svg"
-    ...
-
- -

Noncompliant Code Example

-
-    public void foo() {
-        ...
-        image_format = testImage("image.jpg")
-        ...
-    }
-
-

Compliant Solution

-
-    public void foo() {
-        ...
-        image_format = testImage("image.svg")
-        ...
-   }
-
- -

Noncompliant Code Example

-
-    public void foo() {
-        ...
-        return '<html><img src="xx/xx/image.bmp"></html>'
-        ...
-    }
-
-

Compliant Solution

-
-    public void foo() {
-        ...
-        return '<html><img src="xx/xx/image.svg"></html>'
-        ...
-   }
-
-     public void foo2() {
-        ...
-        return ('<html><svg width="100" height="100">' +
-                '<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />' +
-                '</svg></html>')
-        ...
-   }
-
+If possible, the utilisation of svg image format (or `` html tag) is recommended over other image format. + +Because SVGs are generally smaller than other image format, they’re less taxing on your server despite needing to render on load. + +When to use SVG : + +- Your image is used for decorative website graphics, logos, icons, graphs and diagrams, and other simple images. +- You image require animation. +- You image need to be responsive and scale without lack of quality. + +Some advantages of using SVG: + +- SVGs are scalable and will render pixel-perfect at any resolution whereas JPEGs, PNGs and GIFs will not. +- SVGs are vector images and therefore are usually much smaller in file-size than bitmap-based images. +- SVGs can be embedded into the HTML which means they can be cached, edited directly using CSS and indexed for greater accessibility. +- SVGs can be animated directly or by using CSS or JavaScript making it easy for web designers to add interactivity to a site. + +## Noncompliant Code Example + +``` +img_jpg = "image.jpg" +``` + +## Compliant Solution + +``` +img_svg = "image.svg" +``` + +## Noncompliant Code Example + +``` +public void foo() { + // ... + image_format = testImage("image.jpg") + // ... +} +``` + +## Compliant Solution + +``` +public void foo() { + // ... + image_format = testImage("image.svg") + // ... +} +``` + +## Noncompliant Code Example + +``` +public void foo() { + // ... + return '' + // ... +} +``` + +## Compliant Solution + +``` +public void foo() { + // ... + return '' + // ... +} +``` + +Or + +``` + public void foo() { + // ... + return ('') + // ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc b/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc index 0294f0a03..c42338993 100644 --- a/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC22/php/EC22.asciidoc @@ -1,9 +1,13 @@ -

Use of methods for basic operations

-

Noncompliant Code Example

-
-	$min = min($a, $b);  // Noncompliant
-
-

Compliant Solution

-
-	$min = $a < $b ? $a : $b;
-
+Use of methods for basic operations + +## Noncompliant Code Example + +```php +$min = min($a, $b); // Noncompliant +``` + +## Compliant Solution + +```php +$min = $a < $b ? $a : $b; +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC27/java/EC27.asciidoc b/ecocode-rules-specifications/src/main/rules/EC27/java/EC27.asciidoc index 8bfb72e6b..455e0a137 100644 --- a/ecocode-rules-specifications/src/main/rules/EC27/java/EC27.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC27/java/EC27.asciidoc @@ -1,24 +1,28 @@ -

Using System.arraycopy to copy arrays

-

- Programs spend most of the time in loops. These can be resource consuming, especially when they integrate heavy processing (IO access). Moreover, the size of the data and processing inside the loops will not allow full use of hardware mechanisms such as the cache or compiler optimization mechanisms.
- For example, an array copy is potentially a non-performance source if it is poorly designed. Indeed, the use of a single copy loop can be twice as consuming as dedicated methods.
- Loops must be optimized to reduce processing time and make full use of hardware and processor mechanisms and optimizations.
- In the case of table copying (table), the native System.arraycopy.
- We can also use copyOf or clone that are slightly less efficient.
- The looping method will be outlawed. -

-

Noncompliant Code Example

-
-	int len = array.length;
-	boolean[] copy = new boolean[array.length];
-	for (int i = 0; i < len; i++) {
-  		copy[i] = array[i];  // Noncompliant
-	}
-	return copy;
-
-

Compliant Solution

-
-	int[] copy = new int[array.length];
-	System.arraycopy(array, 0, copy, 0, array.length);
-	return copy;
-
+Using `System.arraycopy` to copy arrays + +Programs spend most of the time in loops. These can be resource consuming, especially when they integrate heavy processing (IO access). Moreover, the size of the data and processing inside the loops will not allow full use of hardware mechanisms such as the cache or compiler optimization mechanisms. + +For example, an array copy is potentially a non-performance source if it is poorly designed. Indeed, the use of a single copy loop can be twice as consuming as dedicated methods. +Loops must be optimized to reduce processing time and make full use of hardware and processor mechanisms and optimizations. +In the case of table copying (table), use the native `System.arraycopy`. +We can also use `copyOf` or `clone` that are slightly less efficient. +The looping method will be outlawed. + +## Noncompliant Code Example + +```java +int len = array.length; +boolean[] copy = new boolean[array.length]; +for (int i = 0; i < len; i++) { + copy[i] = array[i]; // Noncompliant +} +return copy; +``` + +## Compliant Solution + +```java +int[] copy = new int[array.length]; +System.arraycopy(array, 0, copy, 0, array.length); +return copy; +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc b/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc index d37bcef22..841ee9f8c 100644 --- a/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC28/java/EC28.asciidoc @@ -1,29 +1,30 @@ -

Optimize read file exception

-

Noncompliant Code Example

-
-		public void readPreferences(String filename) {
-		  //...
-		  InputStream in = null;
-		  try {
-			in = new FileInputStream(filename);
-		  } catch (FileNotFoundException e) {
-			logger.log(e);
-		  }
-		  in.read(...);
-		  //...
-		}
+Optimize read file exception
 
-
-

Compliant Solution

-
-		public void readPreferences(String filename)
-			throws IllegalArgumentException,
-				   FileNotFoundException, IOException {
-		  if (filename == null) {
-			throw new IllegalArgumentException ("filename is null");
-		  }  //if
-		  //...
-		  InputStream in = new FileInputStream(filename);
-		  //...
-		}
-
+## Noncompliant Code Example + +```java +public void readPreferences(String filename) { + //... + InputStream in = null; + try { + in = new FileInputStream(filename); + } catch (FileNotFoundException e) { + logger.log(e); + } + in.read(...); + //... +} +``` + +## Compliant Solution + +```java +public void readPreferences(String filename) throws IllegalArgumentException, FileNotFoundException, IOException { + if (filename == null) { + throw new IllegalArgumentException ("filename is null"); + } + //... + InputStream in = new FileInputStream(filename); + //... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc b/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc index b347d7141..49fcb223e 100644 --- a/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC3/java/EC3.asciidoc @@ -1,19 +1,22 @@ -

When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. The example provided below illustrates what should be avoided.

-

Noncompliant Code Example

-
-		List<String> objList = getData();
+When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. The example provided below illustrates what should be avoided.
 
-        for (int i = 0; i < objList.size(); i++) {  // Noncompliant
-            // execute code
-        }
+## Noncompliant Code Example
 
-
-

Compliant Solution

-
-        List<String> objList = getData();
+```java
+List objList = getData();
 
-        int size = objList.size();
-        for (int i = 0; i < size; i++) {
-            // execute code
-        }
-
+for (int i = 0; i < objList.size(); i++) { // Noncompliant + // execute code +} +``` + +## Compliant Solution + +```java +List objList = getData(); + +int size = objList.size(); +for (int i = 0; i < size; i++) { + // execute code +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC3/php/EC3.asciidoc b/ecocode-rules-specifications/src/main/rules/EC3/php/EC3.asciidoc index 3eace53ff..9c4d5bb81 100644 --- a/ecocode-rules-specifications/src/main/rules/EC3/php/EC3.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC3/php/EC3.asciidoc @@ -1,93 +1,96 @@ -

When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power.

-

NB : note that we are using the count() method to get the size of an array but it would work the same with the sizeof() and iterator_count() methods

- -

Noncompliant Code Examples

-
-	$array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
-
-	// FOR STATEMENTS / Right operand
-	for ($i = 0; $i < count($array); ++$i) {
-		var_dump($array[$i]);
-	}
-
-	// FOR STATEMENTS / Left operand
-	for ($i = 0; count($array) > $i; ++$i) {
-		var_dump($array[$i]);
-	}
-
-	// WHILE STATEMENTS / Right operand
-	$i = 0;
-	while($i < count($array)) {
-		var_dump($array[$i]);
-		++$i;
-	}
-
-	// WHILE STATEMENTS / Left operand
-	$i = 0;
-	while(count($array) > $i) {
-		var_dump($array[$i]);
-		++$i;
-	}
-
-	// DO WHILE STATEMENTS / Right operand
-	$i = 0;
-	do {
-		var_dump($array[$i]);
-		++$i;
-	} while ($i < count($array));
-
-	// DO WHILE STATEMENTS / Left operand
-	$i = 0;
-	do {
-		var_dump($array[$i]);
-		++$i;
-	} while (count($array) > $i);
-
- -

Compliant Solution

-
-	$array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea');
-	// FOR STATEMENTS / Right operand
-	$size = sizeof($array);
-	for ($i = 0; $i < $size; ++$i) {
-		var_dump($array[$i]);
-	}
-
-	// FOR STATEMENTS / Left operand
-	$size = sizeof($array);
-	for ($i = 0; $size > $i; ++$i) {
-		var_dump($array[$i]);
-	}
-
-	// WHILE STATEMENTS / Right operand
-	$i = 0;
-	$size = count($array);
-	while($i < $size) {
-		var_dump($array[$i]);
-		++$i;
-	}
-
-	// WHILE STATEMENTS / Left operand
-	$i = 0;
-	$size = count($array);
-	while($size > $i) {
-		var_dump($array[$i]);
-		++$i;
-	}
-
-	// DO WHILE STATEMENTS / Right operand
-	$i = 0;
-	$size = count($array);
-	do {
-		var_dump($array[$i]);
-		++$i;
-	} while ($i < $size);
-
-	// DO WHILE STATEMENTS / Left operand
-	$i = 0;
-	$size = count($array);
-	do {
-		var_dump($array[$i]);
-		++$i;
-	} while ($size > $i);
-
+When iterating over any collection, fetch the size of the collection in advance to avoid fetching it on each iteration, this saves CPU cycles, and therefore consumes less power. + +NB : note that we are using the `count()` method to get the size of an array but it would work the same with the `sizeof()` and `iterator_count()` methods. + +## Noncompliant Code Example + +```php +$array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea'); + +// FOR STATEMENTS / Right operand +for ($i = 0; $i < count($array); ++$i) { + var_dump($array[$i]); +} + +// FOR STATEMENTS / Left operand +for ($i = 0; count($array) > $i; ++$i) { + var_dump($array[$i]); +} + +// WHILE STATEMENTS / Right operand +$i = 0; +while($i < count($array)) { + var_dump($array[$i]); + ++$i; +} + +// WHILE STATEMENTS / Left operand +$i = 0; +while(count($array) > $i) { + var_dump($array[$i]); + ++$i; +} + +// DO WHILE STATEMENTS / Right operand +$i = 0; +do { + var_dump($array[$i]); + ++$i; +} while ($i < count($array)); + +// DO WHILE STATEMENTS / Left operand +$i = 0; +do { + var_dump($array[$i]); + ++$i; +} while (count($array) > $i); +``` + +## Compliant Solution + +```php +$array = array('orange', 'banana', 'apple', 'carrot', 'collard', 'pea'); +// FOR STATEMENTS / Right operand +$size = sizeof($array); +for ($i = 0; $i < $size; ++$i) { + var_dump($array[$i]); +} + +// FOR STATEMENTS / Left operand +$size = sizeof($array); +for ($i = 0; $size > $i; ++$i) { + var_dump($array[$i]); +} + +// WHILE STATEMENTS / Right operand +$i = 0; +$size = count($array); +while($i < $size) { + var_dump($array[$i]); + ++$i; +} + +// WHILE STATEMENTS / Left operand +$i = 0; +$size = count($array); +while($size > $i) { + var_dump($array[$i]); + ++$i; +} + +// DO WHILE STATEMENTS / Right operand +$i = 0; +$size = count($array); +do { + var_dump($array[$i]); + ++$i; +} while ($i < $size); + +// DO WHILE STATEMENTS / Left operand +$i = 0; +$size = count($array); +do { + var_dump($array[$i]); + ++$i; +} while ($size > $i); +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc b/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc index 253090269..00c2ac907 100644 --- a/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC32/java/EC32.asciidoc @@ -1,19 +1,21 @@ -

- If you know in advance how many characters would be appended, initialize builder/buffer with the appropriate size. - They will thus never have to be resized. - This saves CPU cycles and therefore consumes less energy. -

-

Noncompliant Code Example

-
-    StringBuilder sb = new StringBuilder(); // Noncompliant
-    for (int i = 0; i < 100; i++) {
-       sb.append(...);
-    }
-
-

Compliant Solution

-
-    StringBuilder sb = new StringBuilder(100);
-    for (int i = 0; i < 100; i++) {
-       sb.append(...);
-    }
-
+If you know in advance how many characters would be appended, initialize builder/buffer with the appropriate size. +They will thus never have to be resized. +This saves CPU cycles and therefore consumes less energy. + +## Noncompliant Code Example + +```java +StringBuilder sb = new StringBuilder(); // Noncompliant +for (int i = 0; i < 100; i++) { + sb.append(...); +} +``` + +## Compliant Solution + +```java +StringBuilder sb = new StringBuilder(100); +for (int i = 0; i < 100; i++) { + sb.append(...); +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC34/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC34/php/1GB.etsdiff.csv new file mode 100644 index 000000000..5b56c3789 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC34/php/1GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),515.855638,516.9188409999999 +Transfer (B),1579453,1579457 +Storage (B),637549804,637549804 diff --git a/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc b/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc index 5b8bd83c2..f7b2ab71d 100644 --- a/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC34/php/EC34.asciidoc @@ -1,7 +1,10 @@ -

Inside complex code parts (for exemple multiple loops, complex data constructions...), avoid using try...catch...finally.

-

When an exception is thrown, a variable (the exception itself) is created in a catch block and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.

-

Noncompliant Code Example

-
+Inside complex code parts (for exemple multiple loops, complex data constructions...), avoid using try...catch...finally.
+
+When an exception is thrown, a variable (the exception itself) is created in a catch block and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.
+
+## Noncompliant Code Example
+
+```php
 try
 {
   $picture = PDF_open_image_file($PDF, "jpeg", $imgFile, "", 0); // This is the original statement, this works on PHP4
@@ -11,10 +14,11 @@ catch(Exception $ex)
   $msg = "Error opening $imgFile for Product $row['Identifier']";
   throw new Exception($msg);
 }
+```
 
-
-

Compliant Solution

-
+## Compliant Solution
+
+```php
 //try
 if (file_exists($imgFile)) {
     $picture = PDF_open_image_file($PDF, "jpeg", $imgFile, "", 0);
@@ -25,85 +29,17 @@ if (!$picture) {
    $msg = "Error opening $imgFile for Product $row['Identifier']";
    print $msg;
 }
-
-

The three sources of impacts of a code identified are:

-- Energy (measured in joules) -
- Transfer (measured in Bytes) -
- Storage (measured in Bytes)
-
The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. -
The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). -
The results generated by ETSdiff must help define the interest of the rule reported by Sonarqube in the context of the code analyzed. -
-

Case for a 1GB database:

-
- ETSdiff percent comparison -
-

Total:

- - - - - - - - - - - - - - - - - - - - - - - -
-
-
Compliant
-
-
-
-
Non-compliant
-
-
-
-
Energy
-
-
-
-
515.855638
-
-
-
-
516.9188409999999
-
-
-
-
Transfer
-
-
-
-
1579453
-
-
-
-
1579457
-
-
-
-
Storage
-
-
-
-
637549804
-
-
-
-
637549804
-
-
+``` + +include::../../etsdiff-methodology.asciidoc[] + +## Case for a 1GB database: + +image::https://live.staticflickr.com/65535/52622382871_f19da08db4_o.png[ETSdiff percent comparison] + +[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant + +include::1GB.etsdiff.csv[] +|=== diff --git a/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc b/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc index d90cacc9e..14b3c3c5b 100644 --- a/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC34/python/EC34.asciidoc @@ -1,8 +1,10 @@ -

Inside complex code parts (for example multiple loops, complex data constructions...), avoid using try...catch...finally. -

When an exception is thrown, a variable (the exception itself) is created in a catch block, and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.

-

-

Noncompliant Code Example

-
+Inside complex code parts (for example multiple loops, complex data constructions...), avoid using try...catch...finally.
+
+When an exception is thrown, a variable (the exception itself) is created in a catch block, and it's destruction consumes unnecessary CPU cycles and RAM. Prefer using logical tests in this cases.
+
+## Noncompliant Code Example
+
+```python
 try:
     f = open(path)
     print(fh.read())
@@ -10,12 +12,14 @@ except:
     print('No such file '+path
 finally:
     f.close()
+```
 
-
-

Compliant Solution

-
+## Compliant Solution
+
+```python
 if os.path.isfile(path):
   fh = open(path, 'r')
   print(fh.read())
   fh.close
-
+``` + diff --git a/ecocode-rules-specifications/src/main/rules/EC4/java/EC4.asciidoc b/ecocode-rules-specifications/src/main/rules/EC4/java/EC4.asciidoc index e95fd679d..f8763b4ed 100644 --- a/ecocode-rules-specifications/src/main/rules/EC4/java/EC4.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC4/java/EC4.asciidoc @@ -1,34 +1,37 @@ -

- Prefer local variables as parameters -

-

When calling a global variable, the interpretation engine must check that it exists in all the scopes, that it has a value, etc. Passing global variables as arguments gives them the status of local variables inside the function, thus saving computing time (CPU cycles). -

-

-CASE 1 (Avoid as possible):
-You are back on the service code. You see that the func1() uses globalVariabl1. Okay, but whats its value by now ? How does it change ? Who mutates the globalVariabl1 before it comes to this function ? What have been the sequence of all these mutations ? You would have no idea. It will be quite difficult to figure all this out. -
-CASE 2 (Recommended):
-You are back to you code, and see that the func0() fetches something and then passes it to func1(param1) as a parameter. You clearly know what the data is, how does it gets here. -

-

Noncompliant Code Example

-
-    var aGlobal = new String('Hello');
-
-    function globalLength(){
-        length = aGlobal.length;
-        console.log(length);
-    }
-
-    globalLength();
-
-

Compliant Solution

-
-    var aGlobal = new String('Hello');
-
-    function someVarLength(str){
-        length = str.length;
-        console.log(length);
-    }
-
-    somVarLength(aGlobal);
-
\ No newline at end of file +Prefer local variables as parameters + +When calling a global variable, the interpretation engine must check that it exists in all the scopes, that it has a value, etc. Passing global variables as arguments gives them the status of local variables inside the function, thus saving computing time (CPU cycles). + +## CASE 1 (Avoid as possible) + +You are back on the service code. You see that the `func1()` uses `globalVariabl1`. Okay, but whats its value by now ? How does it change ? Who mutates the `globalVariabl1` before it comes to this function ? What have been the sequence of all these mutations ? You would have no idea. It will be quite difficult to figure all this out. + +## CASE 2 (Recommended) + +You are back to you code, and see that the `func0()` fetches something and then passes it to `func1(param1)` as a parameter. You clearly know what the data is, how does it gets here. + +## Noncompliant Code Example + +```java +var aGlobal = new String('Hello'); + +function globalLength(){ + length = aGlobal.length; + console.log(length); +} + +globalLength(); +``` + +## Compliant Solution + +```java +var aGlobal = new String('Hello'); + +function someVarLength(str){ + length = str.length; + console.log(length); +} + +somVarLength(aGlobal); +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc b/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc index 6e9687fa7..94021a9e6 100644 --- a/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC4/php/EC4.asciidoc @@ -1,27 +1,29 @@ -

- Prefer local variables as parameters -

-

When calling a global variable, the interpretation engine must check that it exists in all the scopes, that it has a value, etc. Passing global variables as arguments gives them the status of local variables inside the function, thus saving computing time (CPU cycles). -

-

Noncompliant Code Example

-
-  var aGlobal = new String('Hello');
-
-  function globalLength(){
+Prefer local variables as parameters
+
+When calling a global variable, the interpretation engine must check that it exists in all the scopes, that it has a value, etc. Passing global variables as arguments gives them the status of local variables inside the function, thus saving computing time (CPU cycles).
+
+## Noncompliant Code Example
+
+```php
+var aGlobal = new String('Hello');
+
+function globalLength(){
     length = aGlobal.length;
     console.log(length);
-  }
+}
+
+globalLength();
+```
+
+## Compliant Solution
 
-  globalLength();
-
-

Compliant Solution

-
-  var aGlobal = new String('Hello');
+```php
+var aGlobal = new String('Hello');
 
-  function someVarLength(str){
+function someVarLength(str){
     length = str.length;
     console.log(length);
-  }
+}
 
-  somVarLength(aGlobal);
-
\ No newline at end of file +somVarLength(aGlobal); +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc b/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc index c92e7e5be..b777840a9 100644 --- a/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC4/python/EC4.asciidoc @@ -1,20 +1,24 @@ -

When function calls global variables, a lot a CPU cycles is consumed.

-

Noncompliant Code Example

-
+When function calls global variables, a lot a CPU cycles is consumed.
+
+## Noncompliant Code Example
+
+```python
 global_var = 'foo'
 def print_global_var_details():
     print(len(global_var)) # Noncompliant
     print('Global var : ', global_var) # Noncompliant
     print('Global var : ' + global_var) # Noncompliant
 print_global_var_details()
-
-

Compliant Solution

-
+```
+
+## Compliant Solution
+
+```python
 global_var = 'foo';
 def print_var_details(local_var) {
-  print(len(local_var));
-  print('Var : ', local_var)
-  print('Var : ' + local_var)
+    print(len(local_var));
+    print('Var : ', local_var)
+    print('Var : ' + local_var)
 }
 print_length(global_var);
-
+``` diff --git a/ecocode-rules-specifications/src/main/rules/EC404/python/EC404.asciidoc b/ecocode-rules-specifications/src/main/rules/EC404/python/EC404.asciidoc index f7c47727f..4a0738f9f 100644 --- a/ecocode-rules-specifications/src/main/rules/EC404/python/EC404.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC404/python/EC404.asciidoc @@ -1,13 +1,20 @@ -

Use generator comprehension instead of list comprehension in for loop declaration.

-

Python generators resemble lazy lists from other programming languages: when iterated over, they compute their values on the fly. They lack some list behaviors (indexing, len method, ...) but are memory-efficient, as they do not store each of their values in memory, unlike lists. Thus, when declared in a for-loop declaration, list comprehensions can be safely replaced with generator comprehensions.

-

For more details on list comprehensions vs generator comprehensions, see Python documentation.

-

Noncompliant Code Example

-
+Use generator comprehension instead of list comprehension in for loop declaration.
+
+Python generators resemble lazy lists from other programming languages: when iterated over, they compute their values on the fly. They lack some list behaviors (indexing, len method, ...) but are memory-efficient, as they do not store each of their values in memory, unlike lists. Thus, when declared in a for-loop declaration, list comprehensions can be safely replaced with generator comprehensions.
+
+For more details on list comprehensions vs generator comprehensions, see https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions[Python documentation].
+
+## Noncompliant Code Example
+
+```python
 for var in [var2 for var2 in range(100)]:
     ...
-
-

Compliant Solution

-
+
+```
+
+## Compliant Solution
+
+```python
 for var in (var2 for var2 in range(100)):
     ...
-
+``` diff --git a/ecocode-rules-specifications/src/main/rules/EC5/java/EC5.asciidoc b/ecocode-rules-specifications/src/main/rules/EC5/java/EC5.asciidoc index 3fd5bb834..229a3503d 100644 --- a/ecocode-rules-specifications/src/main/rules/EC5/java/EC5.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC5/java/EC5.asciidoc @@ -1,18 +1,22 @@ -

Use PreparedStatement instead of Statement, because SQL will only commit the query once, whereas if you used only one statement, it would commit the query every time and thus induce unnecessary calculations by the CPU and therefore superfluous energy consumption.

-

Noncompliant Code Example

-
-    public void select() {
-        Statement statement = connection.createStatement();
-        statement.executeUpdate("INSERT INTO persons(id, name) VALUES(2, 'Toto')");  // Noncompliant
-    }
-
-

Compliant Solution

-
-    public void select() {
-        PreparedStatement statement = connection.prepareStatement(INSERT INTO persons(id, name) VALUES(?, ?));
+Use `PreparedStatement` instead of `Statement`, because SQL will only commit the query once, whereas if you used only one statement, it would commit the query every time and thus induce unnecessary calculations by the CPU and therefore superfluous energy consumption.
 
-        statement.setInt(1, 2);
-        statement.setString(2, "Toto");
-        statement.executeQuery();
-    }
-
+## Noncompliant Code Example + +```java +public void select() { + Statement statement = connection.createStatement(); + statement.executeUpdate("INSERT INTO persons(id, name) VALUES(2, 'John DOE')"); // Noncompliant +} +``` + +## Compliant Solution + +```java +public void select() { + PreparedStatement statement = connection.prepareStatement(INSERT INTO persons(id, name) VALUES(?, ?)); + + statement.setInt(1, 2); + statement.setString(2, "John DOE"); + statement.executeQuery(); +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC53/java/EC53.asciidoc b/ecocode-rules-specifications/src/main/rules/EC53/java/EC53.asciidoc index b1d548c92..924efda63 100644 --- a/ecocode-rules-specifications/src/main/rules/EC53/java/EC53.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC53/java/EC53.asciidoc @@ -1,18 +1,21 @@ -

Using List instead of Arrays with Foreach save CPU cycles calculations and RAM consumption.

-

Noncompliant Code Example

-
-		private final Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+Using List instead of Arrays with Foreach save CPU cycles calculations and RAM consumption.
 
-		for (Integer i : intArray) {
-			...
-		}
+## Noncompliant Code Example
 
-
-

Compliant Solution

-
-		private final List<Integer> intList = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });
+```java
+private final Integer[] intArray = new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
-		for (Integer i : intList) {
-			...
-		}
-
+for (Integer i : intArray) { + // ... +} +``` + +## Compliant Solution + +```java +private final List intList = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); + +for (Integer i : intList) { + // ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC63/java/EC63.asciidoc b/ecocode-rules-specifications/src/main/rules/EC63/java/EC63.asciidoc index be6d491d4..9d3ca796d 100644 --- a/ecocode-rules-specifications/src/main/rules/EC63/java/EC63.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC63/java/EC63.asciidoc @@ -1,12 +1,17 @@ -

Do not unnecessarily assign values to variables. It increases the use of RAM memory.

-

Noncompliant Code Example

-
+Do not unnecessarily assign values to variables. It increases the use of RAM memory.
+
+## Noncompliant Code Example
+
+```java
 String var1 = getValue();
 return var1;
 
 String var2 = "hello"
-var2 = "world"        //Non compliant cause never assigned 
+var2 = "world"        //Non compliant cause never assigned
+```
+
+## Compliant Solution
 
-
-

Compliant Solution

-
return getValue();
+```java +return getValue(); +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC66/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC66/php/1GB.etsdiff.csv new file mode 100644 index 000000000..4765a99fe --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC66/php/1GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),3.041966,1.2651545000000002 +Transfer (B),68520884,68588123 +Storage (B),637548795,637548795 diff --git a/ecocode-rules-specifications/src/main/rules/EC66/php/EC66.asciidoc b/ecocode-rules-specifications/src/main/rules/EC66/php/EC66.asciidoc index 233604feb..8af551481 100644 --- a/ecocode-rules-specifications/src/main/rules/EC66/php/EC66.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC66/php/EC66.asciidoc @@ -1,94 +1,30 @@ -

PHP allows declaring a string with simple or double quotes. Using double quotes allows developers to insert variables which will be substituted during execution. When the string has no variables, using single quotes prevents PHP from searching for non-existent variables. It will save CPU cycles consumption and RAM usage.

-

Noncompliant Code Example

-
+PHP allows declaring a string with simple or double quotes. Using double quotes allows developers to insert variables which will be substituted during execution. When the string has no variables, using single quotes prevents PHP from searching for non-existent variables. It will save CPU cycles consumption and RAM usage.
+
+## Noncompliant Code Example
+
+```php
 myFunction("name", "age", "IsStudent");
-  $lastName = "Hugo";
-  $concatenatedString = "$lastName is a student";
-
-

Compliant Solution

-
+    $lastName = "Hugo";
+    $concatenatedString = "$lastName is a student";
+```
+
+## Compliant Solution
+
+```php
 myFunction('name', 'age', 'IsStudent');
     $lastName = 'Hugo';
     $concatenatedString = $lastName . 'is a student';
-
-

The three sources of impacts of a code identified are:

-- Energy (measured in joules) -
- Transfer (measured in Bytes) -
- Storage (measured in Bytes)
-
The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. -
The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). -
The results generated by ETSdiff must help define the interest of the rule reported by Sonarqube in the context of the code analyzed. -
-

Case for a 1GB database:

-
- ETSdiff percent comparison -
-

Total:

- - - - - - - - - - - - - - - - - - - - - - - -
-
-
Compliant
-
-
-
-
Non-compliant
-
-
-
-
Energy
-
-
-
-
3.041966
-
-
-
-
1.2651545000000002
-
-
-
-
Transfer
-
-
-
-
68520884
-
-
-
-
68588123
-
-
-
-
Storage
-
-
-
-
637548795
-
-
-
-
637548795
-
-
+``` + +include::../../etsdiff-methodology.asciidoc[] + +## Case for a 1GB database: + +image::https://live.staticflickr.com/65535/52621866212_de15608a41_o.png[ETSdiff percent comparison] + +[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant + +include::1GB.etsdiff.csv[] +|=== diff --git a/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc b/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc index 0a94f3529..09e0eda41 100644 --- a/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC66/python/EC66.asciidoc @@ -1,27 +1,31 @@ -

- The shape using the quotation marks (") allows the developer to insert variables that will be substituted at run time.
- But if the string does not have a variable, use quotes (') instead.
- Thus, language will not look for variables to substitute, which will reduce the consumption of CPU cycles. -

-

Noncompliant Code Example

-
-    # in variables
-    firstname = "Andrea" # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}}
-
-    # in functions
-    def my_function(name, age):
-        print(name + 'is' + age + ' yo.')
-
-    my_function("Robert", 12) # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}}
-
-

Compliant Solution

-
-    # in variables
-    firstname = 'Andrea'
-
-    # in functions
-    def my_function(name, age):
-        print(name + 'is' + age + ' yo.')
-
-    my_function('Robert', 12)
-
+The shape using the quotation marks (") allows the developer to insert variables that will be substituted at run time. + +But if the string does not have a variable, use quotes (') instead. + +Thus, language will not look for variables to substitute, which will reduce the consumption of CPU cycles. + +## Noncompliant Code Example + +```python +# in variables +firstname = "Andrea" # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} + +# in functions +def my_function(name, age): + print(name + 'is' + age + ' yo.') + +my_function("Robert", 12) # Noncompliant {{Avoid using quotation mark ("), prefer using simple quote (')}} +``` + +## Compliant Solution + +```python +# in variables +firstname = 'Andrea' + +# in functions +def my_function(name, age): + print(name + 'is' + age + ' yo.') + +my_function('Robert', 12) +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc b/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc index 3c55323e5..a0c7b961a 100644 --- a/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC67/java/EC67.asciidoc @@ -1,7 +1,13 @@ -

The form $i++ creates a temporary variable whereas ++$i does not. It save CPU cycles.

-

Noncompliant Code Example

-
+The form `$i++` creates a temporary variable whereas `++$i` does not. It save CPU cycles.
+
+## Noncompliant Code Example
+
+```java
 i++  // Noncompliant
-
-

Compliant Solution

-
++i
+``` + +## Compliant Solution + +```java +++i +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC67/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC67/php/1GB.etsdiff.csv new file mode 100644 index 000000000..c79e54fc0 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC67/php/1GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),1.8163645000000002,0.2613885000000001 +Transfer (B),11265758,11290494 +Storage (B),637548673,637548673 diff --git a/ecocode-rules-specifications/src/main/rules/EC67/php/EC67.asciidoc b/ecocode-rules-specifications/src/main/rules/EC67/php/EC67.asciidoc index 6e087ebf4..9a025ea99 100644 --- a/ecocode-rules-specifications/src/main/rules/EC67/php/EC67.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC67/php/EC67.asciidoc @@ -1,88 +1,26 @@ -

The form $i++ creates a temporary variable whereas ++$i does not. It save CPU cycles.

-

Noncompliant Code Example

-
+The form `$i++` creates a temporary variable whereas `++$i` does not. It save CPU cycles.
+
+## Noncompliant Code Example
+
+```php
 $i++
-
-

Compliant Solution

-
++$i
-

The three sources of impacts of a code identified are:

-- Energy (measured in joules) -
- Transfer (measured in Bytes) -
- Storage (measured in Bytes)
-
The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. -
The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). -
The results generated by ETSdiff must help define the interest of the rule reported by Sonarqube in the context of the code analyzed. -
-

Case for a 1GB database:

-
- ETSdiff percent comparison -
-

Total:

- - - - - - - - - - - - - - - - - - - - - - - -
-
-
Compliant
-
-
-
-
Non-compliant
-
-
-
-
Energy
-
-
-
-
1.8163645000000002
-
-
-
-
0.2613885000000001
-
-
-
-
Transfer
-
-
-
-
11265758
-
-
-
-
11290494
-
-
-
-
Storage
-
-
-
-
637548673
-
-
-
-
637548673
-
-
\ No newline at end of file +``` + +## Compliant Solution + +```php +++$i +``` + +include::../../etsdiff-methodology.asciidoc[] + +## Case for a 1GB database: + +image::https://live.staticflickr.com/65535/52622379586_f84c767111_o.png[ETSdiff percent comparison] + +[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant + +include::1GB.etsdiff.csv[] +|=== diff --git a/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc b/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc index 5d8c46aa1..e32cd94db 100644 --- a/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC69/java/EC69.asciidoc @@ -1,23 +1,24 @@ -

Do not call a function when declaring a for-type loop in order to avoid function calls each iterations. It saves CPU cycles.

-

Noncompliant Code Example

-
-    public void foo() {
-        for (int i = 0; i < getMyValue(); i++) {  // Noncompliant
-            System.out.println(i);
-            boolean b = getMyValue() > 6;
-        }
-    }
+Do not call a function when declaring a for-type loop in order to avoid function calls each iterations. It saves CPU cycles.
 
-
-

Compliant Solution

-
+## Noncompliant Code Example
 
-    public void foo() {
-        int myValue =  getMyValue();
-        for (int i = 0; i < myValue; i++) {
-            System.out.println(i);
-            boolean b = getMyValue() > 6;
-        }
+```java
+public void foo() {
+    for (int i = 0; i < getMyValue(); i++) {  // Noncompliant
+        System.out.println(i);
+        boolean b = getMyValue() > 6;
     }
+}
+```
+
+## Compliant Solution
 
-
+```java +public void foo() { + int myValue = getMyValue(); + for (int i = 0; i < myValue; i++) { + System.out.println(i); + boolean b = getMyValue() > 6; + } +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC69/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC69/php/1GB.etsdiff.csv new file mode 100644 index 000000000..227f4def5 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC69/php/1GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),144.635057,144.58341249999998 +Transfer (B),50000,50004 +Storage (B),637549590,637549590 diff --git a/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc b/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc index c71d96a37..0da3cde83 100644 --- a/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC69/php/EC69.asciidoc @@ -1,12 +1,16 @@ -

Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.

-

Noncompliant Code Example

-
+Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.
+
+## Noncompliant Code Example
+
+```php
 for ($i = 0; $i <= foo(); $i++) {  // Noncompliant
 	// ......
 }
-
-

Compliant Solution

-
+```
+
+## Compliant Solution
+
+```php
 $maxI = foo();
 for ($i = 0; $i <= $maxI; $i++) {
   .....
@@ -17,88 +21,18 @@ for ($i = 0; $i <= $maxI; $i++) {
 for ($i = 0, $maxI = foo(); $i <= $maxI; $i++) {
   .....
 }
-}
+} +``` + +include::../../etsdiff-methodology.asciidoc[] + +## Case for a 1GB database: -

The three sources of impacts of a code identified are:

-- Energy (measured in joules) -
- Transfer (measured in Bytes) -
- Storage (measured in Bytes)
-
The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. -
The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). -
The results generated by ETSdiff must help define the interest of the rule reported by Sonarqube in the context of the code analyzed. -
+image::https://live.staticflickr.com/65535/52622634654_bf3c3d9ba8_o.png[ETSdiff percent comparison] -

Case for a 1GB database:

-
- ETSdiff percent comparison -
+[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant -

Total:

- - - - - - - - - - - - - - - - - - - - - - - -
-
-
Compliant
-
-
-
-
Non-compliant
-
-
-
-
Energy
-
-
-
-
144.635057
-
-
-
-
144.58341249999998
-
-
-
-
Transfer
-
-
-
-
50000
-
-
-
-
50004
-
-
-
-
Storage
-
-
-
-
637549590
-
-
-
-
637549590
-
-
+include::1GB.etsdiff.csv[] +|=== diff --git a/ecocode-rules-specifications/src/main/rules/EC69/python/EC69.asciidoc b/ecocode-rules-specifications/src/main/rules/EC69/python/EC69.asciidoc index 2c3c64ff1..3d73ce30a 100644 --- a/ecocode-rules-specifications/src/main/rules/EC69/python/EC69.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC69/python/EC69.asciidoc @@ -1,13 +1,17 @@ -

Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.

-

Noncompliant Code Example

-
+Do not call a function when declaring a for-type loop in order to avoid function calls each iteration. It saves CPU cycles.
+
+## Noncompliant Code Example
+
+```python
 for i in my_function():  # Noncompliant
     ......
+```
 
-
-

Compliant Solution

-
+## Compliant Solution
+
+```python
 limit = my_function()
 for i in limit:
     ......
-
+``` + diff --git a/ecocode-rules-specifications/src/main/rules/EC7/python/EC7.asciidoc b/ecocode-rules-specifications/src/main/rules/EC7/python/EC7.asciidoc index dba3dd847..4ca4240e5 100644 --- a/ecocode-rules-specifications/src/main/rules/EC7/python/EC7.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC7/python/EC7.asciidoc @@ -1,6 +1,8 @@ -

Avoid using getters and setters in a class, as they increase unnecessary RAM memory usage.

-

Noncompliant Code Example

-
+Avoid using getters and setters in a class, as they increase unnecessary RAM memory usage.
+
+## Noncompliant Code Example
+
+```python
 class Client():
 
     def __init__(self, age):
@@ -15,10 +17,11 @@ class Client():
 client = Client(25)
 client.get_age() # Getter inutile
 client.set_age(25) # Setter inutile
+```
 
-
-

Compliant Solution

-
+## Compliant Solution
+
+```python
 class Client():
 
     def __init__(self, age):
@@ -33,4 +36,5 @@ class Client():
 client = Client(25)
 client.age # Récupérer l'attribut age
 client.age = 26 # Modifier l'attribut age
-
+``` + diff --git a/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc b/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc index 7c6588afb..7032eb960 100644 --- a/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC72/java/EC72.asciidoc @@ -1,41 +1,17 @@ -

Executing SQL queries in loop induced unnecessary calculation by the cpu, RAM usage and network transfer.

-

Noncompliant Code Example

-
-    public void foo() {
-        ...
-        String baseQuery = "SELECT name FROM users where id = ";
-
-        for (int i = 0; i < 20; i++) {
-
-            String query  = baseQuery.concat("" + i);
-            Statement st = conn.createStatement();
-            ResultSet rs = st.executeQuery(query); // Noncompliant
-
-            // iterate through the java resultset
-            while (rs.next()) {
-                String name = rs.getString("name");
-                System.out.println(name);
-            }
-            st.close();
-        }
-        ...
-    }
+Executing SQL queries in loop induced unnecessary calculation by the CPU, RAM usage and network transfer.
 
-
-

Compliant Solution

-
+## Noncompliant Code Example
 
-    public void foo() {
-        ...
-        String query = "SELECT name FROM users where id in (0 ";
-        for (int i = 1; i < 20; i++) {
+```java
+public void foo() {
+    // ...
+    String baseQuery = "SELECT name FROM users where id = ";
 
-            query  = baseQuery.concat("," + i);
-        }
+    for (int i = 0; i < 20; i++) {
 
-        query  = baseQuery.concat(")");
+        String query  = baseQuery.concat("" + i);
         Statement st = conn.createStatement();
-        ResultSet rs = st.executeQuery(query); // compliant
+        ResultSet rs = st.executeQuery(query); // Noncompliant
 
         // iterate through the java resultset
         while (rs.next()) {
@@ -43,7 +19,32 @@
             System.out.println(name);
         }
         st.close();
-        ...
-   }
+    }
+    // ...
+}
+```
+
+## Compliant Solution
 
-
+```java +public void foo() { + // ... + String query = "SELECT name FROM users where id in (0 "; + for (int i = 1; i < 20; i++) { + + query = baseQuery.concat("," + i); + } + + query = baseQuery.concat(")"); + Statement st = conn.createStatement(); + ResultSet rs = st.executeQuery(query); // compliant + + // iterate through the java resultset + while (rs.next()) { + String name = rs.getString("name"); + System.out.println(name); + } + st.close(); + // ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC72/php/1GB.etsdiff.csv new file mode 100644 index 000000000..b006091ac --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC72/php/1GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),73.907586,82.15627099999998 +Transfer (B),49526,221836 +Storage (B),637549572,637549572 diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/2GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC72/php/2GB.etsdiff.csv new file mode 100644 index 000000000..73f5bac22 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC72/php/2GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),159.4871645,169.746055 +Transfer (B),50385,228225 +Storage (B),1178614788,1178614788 diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/4GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC72/php/4GB.etsdiff.csv new file mode 100644 index 000000000..4c253ef72 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC72/php/4GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),395.7629349999999,404.37447649999996 +Transfer (B),51597,238884 +Storage (B),2357214212,2357214212 diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/8GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC72/php/8GB.etsdiff.csv new file mode 100644 index 000000000..2a518e5eb --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC72/php/8GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),992.128585,1005.4625534999999 +Transfer (B),52189,249499 +Storage (B),4685052932,4685052932 diff --git a/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc b/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc index 7973ec509..12fe0d7b7 100644 --- a/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC72/php/EC72.asciidoc @@ -1,349 +1,91 @@ -

Executing SQL queries in loop induced unnecessary network transfert, calculation by the cpu and RAM usage.

-

Noncompliant Code Example

-
-    public function foo() {
-        ...
-        $baseQuery = "SELECT name FROM users where id = ";
+Executing SQL queries in loop induced unnecessary network transfert, calculation by the cpu and RAM usage.
+
+## Noncompliant Code Example
+
+```php
+public function foo() {
+    ...
+    $baseQuery = "SELECT name FROM users where id = ";
 
-        for ($i = 0; $i < 20; ++$i) {
+    for ($i = 0; $i < 20; ++$i) {
 
-            $query = $baseQuery . $i;
-            $connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
-		        mysql_select_db($dbname) or die("Could not open the db '$dbname'");
-            $result = mysql_query($this->Query);// Noncompliant
+        $query = $baseQuery . $i;
+        $connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
+            mysql_select_db($dbname) or die("Could not open the db '$dbname'");
+        $result = mysql_query($this->Query);// Noncompliant
 
-            // iterate through the result
-            ...
-            mysql_close($connection);
-        }
+        // iterate through the result
         ...
+        mysql_close($connection);
     }
+    ...
+}
+```
 
-
-

Compliant Solution

-
+## Compliant Solution
 
-    public function foo() {
-        ...
-        $query = "SELECT name FROM users where id in (";
+```php
+public function foo() {
+    ...
+    $query = "SELECT name FROM users where id in (";
 
-        for ($i = 0; $i < 20; ++$i) {
-            $query .= ',' . $i;
-        }
-        $query .= ')';
+    for ($i = 0; $i < 20; ++$i) {
+        $query .= ',' . $i;
+    }
+    $query .= ')';
 
-        $connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
-        mysql_select_db($dbname) or die("Could not open the db '$dbname'");
-        $result = mysql_query($this->Query); // compliant
+    $connection = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to Connect to '$dbhost'");
+    mysql_select_db($dbname) or die("Could not open the db '$dbname'");
+    $result = mysql_query($this->Query); // compliant
 
-        // iterate through the result
-        ...
-        mysql_close($connection);
-   }
+    // iterate through the result
+    ...
+    mysql_close($connection);
+}
+```
+
+include::../../etsdiff-methodology.asciidoc[]
+
+## Case for a 1GB database:
+
+image::https://live.staticflickr.com/65535/52622813465_9c453a43b1_w.jpg[ETSdiff percent comparison" style="padding: 1rem;]
+
+[format=csv,cols="1h,1,1"]
+|===
+Source of impacts,Compliant,Non-compliant
+
+include::1GB.etsdiff.csv[]
+|===
+
+## Case for a 2GB database:
+
+image::https://live.staticflickr.com/65535/52622862388_720fd219ba_o.png[ETSdiff percent comparison" style="padding: 1rem;]
+
+[format=csv,cols="1h,1,1"]
+|===
+Source of impacts,Compliant,Non-compliant
+
+include::2GB.etsdiff.csv[]
+|===
+
+## Case for a 4GB database:
+
+image::https://live.staticflickr.com/65535/52622814395_f8aab7a5c0_o.png[ETSdiff percent comparison" style="padding: 1rem;]
 
-
+[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant -

The three sources of impacts of a code identified are:

- - Energy (measured in joules) -
- Transfer (measured in Bytes) -
- Storage (measured in Bytes)
-
The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. -
The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). -
The results generated by ETSdiff must help define the interest of the rule reported by Sonarqube in the context of the code analyzed. -
+include::4GB.etsdiff.csv[] +|=== -

Case for a 1GB database:

-
- ETSdiff percent comparison -
-

Total:

- - - - - - - - - - - - - - - - - - - - - - - -
-
-
Compliant
-
-
-
-
Non-compliant
-
-
-
-
Energy
-
-
-
-
73.907586
-
-
-
-
82.15627099999998
-
-
-
-
Transfer
-
-
-
-
49526
-
-
-
-
221836
-
-
-
-
Storage
-
-
-
-
637549572
-
-
-
-
637549572
-
-
+## Case for a 8GB database: -

Case for a 2GB database:

-
- ETSdiff percent comparison -
-

Total:

- - - - - - - - - - - - - - - - - - - - - - - -
-
-
Compliant
-
-
-
-
Non-compliant
-
-
-
-
Energy
-
-
-
-
159.4871645
-
-
-
-
169.746055
-
-
-
-
Transfer
-
-
-
-
50385
-
-
-
-
228225
-
-
-
-
Storage
-
-
-
-
1178614788
-
-
-
-
1178614788
-
-
+image::https://live.staticflickr.com/65535/52622635779_f1c5d9660e_o.png[ETSdiff percent comparison" style="padding: 1rem;] -

Case for a 4GB database:

-
- ETSdiff percent comparison -
-

Total:

- - - - - - - - - - - - - - - - - - - - - - - -
-
-
Compliant
-
-
-
-
Non-compliant
-
-
-
-
Energy
-
-
-
-
395.7629349999999
-
-
-
-
404.37447649999996
-
-
-
-
Transfer
-
-
-
-
51597
-
-
-
-
238884
-
-
-
-
Storage
-
-
-
-
2357214212
-
-
-
-
2357214212
-
-
+[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant -

Case for a 8GB database:

-
- ETSdiff percent comparison -
-

Total:

- - - - - - - - - - - - - - - - - - - - - - - -
-
-
Compliant
-
-
-
-
Non-compliant
-
-
-
-
Energy
-
-
-
-
992.128585
-
-
-
-
1005.4625534999999
-
-
-
-
Transfer
-
-
-
-
52189
-
-
-
-
249499
-
-
-
-
Storage
-
-
-
-
4685052932
-
-
-
-
4685052932
-
-
\ No newline at end of file +include::8GB.etsdiff.csv[] +|=== diff --git a/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc b/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc index 2323c02f5..ae85dfe3e 100644 --- a/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC72/python/EC72.asciidoc @@ -1,21 +1,23 @@ -

Executing SQL queries in loop induced unnecessary calculation by the cpu, RAM usage and network transfer.

-

Noncompliant Code Example

-
-    def foo():
-        ...
-        results = []
-        for id in range(20):
-          results.append(cursor.execute("SELECT name FROM users where id = ?", (id)).fetchone()) # Noncompliant {{Avoid performing SQL queries within a loop}}
-        ...
-
-

Compliant Solution

-
+Executing SQL queries in loop induced unnecessary calculation by the CPU, RAM usage and network transfer.
 
-    def foo():
-        ...
-        ids = range(20)
-        results = cursor.execute("SELECT name FROM users where id IN ({0})".format(', '.join("?" * len(ids))), ids).fetchmany() # Compliant
-        ...
-   }
+## Noncompliant Code Example
 
-
+```python +def foo(): + ... + results = [] + for id in range(20): + results.append(cursor.execute("SELECT name FROM users where id = ?", (id)).fetchone()) # Noncompliant {{Avoid performing SQL queries within a loop}} + ... +``` + +## Compliant Solution + +```python +def foo(): + ... + ids = range(20) + results = cursor.execute("SELECT name FROM users where id IN ({0})".format(', '.join("?" * len(ids))), ids).fetchmany() # Compliant + ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc b/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc index 35ffbf7af..4f1299b18 100644 --- a/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC74/java/EC74.asciidoc @@ -1,21 +1,21 @@ -

Database servers have to resolve schema fields when using asterisk symbol (*). Knowing and using the schema saves CPU cycles and network transfer.

-

Noncompliant Code Example

-
-    public void foo() {
-        ...
-        String baseQuery = "SELECT * FROM users"; // Noncompliant
+Database servers have to resolve schema fields when using asterisk symbol (`*`). Knowing and using the schema saves CPU cycles and network transfer.
 
-        ...
-    }
+## Noncompliant Code Example
 
-
-

Compliant Solution

-
+```java
+public void foo() {
+    // ...
+    String baseQuery = "SELECT * FROM users"; // Noncompliant
+    // ...
+}
+```
 
-    public void foo() {
-        ...
-        String query = "SELECT id, name, address FROM users ";
-        ...
-   }
+## Compliant Solution
 
-
+```java +public void foo() { + // ... + String query = "SELECT id, name, address FROM users"; + // ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC74/php/1GB.etsdiff.csv b/ecocode-rules-specifications/src/main/rules/EC74/php/1GB.etsdiff.csv new file mode 100644 index 000000000..06710e417 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/EC74/php/1GB.etsdiff.csv @@ -0,0 +1,3 @@ +Energy (J),0.040610499999999994,0.065223 +Transfer (B),779232,2697937 +Storage (B),637548827,637548827 diff --git a/ecocode-rules-specifications/src/main/rules/EC74/php/EC74.asciidoc b/ecocode-rules-specifications/src/main/rules/EC74/php/EC74.asciidoc index de53be78e..ffb380dd5 100644 --- a/ecocode-rules-specifications/src/main/rules/EC74/php/EC74.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC74/php/EC74.asciidoc @@ -1,101 +1,34 @@ -

Database servers have to resolve schema fields when using asterisk symbol (*). Knowing and using the schema saves CPU cycles and network transfer.

-

Noncompliant Code Example

-
-    public function foo() {
-        ...
-        $baseQuery = "SELECT * FROM users"; // Noncompliant
+Database servers have to resolve schema fields when using asterisk symbol (`*`). Knowing and using the schema saves CPU cycles and network transfer.
 
-        ...
-    }
-
-

Compliant Solution

-
-    public function foo() {
-        ...
-        $baseQuery = "SELECT id,name, address FROM users ";
-        ...
-   }
-
-

The three sources of impacts of a code identified are:

-- Energy (measured in joules) -
- Transfer (measured in Bytes) -
- Storage (measured in Bytes)
-
The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. -
The ETSdiff tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). -
The results generated by ETSdiff must help define the interest of the rule reported by Sonarqube in the context of the code analyzed. -
+## Noncompliant Code Example -

Case for a 1GB database:

-
- ETSdiff percent comparison -
+```php +public function foo() { + ... + $baseQuery = "SELECT * FROM users"; // Noncompliant + ... +} +``` -

Total:

- - - - - - - - - - - - - - - - - - - - - - - -
-
-
Compliant
-
-
-
-
Non-compliant
-
-
-
-
Energy
-
-
-
-
0.040610499999999994
-
-
-
-
0.065223
-
-
-
-
Transfer
-
-
-
-
779232
-
-
-
-
2697937
-
-
-
-
Storage
-
-
-
-
637548827
-
-
-
-
637548827
-
-
+## Compliant Solution + +```php +public function foo() { + ... + $baseQuery = "SELECT id,name, address FROM users "; + ... +} +``` + +include::../../etsdiff-methodology.asciidoc[] + +## Case for a 1GB database: + +image::https://live.staticflickr.com/65535/52622636584_52938fcf7e_o.png[ETSdiff percent comparison] + +[format=csv,cols="1h,1,1"] +|=== +Source of impacts,Compliant,Non-compliant + +include::1GB.etsdiff.csv[] +|=== diff --git a/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc b/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc index 35ffbf7af..3b9b41c0f 100644 --- a/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC74/python/EC74.asciidoc @@ -1,21 +1,21 @@ -

Database servers have to resolve schema fields when using asterisk symbol (*). Knowing and using the schema saves CPU cycles and network transfer.

-

Noncompliant Code Example

-
-    public void foo() {
-        ...
-        String baseQuery = "SELECT * FROM users"; // Noncompliant
+Database servers have to resolve schema fields when using asterisk symbol (`*`). Knowing and using the schema saves CPU cycles and network transfer.
 
-        ...
-    }
+## Noncompliant Code Example
 
-
-

Compliant Solution

-
+```python
+public void foo() {
+    ...
+    String baseQuery = "SELECT * FROM users"; // Noncompliant
+    ...
+}
+```
 
-    public void foo() {
-        ...
-        String query = "SELECT id, name, address FROM users ";
-        ...
-   }
+## Compliant Solution
 
-
+```python +public void foo() { + ... + String query = "SELECT id, name, address FROM users "; + ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC75/java/EC75.asciidoc b/ecocode-rules-specifications/src/main/rules/EC75/java/EC75.asciidoc index 67c1c1ccf..6cbc5ed2a 100644 --- a/ecocode-rules-specifications/src/main/rules/EC75/java/EC75.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC75/java/EC75.asciidoc @@ -1,41 +1,38 @@ -

- Don't concatenate Strings in loop. User StringBuilder instead.
- Strings are immutable so each time you concatenate a String, a new String is created. This is a waste of memory and CPU. -

+Don't concatenate Strings in loop. Use `StringBuilder instead. -

Noncompliant Code Example

-
+Strings are immutable so each time you concatenate a String, a new String is created. This is a waste of memory and CPU.
 
-    public String concatenateStrings(String[] strings) {
-        String result = "";
+## Noncompliant Code Example
 
-        for (String string : strings) {
-            result += string; // Noncompliant
-        }
-        return result;
+```java
+public String concatenateStrings(String[] strings) {
+    String result = "";
+
+    for (String string : strings) {
+        result += string; // Noncompliant
     }
+    return result;
+}
 
-    public String concatenateStrings2() {
-        String result = "";
+public String concatenateStrings2() {
+    String result = "";
 
-        for (int i = 0; i < 1000; ++i) {
-            result += "another"; // Noncompliant
-        }
-        return result;
+    for (int i = 0; i < 1000; ++i) {
+        result += "another"; // Noncompliant
     }
+    return result;
+}
+```
 
-
- -

Compliant Solution

-
+## Compliant Solution
 
-    public String concatenateStrings(String[] strings) {
-        StringBuilder result = new StringBuilder();
+```java
+public String concatenateStrings(String[] strings) {
+    StringBuilder result = new StringBuilder();
 
-        for (String string : strings) {
-            result.append(string);
-        }
-        return result.toString();
+    for (String string : strings) {
+        result.append(string);
     }
-
-
+ return result.toString(); +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC76/java/EC76.asciidoc b/ecocode-rules-specifications/src/main/rules/EC76/java/EC76.asciidoc index 608b0285b..f21e5298c 100644 --- a/ecocode-rules-specifications/src/main/rules/EC76/java/EC76.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC76/java/EC76.asciidoc @@ -1,38 +1,36 @@ -

- Avoid usage of static collections.
- If you want to use static collections make them final and create for example a singleton if needed containing the collections.
- The static fields are more complicated for the Garbage Collector to manage and can lead to memory leaks. -

- -

Noncompliant Code Example

-
-
-    /**
-     * Not compliant
-     */
-    public class AvoidUsageOfStaticCollections {
-        public static final List<> LIST = new ArrayList<>();
-        public static final Set<> SET = new HashSet<>();
-        public static final Map<> MAP = new HashMap<>();
-    }
+Avoid usage of static collections.
 
-
+If you want to use static collections make them final and create for example a singleton if needed containing the collections. -

Compliant Solution

-
+The static fields are more complicated for the Garbage Collector to manage and can lead to memory leaks.
 
-    /**
-     * Compliant
-     */
-    public class GoodUsageOfStaticCollections {
-        public static volatile GoodUsageOfStaticCollections INSTANCE = new GoodUsageOfStaticCollections();
+## Noncompliant Code Example
 
-        public final List<> LIST = new ArrayList<>();
-        public final Set<> SET = new HashSet<>();
-        public final Map<> MAP = new HashMap<>();
+```java
+/**
+ * Not compliant
+ */
+public class AvoidUsageOfStaticCollections {
+    public static final List<> LIST = new ArrayList<>();
+    public static final Set<> SET = new HashSet<>();
+    public static final Map<> MAP = new HashMap<>();
+}
+```
 
-        private GoodUsageOfStaticCollections() {
-        }
-    }
+## Compliant Solution
+
+```java
+/**
+ * Compliant
+ */
+public class GoodUsageOfStaticCollections {
+    public static volatile GoodUsageOfStaticCollections INSTANCE = new GoodUsageOfStaticCollections();
 
-
\ No newline at end of file + public final List<> LIST = new ArrayList<>(); + public final Set<> SET = new HashSet<>(); + public final Map<> MAP = new HashMap<>(); + + private GoodUsageOfStaticCollections() { + } +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc b/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc index f0aed4f4f..188b8f648 100644 --- a/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC77/java/EC77.asciidoc @@ -1,67 +1,53 @@ -

- Avoid using Pattern.compile() in a non-static context. - This operation requires a significant amount of computational power, Using a single match saves CPU cycles and RAM consumption. -

+Avoid using `Pattern.compile()` in a non-static context. +This operation requires a significant amount of computational power, Using a single match saves CPU cycles and RAM consumption. -

Noncompliant Code Example

-
-
-    public class AvoidRegexPatternNotStatic {
-
-        public boolean foo() {
-            final Pattern pattern = Pattern.compile("foo"); // Noncompliant
-            return pattern.matcher("foo").find();
-        }
+## Noncompliant Code Example
 
+```java
+public class AvoidRegexPatternNotStatic {
+    public boolean foo() {
+        final Pattern pattern = Pattern.compile("foo"); // Noncompliant
+        return pattern.matcher("foo").find();
     }
+}
+```
 
-
- -

Compliant Solution N°1

-
-
-    public class ValidRegexPattern {
+## Compliant Solution N°1
 
-        private static final Pattern pattern = Pattern.compile("foo"); // Compliant
-
-        public boolean foo() {
-            return pattern.matcher("foo").find();
-        }
+```java
+public class ValidRegexPattern {
+    private static final Pattern pattern = Pattern.compile("foo"); // Compliant
 
+    public boolean foo() {
+        return pattern.matcher("foo").find();
     }
+}
+```
 
-
- -

Compliant Solution N°2

-
-
-    public class ValidRegexPattern2 {
+## Compliant Solution N°2
 
-        private final Pattern pattern = Pattern.compile("foo"); // Compliant
-
-        public boolean foo() {
-            return pattern.matcher("foo").find();
-        }
+```java
+public class ValidRegexPattern2 {
+    private final Pattern pattern = Pattern.compile("foo"); // Compliant
 
+    public boolean foo() {
+        return pattern.matcher("foo").find();
     }
+}
+```
 
-
- -

Compliant Solution N°3

-
-
-    public class ValidRegexPattern3 {
+## Compliant Solution N°3
 
-        private final Pattern pattern;
-
-        public ValidRegexPattern3() {
-            pattern = Pattern.compile("foo"); // Compliant
-        }
-
-        public boolean foo() {
-            return pattern.matcher("foo").find();
-        }
+```java
+public class ValidRegexPattern3 {
+    private final Pattern pattern;
 
+    public ValidRegexPattern3() {
+        pattern = Pattern.compile("foo"); // Compliant
     }
 
-
+ public boolean foo() { + return pattern.matcher("foo").find(); + } +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC78/java/EC78.asciidoc b/ecocode-rules-specifications/src/main/rules/EC78/java/EC78.asciidoc index 2b0c687b0..3153a8742 100644 --- a/ecocode-rules-specifications/src/main/rules/EC78/java/EC78.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC78/java/EC78.asciidoc @@ -1,30 +1,34 @@ -

Don't set const parameter in batch update => Put its in query. Creating this parameter and destroying it consumes CPU cycles and RAM unnecessarily.

-

Noncompliant Code Example

-
-    public void foo() {
-    	...
-    	String query = "insert into mytable values(?,?,?)";
-        ...
-        for(DummyClass o : list) {
-			stmt.setInt(1, 123);  // Noncompliant
-			stmt.setString(2, o.getName());
-			stmt.setDouble(3, o.getPrice());
-			stmt.addBatch();
-		}
-        ...
+Don't set a constant parameter in batch update. Instead, put it in query. Creating this parameter and destroying it consumes CPU cycles and RAM unnecessarily.
+
+## Noncompliant Code Example
+
+```java
+public void foo() {
+    // ...
+    String query = "insert into mytable values(?,?,?)";
+    // ...
+    for(DummyClass o : list) {
+        stmt.setInt(1, 123);  // Noncompliant
+        stmt.setString(2, o.getName());
+        stmt.setDouble(3, o.getPrice());
+        stmt.addBatch();
     }
-
-

Compliant Solution

-
-    public void foo() {
-    	...
-    	String query = "insert into mytable values(123,?,?)";
-        ...
-        for(DummyClass o : list) {
-			stmt.setString(1, o.getName());
-			stmt.setDouble(2, o.getPrice());
-			stmt.addBatch();
-		}
-        ...
+    // ...
+}
+```
+
+## Compliant Solution
+
+```java
+public void foo() {
+    // ...
+    String query = "insert into mytable values(123,?,?)";
+    // ...
+    for(DummyClass o : list) {
+        stmt.setString(1, o.getName());
+        stmt.setDouble(2, o.getPrice());
+        stmt.addBatch();
     }
-
+ // ... +} +``` diff --git a/ecocode-rules-specifications/src/main/rules/EC79/java/EC79.asciidoc b/ecocode-rules-specifications/src/main/rules/EC79/java/EC79.asciidoc index f8801ef21..ef8bc2156 100644 --- a/ecocode-rules-specifications/src/main/rules/EC79/java/EC79.asciidoc +++ b/ecocode-rules-specifications/src/main/rules/EC79/java/EC79.asciidoc @@ -1,24 +1,28 @@ -

try-with-resources Statement needs to be implemented for any object that implements the AutoCloseable interface, it save computer resources.

-

Noncompliant Code Example

-
-    private static void printFileJava7() throws IOException {
-        FileInputStream input = new FileInputStream("file.txt");
+Use `try-with-resources` statement for any object that implements the `AutoCloseable` interface, it save computer resources.
+
+## Noncompliant Code Example
+
+```java
+private static void printFileJava7() throws IOException {
+    FileInputStream input = new FileInputStream("file.txt");
+    int data = input.read();
+    while(data != -1){
+        System.out.print((char) data);
+        data = input.read();
+    }
+}
+```
+
+## Compliant Solution
+
+```java
+private static void printFileJava7() throws IOException {
+    try(FileInputStream input = new FileInputStream("file.txt")) {
         int data = input.read();
         while(data != -1){
             System.out.print((char) data);
             data = input.read();
         }
     }
-
-

Compliant Solution

-
-    private static void printFileJava7() throws IOException {
-        try(FileInputStream input = new FileInputStream("file.txt")) {
-            int data = input.read();
-            while(data != -1){
-                System.out.print((char) data);
-                data = input.read();
-            }
-        }
-    }
-
+} +``` diff --git a/ecocode-rules-specifications/src/main/rules/etsdiff-methodology.asciidoc b/ecocode-rules-specifications/src/main/rules/etsdiff-methodology.asciidoc new file mode 100644 index 000000000..3239fa7d4 --- /dev/null +++ b/ecocode-rules-specifications/src/main/rules/etsdiff-methodology.asciidoc @@ -0,0 +1,11 @@ +## The three sources of impacts of a code identified are: + +- Energy: measured in joules (J) +- Transfer: measured in Bytes (B) +- Storage: measured in Bytes (B) + +The control of these 3 impacts allows to lengthen the life of the terminals as well as reduce their energy consumption. + +The _ETSdiff_ tool allows measuring a differential on these three values and in a given context (database and fixed measurement environment). + +The results generated by _ETSdiff_ must help define the interest of the rule reported by _SonarQube_ in the context of the code analyzed.