
Programming is a complex creative activity that we at ESSE I like to call an art. And in every art there are tricks and techniques that not everyone knows or uses to make their work more efficient, elegant, high-performing or simply better.
Coding is no exception, and here we are talking about methods which, used shrewdly, reveal programming experience.
Of course, being an expert programmer is not just about knowledge, but also about building and maintaining "lateral" thinking that leads to solving certain problems in new and original ways. Above all, it is about having an overall view of what you are doing, how you are doing it and, in particular, why you are doing it.
However, we believe that knowing certain coding tricks can help build and apply that experience. And, why not, speed up work without losing effectiveness in solving individual problems.
With this in mind, in today's article for our monthly coding column "comprESSE I", we will explore seven lesser-known programming tricks that could make a difference when writing code.
To illustrate them we will use some of the most popular languages, such as JavaScript, Python and C; bear in mind, though, that many of these tricks can also be translated into other languages. But we'll talk about that in the last point.
1) Use destructuring
Destructuring is a feature of some programming languages that lets you break down complex data structures such as objects or arrays into smaller parts. It is common especially in languages like JavaScript and Python.
Here is an example of destructuring a variable in JavaScript. The object is "person", and in this way we extract its firstName, lastName and age properties into separate variables:
const person = { firstName: 'Mario', lastName: 'Rossi', age: 30 };
const { firstName, lastName, age } = person;
console.log(firstName); // Output: Mario
console.log(lastName); // Output: Rossi
console.log(age); // Output: 30
In this other example, instead, we destructure the "numbers" array to extract the first two elements into separate variables (first and second). The remaining elements are collected in the "rest" array.
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4, 5]
Why use destructuring? Because it makes it easier to access and assign values within complex data.
2) Take advantage of lazy loading for images
Not all web developers are always aware of how important it is to make pages load as fast as possible, to improve the user experience and, consequently, send a "positive signal" to Google, which will take it into account in its search results.
Lazy loading of images is a very useful technique for this: it is used to delay loading non-essential images on a web page until the user gets close to seeing them. This can significantly improve page performance, reducing the initial load and speeding up loading time.
Not everyone knows that HTML5 supports lazy loading natively and very simply through the "loading" attribute of the "<img>" tag. Here the "lazy" option indicates lazy loading, delaying the loading of images.
<img loading="lazy" src="image.jpg" alt="Lazy-loaded Image">
For more control you can use JavaScript code, lazy loading libraries or the equally simple and, like the HTML version, lesser-known CSS version:
img {
loading: lazy;
}
3) Optimise SQL queries with JOIN
Not everyone knows that joining two or more database tables in SQL can improve query performance, a very important factor which, repeated across many client-server calls, can considerably reduce the load and therefore improve the overall performance of a web project.
Here is some sample SQL code (to be adapted to your own situation):
SELECT users.name, orders.product
FROM users
JOIN orders ON users.id = orders.user_id;
Using JOIN (also available as INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN) is essential when working with relational databases whose data is spread across several tables, because it lets you build relationships and retrieve related information efficiently.
4) Use XOR to swap variables
To swap the values of two variables, many programmers tend to use a temporary variable. A simple but not particularly efficient method. There is, however, the "bitwise XOR" swap, which we explain here with a simple piece of C code:
a = a ^ b;
b = a ^ b;
a = a ^ b;
But how exactly does it work?
XOR is a "bitwise" logical operation that performs an exclusive comparison between the corresponding bits of two operands, returning 1 for each pair of different bits and 0 for each pair of equal bits.
- a = a ^ b; performs XOR between the values of "a" and "b" and assigns the result to "a". After this line, "a" contains the result of XOR between the original value of "a" and the original value of "b".
- b = a ^ b; performs XOR between the new value of "a" (from the previous line) and the original value of "b" and assigns the result to "b". After this line, "b" contains the result of XOR between the new value of "a" and the original value of "b", which is in fact the original value of "a".
- a = a ^ b; finally performs XOR between the new value of "a" (from the first line) and the new value of "b" (from the second line) and assigns the result to "a". After this line, "a" contains the result of XOR between the new "a" and the new "b", which is in fact the original value of "b".
5) Optimise matching with regular expressions
When programming you often need to perform "matching", a technique that consists of finding a piece of text within another, usually longer, piece of text (the "string") so that it satisfies the "pattern" (the rule specified in the regular expression).
A trick not everyone knows, shown here in JavaScript, is to use a "non-capturing" group ("?:" followed by the pattern) when you have groups in a regular expression and do not need to capture the match. Here is an example with the two approaches.
// Without non-capturing
/(\d+)-(\d+)/
// With non-capturing
/(?:\d+)-(\d+)/
In the first approach, using capturing groups means that the match result will include both the digits before the hyphen and those after it. For example, applying this regular expression to the string "123-456" gives two capturing groups: "123" (group 1) and "456" (group 2).
In the second approach, the digits before the hyphen are not included in the capturing groups. Using "?:" makes the group non-capturing, which means it will NOT be included in the match result. So if you apply this regular expression to the string "123-456", you will get only one capturing group, "456" (group 1).
Using a non-capturing group lets you specify a block of pattern without including it in the capturing groups of the match result, making the process of extracting information from the string more flexible and clear.
6) Use the "ternary operator" in assignments
Take for example the following line of Python code:
result = "Even" if num % 2 == 0 else "Odd"
We wanted to add this conditional expression (or "ternary conditional expression") to our list because it lets you write a conditional statement concisely and directly (thanks to the built-in assignment) on a single line. A technique we find useful when you want to keep code concise and readable.
But be careful: it is best to use this form responsibly and only when it makes the code clearer and easier to understand, especially when the conditional logic is simple. In some situations, particularly when the logic is complex, a multi-line if-else statement may be preferable for readability. We talked about code readability and its importance, and how it may clash with tricks like this one, in this earlier article.
7) Translate code with generative AI
We must admit that generative AI, with tools such as OpenAI ChatGPT or the even more specific GitHub Copilot, is now a great help for programmers. Often a simple prompt is enough to get working, well-documented scripts that perform the requested task effectively. AI proved very useful in writing this very article.
However, don't think it is enough: software, unlike a single script, is something extremely complex that requires competent overall control and supervision, and experience that a machine cannot have. But AI is useful when you need to carry out individual mechanical and specific operations or, and this is why we present it as a "trick" you may never have thought of, when you need to translate code from one language to another.
To document this trick we asked ChatGPT to translate a script from VBScript to PHP. And the best part is that we didn't even have to write the original code ourselves, since that too was generated by the AI.
We started from the following prompt: "Write VBScript/ASP code that connects to a database, reads a specific record based on the query string and displays it".
This is the answer we got:
<%@ Language=VBScript %>
<% Option Explicit %>
<% Response.Buffer = True %>
<%
' Database connection
Dim connStr
connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("YourDatabase.mdb")
Dim conn
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open connStr
' Read the parameter from the query string
Dim userID
userID = Request.QueryString("ID")
' Run the query to get the specific record
Dim sql
sql = "SELECT * FROM YourTable WHERE ID = " & userID
Dim rs
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open sql, conn
' Check whether there are results
If Not rs.EOF Then
' Display the data
Response.Write("<p>ID: " & rs("ID") & "</p>")
Response.Write("<p>First name: " & rs("FirstName") & "</p>")
Response.Write("<p>Last name: " & rs("LastName") & "</p>")
Else
' Message if there are no results
Response.Write("<p>No results found.</p>")
End If
' Close the connection and the recordset
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing
%>
Then we typed: "Rewrite this code in PHP". Here is the result:
<?php
// Database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "YourDatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check the database connection
if ($conn->connect_error) {
die("Database connection failed: " . $conn->connect_error);
}
// Read the parameter from the query string
$userID = $_GET["ID"];
// Run the query to get the specific record
$sql = "SELECT * FROM YourTable WHERE ID = " . $userID;
$result = $conn->query($sql);
// Check whether there are results
if ($result->num_rows > 0) {
// Display the data
while ($row = $result->fetch_assoc()) {
echo "<p>ID: " . $row["ID"] . "</p>";
echo "<p>First name: " . $row["FirstName"] . "</p>";
echo "<p>Last name: " . $row["LastName"] . "</p>";
}
} else {
// Message if there are no results
echo "<p>No results found.</p>";
}
// Close the connection
$conn->close();
?>
As you can see, both the code created from scratch and its translation are correct, working scripts (of course to be adapted to your own "situation": for example, the database you connect to must exist and be configured properly), proof that AI can be useful in this field too.
It also shows that, by asking the right questions, the other tricks we have suggested can (though not always) be translated into other languages.
Even though we have finished our round-up of seven coding tricks, please don't stop reading, because what we want to stress in closing is very important.
In conclusion
Many readers will already know the "power" of generative AI and its application in coding. It is a revolution that has been under way for some time and cannot be ignored, and indeed we don't ignore it. Not least because we don't fear it: we are not afraid AI will steal our jobs; we don't believe such nonsense.
As we said at the beginning, the art of coding does not lie in tricks but in a design vision that only humans can provide. We certainly believe that generative AI is a convenience that speeds up and simplifies work, and that knowing certain programming tricks, including those involving the (conscious) use of AI, can help a programmer mature. And help them learn, too.
In short, writing code with AI or having it translated is, in our view, a useful trick, just like knowing and applying all seven tricks presented in this article.
But, and we will repeat it ad nauseam, let's always do it with the greatest care.
Because building a real software project, applying the authentic creativity that distinguishes "the art of programming", is another matter altogether.



