Sobes.tech
Junior

Have you ever worked with legacy code?

sobes.tech AI

Answer from AI

Yes, I have had to work with legacy code, including code written in PHP 5.x and even earlier versions.

Working with legacy code involves:

  • Understanding the structure and logic of the application, often without up-to-date documentation.
  • Identifying and fixing bugs and vulnerabilities.
  • Refactoring code sections to improve readability, maintainability, and performance.
  • Gradually updating outdated functions and approaches in accordance with modern PHP standards and best development practices.
  • Adding tests to ensure stability when making changes.
  • Carefully implementing new features, minimizing the risk of disrupting existing functionality.

Typical tasks include:

  • Fixing critical bugs in production.
  • Adding small features or modifying existing functionality.
  • Large-scale refactoring or rewriting modules.
  • Updating PHP versions and used libraries.

An example of refactoring outdated code:

Suppose there is a function using the deprecated mysql_* extension:

<?php
// Deprecated code
function getUserDataLegacy($userId) {
    $link = mysql_connect('localhost', 'myuser', 'mypass');
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    mysql_select_db('mydatabase', $link);
    $query = "SELECT * FROM users WHERE id = " . (int)$userId;
    $result = mysql_query($query, $link);
    if (!$result) {
        die('Invalid query: ' . mysql_error());
    }
    $data = mysql_fetch_assoc($result);
    mysql_close($link);
    return $data;
}

Refactoring using mysqli:

<?php
// Refactoring using mysqli
function getUserDataRefactored($userId) {
    $mysqli = new mysqli('localhost', 'myuser', 'mypass', 'mydatabase');
    if ($mysqli->connect_error) {
        die('Could not connect: ' . $mysqli->connect_error);
    }
    // Using prepared statements to prevent SQL injection
    $stmt = $mysqli->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->bind_param('i', $userId);
    $stmt->execute();
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();
    $mysqli->close();
    return $data;
}

It is important to approach working with legacy code cautiously, paying attention to testing and gradual changes.

Have you ever worked with legacy code? — PHP - sobes.tech