We have mentioned on a few occasions how important it is to keep the quality of source code high. It is not just a matter of pride or of showing off how elegant a developer's style can be. It is a real, practical skill that makes software easier to develop and extend later, and easier for new developers (or experienced ones coming back after a long break) to find their way around. It also lets you track down the source of bugs and fix them faster. All of this makes programming more enjoyable, and that in turn raises the quality of the software itself from a functional point of view. A happy developer means good software.

The problem is that writing clean code is hard, even for good developers, and it has nothing to do with skills or knowledge alone. There is no denying that crafting the well-groomed lines that make up an application also takes time, a chance to think calmly about the class structure, to design everything up front (if not on paper, then at least in your head), and so on. What is more, software engineering and common sense clearly say that you should aim for the highest possible code quality, but in practice and in business there are situations where perfection is not always desirable. Still, it is worth striving for it "naturally". That is a challenge and takes experience, many attempts and quite a few failures.

This is where programming gets the concept of refactoring, which we will take on in today's text. We will find out what it is, what it gives you, what side effects it has, whether it should always be applied, and, most importantly, we will walk through an extensive example, step by step, to see why this operation should not be done carelessly. Precisely because of the code listings, this text may be rather long. I am warning you honestly, in case you want to split the reading into parts or make some tea first.

What is refactoring?

Refactoring is changing the organization of source code without changing its functionality. It does not add features to an application or take them away. It is a transformation of the code (or rather a series of transformations) that makes the structure of the program better, clearer and easier to extend. Of course, along the way we may discover potential problems and fix them, but the goals of refactoring concern the upkeep of the source code, not how the software behaves. The process is not about optimization either, although again, along the way a developer may shorten the code and remove unnecessary fragments that slow it down.

Refactoring is a process made up of a series of code transformations. These are various operations that, often with support from the IDE, eventually make the program look clearer. It sounds very mathematical, but the truth is that many of these steps are quite intuitive and come from every developer's experience. Examples include:

  • extracting a method or a class,
  • moving a method, class or field,
  • renaming a method, class or field,
  • adding, removing or changing method parameters,
  • moving a method or field to a base class or a subclass,
  • removing an element from the code,
  • hiding a method

and many more. There are studies that cover the topic in more detail, such as this article by researchers from the Faculty of Computing at Poznań University of Technology.

Benefits of refactoring

We have already listed them indirectly. With refactoring you can achieve:

  • clearer code, and therefore a new person finds their way around it faster,
  • code that is easier to extend with new features, which spares you the later despair of maintaining so-called spaghetti code,
  • shorter code. This is not always possible, but often after the changes it turns out that many operations in the system were duplicated and you can create one method that groups them,
  • a better division of responsibilities in the code, so it is easier to find the place that handles a given feature,
  • removal of unused code,
  • more enthusiasm for further work, because cleaned-up code refreshes developers' minds and motivates them,
  • a better understanding of how the code works,
  • to sum up many of the points above: getting rid of code smells.

As you can see, refactoring is generally a positive thing and helps keep the code in good shape over the long term. It is a bit like taking care of a car. It can keep running as it is, but if we look after certain parts, the vehicle will run trouble-free for more years rather than fewer. However, as we know, there is no rose without thorns, so this process also comes with some less positive effects.

Side effects of refactoring

First of all, refactoring takes time and seemingly does not move the project forward. It is the programmer's version of "taking one step back to take several steps forward", and most people will rightly point out that these are not drawbacks if they lead to savings in the long run. Unfortunately, that is how it works in an ideal world, and in the business world it does not always hold. Clients want to see results and further features, and they are not eager to pay for fixes, especially for something that works. After all, if developers know how to correct it, they should have written it well from the start, right?

And this is where we come to the fact that even the most experienced coders are not always able to imagine the best structure from the beginning and implement it. There are plenty of reasons, but most often it comes down to a lack of time (caused, for example, by the need to release a prototype quickly, which later turns out to be permanent), a lack of initial knowledge about everything the software can do (you cannot always write flexible code right away), or differing levels of experience among the people doing the work.

That is exactly why refactoring was invented. If everyone wrote perfect code from the start, no process of reorganizing code would be needed. We need to accept this and build it into the software development process, for example by splitting it into smaller parts. A so-called "big refactoring" (reorganizing the entire code of the software) almost never ends well, and it usually ends with rewriting the system from scratch, which is expensive and stressful. It is better to follow agile methods and refactor smaller pieces of code, but more often. That way there are fewer changes at any one moment and they are easier to carry out.

There is also no denying that, while the result of refactoring is a feeling of clean code and, with it, happy developers and a tidy project, the process itself can be tedious and thankless. For this reason the IT team does not like it and sometimes puts it off, which creates problems. It also happens that work on new features goes on all the time and it is hard to find a convenient moment to stop implementing new requirements and focus on modifying the existing code. Finally, it is worth mentioning that refactoring is simply difficult. It takes solid knowledge of software engineering and a target "vision" of the IT system. That is another demotivating factor that sometimes pushes these modifications to the back burner.

So that I am not misunderstood: refactoring is necessary and should be included in the project tasks. The problem is that it is hard to justify to laypeople in business terms, and there is too strong a temptation to skip it and thereby allow a disaster in the longer term. So it has to be done sensibly.

Do you always have to refactor all the way?

We already know that refactoring is needed. It will never be possible to plan and write all the code perfectly from beginning to end, and sometimes even small fragments have to be modified to make further development easier or simply possible. These do not always have to be big changes. Sometimes even gentle corrections make the code much better.

We should also dispel a second doubt: do you always have to refactor the code all the way and clean it up 100%? Here the answer may differ depending on the person and the field they work in. From a business point of view it is not always possible, feasible or profitable. There is a reason for the saying "the better is the enemy of the good". A significant improvement in code quality may be possible after applying just 20% of the proposed changes, while the remaining 80% would make the code perfect but take so much time that it is better to let it go, because it becomes unprofitable. These are always hard decisions, and the perfectionists who accept nothing but the ideal may be right. It is just that reaching the ideal is possible with an enormous budget, which software houses rarely get in their projects. Imagine paying a mechanic to put a new engine in your car, and he gives you a big quote, explaining that when he gets the machinery dirty, he has to take it apart and clean it from the inside so that it shines.

That is why it is not at all wrong to aim for code that is "good enough", meaning code you can already like but that is not yet ideal. Remember that refactoring can be an iterative process, and it is quite possible to come back to some places later and improve their readability further.

How to refactor and what to pay attention to

The first and most basic point is that refactoring must not change the functionality of the program. This means it is unacceptable for the process to introduce new bugs into the application or to change the way it works from the user's point of view (unless for the better). That is why refactoring should:

  • be careful,
  • be carried out step by step (that is, you need to verify correctness after each transformation).

For this reason developers often support it with automated tests, and it is also a good opportunity to write them. That is not the topic of this text and we will not go into it now, but it is worth noting that this way of verifying greatly helps refactoring (and more), although it has its own consequences too.

The question remains what to look for when analyzing code that we intend to refactor. Often, during reviews, you can see at a glance that the code is ugly, but it is not always clear how exactly to fix it. That is why it is worth checking it for:

  • doing similar things in several places (although in theory this is not always undesirable),
  • the parameters and return values of functions,
  • conditional statements that are long, complicated or repeated often,
  • the length of classes and methods,
  • cues that may cause the purpose of the code to be misunderstood,
  • closed conditions that make it hard to add, for example, a new subtype of a given object,
  • methods or fields assigned to the wrong classes, and frequent references from one class to another,
  • hand-written functions that duplicate part of the standard library,
  • compliance with the standard that applies in the team.

This is not a complete list, but it is a good starting point. As you can see, many of these points are really the code smells mentioned above, and the topic is indeed closely tied to refactoring. In addition, as they gain experience, developers may notice other problems that will need changes, also with the system's upcoming development or new features in mind.

A step-by-step refactoring example

Let us move on to the example we have already mentioned. Refactoring is a subject of research for software engineering scientists, yet it is above all a practical skill that lets developers improve the quality of the code and, with it, the whole software. So it is worth following what bringing a program into a clearer form can actually look like.

As I write these words, the FIFA World Cup (colloquially just the "World Cup") is taking place, and as we know, it has a group stage and a knockout stage. We are interested in the first of these, in which four teams play each other in a round-robin system and two of them advance to the next stage. As you can easily guess, the two teams that perform best, that is, score the most points (3 for a win, 1 for a draw), get through. However, every football fan (and not only) knows that over the course of the group matches it is quite common for several teams to end up with the same number of points, and then the further advancement criteria start to matter. This adds excitement, but also trouble for people who want to actively follow the teams' chances of getting out of the group. Clearly, some kind of application would come in handy here, right?

And it is precisely a program that determines the order of teams in a group based on results that will be the subject of our interest. For the purposes of this text we have prepared a simple script in PHP that reads the match results in JSON format and shows the final order. And that order is fairly complicated, described both in the official regulations and on sports websites. In short, the criteria for ranking the teams are as follows:

  1. Number of points earned.
  2. Goal difference (goals scored minus goals conceded).
  3. Number of goals scored.
  4. Points earned in head-to-head matches. It may be worth explaining here what the so-called mini-table is: if the situation between teams (most often two, but there can be more) is unresolved, only the matches between those teams are taken into account. In short, in this situation the team that won the direct encounter has the advantage.
  5. Goal difference in head-to-head matches.
  6. Goals scored in head-to-head matches.
  7. Fair play ranking: the fewer cards a team receives, the better.

As you can see, this can get quite involved, which is why the matches in the third round of the group stage (which are played simultaneously) are so exciting. One of the groups in 2022 where the question of advancement was not settled until the last minutes (at one point even the fair play ranking turned out to matter) was Group C, in which Poland played with Argentina, Mexico and Saudi Arabia. The matches between these nations will be the test set for our script. Of course, it will also work for other groups and tournaments with identical rules, but Group C will be our verification case. The actual final order was as follows:

  1. Argentina: 6 points, goals 5-2, -2 fair play points
  2. Poland: 4 pts, goals 2-2, -5
  3. Mexico: 4 pts, goals 2-3, -7
  4. Saudi Arabia: 3 pts, goals 3-5, -14

The plan was this. First, we wrote a script that gave good results (although it contained one bug, more on that later) but was "ugly" and you could tell not much time had gone into it. Then it was refactored step by step, so as not only to improve the quality of the code but also to show the programmer's successive decisions and transformations. You can see all of it in the repository on our GitHub profile. The first commit contains the original, "unclean" script, and the later ones contain the subsequent changes, which we will discuss step by step. You can find the list here, and when analyzing it you should browse it from the bottom up (from the oldest to the newest).

The original script

At first the program looked like this:

$matchesFile = $argv[1];
$matches = json_decode(file_get_contents($matchesFile), true);

$teams = sumResults();
$order = calculateOrder($teams);

$i = 1;
foreach($order as $idx) {
	$team = $teams[$idx];
	
	$name = $team['name'];
	$points = $team['points'];
	$scoredGoals = $team['scoredGoals'];
	$concededGoals = $team['concededGoals'];
	$fairPlay = $team['fairPlay'];
	
	echo ($i++).". $name - $points pkt., $scoredGoals-$concededGoals ($fairPlay)\n";
}

function sumResults($obligatorySymbols = []) {
	global $matches;

	$teams = [];
	foreach($matches as $match) {
		$a = $match['teamA'];
		$b = $match['teamB'];

		if(!empty($obligatorySymbols) && (!in_array($a['symbol'], $obligatorySymbols) || !in_array($b['symbol'], $obligatorySymbols))) {
			continue;
		}
		
		if(!array_key_exists($a['symbol'], $teams)) {
			$teams[$a['symbol']] = ['name' => $a['symbol'], 'points' => 0, 'scoredGoals' => 0, 'concededGoals' => 0, 'goalsBalance' => 0, 'fairPlay' => 0];
		}
		if(!array_key_exists($b['symbol'], $teams)) {
			$teams[$b['symbol']] = ['name' => $b['symbol'], 'points' => 0,'scoredGoals' => 0, 'concededGoals' => 0, 'goalsBalance' => 0, 'fairPlay' => 0];
		}
		
		if($a['goals'] > $b['goals']) {
			$teams[$a['symbol']]['points'] += 3;
		}
		elseif($a['goals'] == $b['goals']) {
			$teams[$a['symbol']]['points']++;
			$teams[$b['symbol']]['points']++;
		}
		else {
			$teams[$b['symbol']]['points'] += 3;
		}
		
		$teams[$a['symbol']]['scoredGoals'] += $a['goals'];
		$teams[$a['symbol']]['concededGoals'] += $b['goals'];
		$teams[$b['symbol']]['scoredGoals'] += $b['goals'];
		$teams[$b['symbol']]['concededGoals'] += $a['goals'];
		
		$teams[$a['symbol']]['goalsBalance'] = $teams[$a['symbol']]['scoredGoals'] - $teams[$a['symbol']]['concededGoals'];
		$teams[$b['symbol']]['goalsBalance'] = $teams[$b['symbol']]['scoredGoals'] - $teams[$b['symbol']]['concededGoals'];
		
		$teams[$a['symbol']]['fairPlay'] += ($a['yellowCards'] * -1) + ($a['doubleYellowCards'] * -3) + ($a['directRedCards'] * -4) + ($a['directYellowAndRedCards'] * -5);
		$teams[$b['symbol']]['fairPlay'] += ($b['yellowCards'] * -1) + ($b['doubleYellowCards'] * -3) + ($b['directRedCards'] * -4) + ($b['directYellowAndRedCards'] * -5);
	}

	return $teams;
}

function calculateOrder($teams, $verifyFairPlay = false) {
	$order = array_keys($teams);
	$smallTables = [];

	for($i = 0; $i < count($order) - 1; ++$i) {
		for($j = $i + 1; $j < count($order); ++$j) {
			if($i == $j) continue;
			
			$team1 = $teams[$order[$i]];
			$team2 = $teams[$order[$j]];
			
			if($team2['points'] > $team1['points']) {
				swapOrder($order, $i, $j);
			}
			elseif($team2['points'] == $team1['points']) {
				if($team2['goalsBalance'] > $team1['goalsBalance']) {
					swapOrder($order, $i, $j);
				}
				elseif($team2['goalsBalance'] == $team1['goalsBalance']) {
					if($team2['scoredGoals'] > $team1['scoredGoals']) {
						swapOrder($order, $i, $j);
					}
					elseif($team2['scoredGoals'] == $team1['scoredGoals']) {
						if($verifyFairPlay) {
							if($team2['fairPlay'] > $team1['fairPlay']) {
								swapOrder($order, $i, $j);
							}
						}
						else {
							$hash = md5($team2['points'].$team2['goalsBalance'].$team2['scoredGoals']);
							if(!array_key_exists($hash, $smallTables)) {
								$smallTables[$hash] = [];
							}
							
							$smallTables[$hash][] = $team1['name'];
							$smallTables[$hash][] = $team2['name'];
						}
					}
				}
			}
		}
	}
	
	if(!empty($smallTables)) {
		foreach($smallTables as $hash => $table) {
			$subTeams = sumResults($table);
			$newOrder = calculateOrder($subTeams, true);
			$smallTables[$hash] = $newOrder;
		}
	}
	
	$result = [];
	$visitedTeams = [];
	for($i = 0; $i < count($order); ++$i) {
		if(in_array($order[$i], $visitedTeams)) continue;
		
		$smallTableIncludingThisTeam = null;
		foreach($smallTables as $smallTable) {
			if(in_array($order[$i], $smallTable)) {
				$smallTableIncludingThisTeam = $smallTable;
				break;
			}
		}
		
		if(!empty($smallTableIncludingThisTeam)) {
			foreach($smallTableIncludingThisTeam as $team) {
				if(in_array($team, $visitedTeams)) continue;
				
				$result[] = $team;
				$visitedTeams[] = $team;
			}
		}
		else {
			$result[] = $order[$i];
			$visitedTeams[] = $order[$i];
		}
	}
	
	return $result;
}

function swapOrder(&$array, $i, $j) {
	list($array[$i], $array[$j]) = [$array[$j], $array[$i]];
}

It is worth explaining first how this code works. It takes as a parameter a JSON file with the matches to load, and then, based on it, it adds up all the results and goals and determines the fair play score. This produces an array of teams (in this case with 4 elements) with their results. Then the algorithm determines the order, that is, it sorts our teams according to the criteria presented above. Along the way it may turn out that some teams have to be checked against head-to-head matches in a mini-table, which means loading only some of the matches again (remember that a mini-table can theoretically include more than two teams) and recalculating its order. Then, with the order from the big table and the mini-tables, the team symbols are returned one by one. Finally, the result is printed.

As I mentioned before, this code produces the correct result (apart from one bug that will show up later). Still, at a glance it is clear that it is not something we would like to show off. It is not even the lack of object orientation, because although we will move toward it, it is not always needed. What you can see here is that the code is simply too long and convoluted, relies heavily on associative arrays and hand-typed fields (which can lead to mistakes), and the part that swaps the order of teams depending on conditions may be not only hard to understand but even give you nightmares. We will modify all of this. It is also worth showing what a sample input file in JSON format looks like.

[
	{
		"teamA": {
			"symbol": "ARG",
			"goals": 1,
			"yellowCards": 0,
			"doubleYellowCards": 0,
			"directRedCards": 0,
			"directYellowAndRedCards": 0
		},
		"teamB": {
			"symbol": "SA",
			"goals": 2,
			"yellowCards": 6,
			"doubleYellowCards": 0,
			"directRedCards": 0,
			"directYellowAndRedCards": 0
		}
	},
	{
		"teamA": {
			"symbol": "MEX",
			"goals": 0,
			"yellowCards": 2,
			"doubleYellowCards": 0,
			"directRedCards": 0,
			"directYellowAndRedCards": 0
		},
		"teamB": {
			"symbol": "POL",
			"goals": 0,
			"yellowCards": 1,
			"doubleYellowCards": 0,
			"directRedCards": 0,
			"directYellowAndRedCards": 0
		}
	},
	{
		"teamA": {
			"symbol": "POL",
			"goals": 2,
			"yellowCards": 3,
			"doubleYellowCards": 0,
			"directRedCards": 0,
			"directYellowAndRedCards": 0
		},
		"teamB": {
			"symbol": "SA",
			"goals": 0,
			"yellowCards": 2,
			"doubleYellowCards": 0,
			"directRedCards": 0,
			"directYellowAndRedCards": 0
		}
	},
	{
		"teamA": {
			"symbol": "ARG",
			"goals": 2,
			"yellowCards": 1,
			"doubleYellowCards": 0,
			"directRedCards": 0,
			"directYellowAndRedCards": 0
		},
		"teamB": {
			"symbol": "MEX",
			"goals": 0,
			"yellowCards": 4,
			"doubleYellowCards": 0,
			"directRedCards": 0,
			"directYellowAndRedCards": 0
		}
	},
	{
		"teamA": {
			"symbol": "SA",
			"goals": 1,
			"yellowCards": 6,
			"doubleYellowCards": 0,
			"directRedCards": 0,
			"directYellowAndRedCards": 0
		},
		"teamB": {
			"symbol": "MEX",
			"goals": 2,
			"yellowCards": 1,
			"doubleYellowCards": 0,
			"directRedCards": 0,
			"directYellowAndRedCards": 0
		}
	},
	{
		"teamA": {
			"symbol": "POL",
			"goals": 0,
			"yellowCards": 1,
			"doubleYellowCards": 0,
			"directRedCards": 0,
			"directYellowAndRedCards": 0
		},
		"teamB": {
			"symbol": "ARG",
			"goals": 2,
			"yellowCards": 1,
			"doubleYellowCards": 0,
			"directRedCards": 0,
			"directYellowAndRedCards": 0
		}
	}
]

A small note: you may rightly notice that although Poland and Mexico have the same number of points, their goal difference is different, which means the case of this group may not be as attractive to calculate as it might seem at first. That is why, when testing, it is worth temporarily making small modifications to the results to verify other cases as well:

  • changing the result of the Saudi Arabia vs. Mexico match from 1-2 to 0-2 gives Mexico and Poland an identical goal difference and number of goals scored, and since the match between these two teams ended 0-0, you can test the fair play ranking calculation,
  • changing the result of the same match from 1-2 to 1-3 puts Mexico ahead of Poland, because despite the identical goal difference, Mexico has scored more goals,
  • if we give Poland a few yellow cards and set the Saudi Arabia vs. Mexico result to 0-2, Mexico will also finish ahead of Poland.

Running the script comes down to a simple console command: php index.php matches.json.

We will now carry out the refactoring transformations one after another. They will make the code visually shorter (that is, a single file will not be as long, or it will be logically split), clearer, leave less room for mistakes by the programmer, and prepare it for further development. Let us begin.

Step 1: introducing object orientation (OOP)

As I mentioned, object orientation is not required for code to count as clean. What is more, with short source code it does not make much sense (unless the programming language itself requires it). It does, however, let you separate shared bundles of data and bring the structure closer to logical reasoning when imagining the next operations. There is also no denying that, used properly, it can simplify the thought process of someone who is just getting to know the application from the inside.

In our case there is one more reason to introduce object orientation. We keep talking about a script run from the console, but it is easy to imagine (especially since this is PHP) that a web application could be built on this code, returning the order of teams through an exposed API. The logic itself would be identical, but the way it is launched would be completely different. That is why we will move the code into a new Group class, from which the operations will be called and which could in the future create objects in a non-console application as well.

Commit with the changes in step 1: https://github.com/WildaSoftware/FootballGroupCalculator/commit/4e889922de4dd001584e3e255972cdd2bd51dca1

Step 2: introducing a team class (Team)

When we look at the sumResults method, we see heavy use of associative arrays, which are very easy to reach for in PHP. That also makes them very useful, but passing a key to get a specific value can cause errors from plain typos. Of course, you can handle this with constants, but the code is still long and very "wide". We are also not using one of the many advantages of code editors: suggesting the members of a class, which speeds up a specialist's work considerably. Add to that the fact that with somewhat larger code it is really easy to lose track of which fields each team has, and we decide to introduce a Team class that will organize this for us and later let us "adopt" some of the methods.

In the transformation below we see that we managed not only to clean up the code in sumResults a bit, but also to shorten printResults. Along the way, we can see that you do not have to declare all the attributes of a class as standard fields, especially if there are many of them. If we follow the principles of object-oriented encapsulation, the Team class would suddenly become very long just because of setters and getters. The alternative is to give up encapsulation, make all the fields public and access them directly, but then the programmer loses full control over when a given value changes. Fortunately, PHP provides a set of magic methods, among them __set and __get, which cover all the fields of a class. True, we lose autocompletion this way, but that can be "fixed" with special comments above the class definition.

class Team {

    private $attributes = [];

    public function __construct(string $symbol) {
        $this->symbol = $symbol;
    }

    public function __set($name, $value) {
        if(!in_array($name, ['symbol', 'points', 'scoredGoals', 'concededGoals', 'goalsBalance', 'fairPlay'])) {
            throw new \Exception("There is no \"$name\" attribute to set in Team");
        }

        $this->attributes[$name] = $value;
    }

    public function __get($name) {
        return $this->attributes[$name] ?? null;
    }
}

This way you can call $team->points = 3 or $goals = $team->scoredGoals without explicitly defining and using "set" or "get" methods. A similar mechanism works in C#, where you can protect a class from an attempt to reach the wrong field, but here too we can do that by listing the permitted attributes. Most importantly, we have extracted the team class, which lets us group the related elements better and take load off other parts of the program.

Commit with the changes in step 2: https://github.com/WildaSoftware/FootballGroupCalculator/commit/f73779ab223a328a6c07938ae4eece1d2df98104

Step 3: a DTO object, better naming conventions in sumResults and extracting the fair play calculation

When loading the JSON from the file, we did it "by hand", that is, without fully controlling which fields we read and can use later. Here we again used associative arrays, so it is a good moment to turn to object orientation. For this we create the MatchDTO and TeamDTO classes. True, they are in one file, but let us say that this is exactly the kind of harmless departure from perfection that speeds up the whole process a bit in return. DTO classes in general stand for Data Transfer Object and, as the name says, they are used to carry data. It is in MatchDTO that the results of a given match will be loaded and stored for later use. We also change name to symbol, matching the convention in the JSON file, but that is just a detail.

Back to sumResults, where of course we use the new "invention". We also see that the calls $a['symbol'] and $b['symbol'] occur very often, and as array indexes at that. Because they appear so frequently and "bloat" the code, we decide it is worth shortening them to variables with short names, $a and $b. This makes the code look clearer. What is more, we notice that the variable name obligatorySymbols can be misleading and not necessarily always read as the list of the only symbols we care about in a given run (it is used to sum the results for a mini-table). So we rename it to restrictedTeamSymbols. It is longer, but thanks to the IDE that is not a problem for us, and it "says" better what the parameter is for.

Finally, we notice that the procedure for calculating fair play points depending on the cards received not only takes up some space and is duplicated, but will also be hard to find later if we have to change the values. So, taking advantage of the fact that these points are already calculated while reading the data from the file, we move the calculation to TeamDTO and format the code accordingly, so it is easy to see how many "points" each card is worth. In theory we should extract the card weights into separate constants or parameters so developers can easily change them later. Still, even now it is clearer, and in the future the appropriate change will be simple to make.

Commit with the changes in step 3: https://github.com/WildaSoftware/FootballGroupCalculator/commit/47ab8cf30dde253e81497ea638262c9008572e4e

Step 4: condensing sumResults and better control of the loaded file

Looking at sumResults after the changes, you can still see that something here needs improvement. The lines that add the goals scored and conceded, and their difference, are too similar to each other. Everything appears twice, and sometimes it even seems to appear four times. On the other hand, we already have the Team class, which perhaps should do this calculation itself. So let us do that and move this code to Team->addMatchResult, passing along from the perspective of which team we are counting the result: as the first (A) or the second (B). We can also see that the code got much shorter: instead of the 18 lines it used to take, summing the values now takes 10 and is clearer.

At this point some people may rightly wonder whether it is too easy to make a mistake with classes named TeamDTO and Team. That is true, you may get that impression, but the "DTO" makes a big difference here, which is why classes are sometimes named this way. It is not the only solution, though, and you could set them apart even more.

// metoda klasy Team
public function addMatchResult(TeamDTO $myTeam, TeamDTO $opponent) {
	if($myTeam->goals > $opponent->goals) {
		$this->points += 3;
	}
	elseif($myTeam->goals == $opponent->goals) {
		$this->points++;
	}
	
	$this->scoredGoals += $myTeam->goals;
	$this->concededGoals += $opponent->goals;
	
	$this->goalsBalance = $this->scoredGoals - $this->concededGoals;
	
	$this->fairPlay += $myTeam->calculateFairPlay();
}

In addition, note that the program will behave very badly if a nonexistent file is passed or if the argument is left out. So we properly secure the constructor of the Group class that takes this file, as well as the index.php entry file itself.

Commit with the changes in step 4: https://github.com/WildaSoftware/FootballGroupCalculator/commit/c3329c5b9c80d9d942b9fdb1df596ce4b58e8bd9

Step 5: creating a table object

Since we have sumResults reasonably cleaned up, we turn to calculateOrder. At a glance we can see that a lot of modifications await us here, but for the moment let us leave the main loop and deal with the fact that the method collects the symbols of the teams, not the teams themselves. This causes quite a few problems, conversions, searching for the team object, and so on. In short, when someone looks at this code for the first time, without extra comments it is hard to find their way around this mess. So can we not keep a single array (of Team objects) and work on that? We can, and we will, but one step at a time.

The problem is that besides calculating the big table, we also have recursive calls to the sorting for mini-tables (there may be many of them), which also has to be taken into account. One solution would be to separate the calculations for each type of table, but that does not entirely make sense, because these calculations would be very similar to each other, and we would end up duplicating code on a large scale. So we work on the same calculateOrder and try to do something here. Intuitively we feel that the symbol arrays can be eliminated here, but it is not immediately obvious how. So let us stay calm and go step by step, starting with something that may not get rid of them right away but rather groups them: let us introduce a table class, TeamTable.

Using a list of teams stored in the table object also means that we can move the operation of swapping the order into this class and sort the teams directly there. That is what we will slowly do, and along the way we introduce a method that arranges the table, specifically for the head-to-head records.

Unfortunately, all this means there are a few more changes and they are deeper than in the previous steps, but this had to be done so that the transformation was consistent and gave a good result.

Commit with the changes in step 5: https://github.com/WildaSoftware/FootballGroupCalculator/commit/069c9440f1746b456430a857136afbceceea5ade

Step 6: moving more of the sorting into TeamTable

The previous step showed us that TeamTable should be used even more. We finally make calculateOrder return not a list of symbols but a table object. In addition, since we no longer have to create a separate list of teams in the right order, and it simply emerges during sorting, the final foreach, in which we modify our order only with the mini-tables, gets much simpler. This gives rise to the method TeamTable->reorderPartByTable, which, well, basically does what used to happen in Group, but in a more organized way. For example, we get rid of the list of visited nodes, replacing it by collecting everything and removing duplicates at the end with array_unique, using the tools PHP gives us.

With a table as the result instead of a list of symbols, we can modify the printResults method. We can see here that soon there will probably be a chance to move this element to another class, but as we wrote earlier, we carry out the refactoring transformations one after another.

We also fix one bug that appeared along the way: in TeamTable->getTeamBySymbol we were iterating over the wrong array. Unfortunately, this sometimes happens, and here insufficient testing let us down. Clearly, automated unit tests would have been useful.

Commit with the changes in step 6: https://github.com/WildaSoftware/FootballGroupCalculator/commit/f7c89d497e70f76ec85f187e72456590a44a68a0

Step 7: shortening the code that cleans up the sorting

After the previous operation we see that the two loops that arrange the order based on mini-tables are quite similar to each other and can be merged. On analysis, you can see that the call to $smallTables[$hash]->reorderBySymbols becomes unnecessary, because calculateOrder itself already guarantees us the right order (we assume that a mini-table does not contain further mini-tables). What is more, since reorderBySymbols has become part of TeamTable and is run only there, it is possible to hide this method and make it private.

Commit with the changes in step 7: https://github.com/WildaSoftware/FootballGroupCalculator/commit/7109b3b2f1c78b57502f76e19cb2fccbf575e81a

Step 8: moving the method that displays the table

As we hinted in step 6, the printResults method takes a TeamTable object as an argument and uses only that, ignoring the members of the class it belongs to, namely Group. This is a typical code smell called feature envy, and the fix is simply to move the method to the class it is "interested" in. That is what we do with printResults, renaming it to print along the way. We also have to change all the related lines of code.

Commit with the changes in step 8: https://github.com/WildaSoftware/FootballGroupCalculator/commit/30982a2ed34d65dfe4e2fbd5c093e2f21003f606

Step 9: fixing the bug in the card count

I mentioned that refactoring does not fix functional bugs, but it can clean the code so much that it reveals their existence and makes them easier to get rid of. This is how we found a bug that consisted of cards being counted an extra time for teams that are put together in a mini-table. Because the results of the head-to-head matches between these teams are calculated again, the fair play scores were duplicated too, but only from those matches. We fix this with global indicators.

On reflection, you can see that we are actually introducing a small mess here: using an additional fair play array does not look like a desirable refactoring move. Still, I leave a different approach to fixing this bug to you, dear readers.

Commit with the changes in step 9: https://github.com/WildaSoftware/FootballGroupCalculator/commit/d346ee8e43a7dd5bb17561761ecc904d14668e03

Step 10: moving the sumResults and calculateOrder methods to TeamTable

Looking even closer, we can see that the two main methods of the Group class also mostly operate on a TeamTable object. So let us move them there. Unfortunately, the bad effect of the decision from step 9 is already visible here, because we have to make it possible to read the fair play table, which means passing a reference to our own object and leaving an additional sumResults behind. For now we can live with that, but I leave it as a lesson.

Commit with the changes in step 10: https://github.com/WildaSoftware/FootballGroupCalculator/commit/19b9e457f5ede29d1eb127a4e4bb125660d6d715

Step 11: removing the flag that decides whether fair play is calculated

Many people will dislike the calculateOrder method also because it takes a single boolean parameter that steers the flow at a certain point. I think you need common sense, and sometimes such a construct makes things much easier, but if it is possible to get rid of such an argument, it is worth doing. Especially since fair play is calculated only when checking the mini-table does not settle the order, so we are in a situation where the algorithm enters calculateOrder for a table that is an element of another table.

Let us use that and fill in the parent table when calculating the head-to-head summary. True, we have not gotten rid of the if, but the method looks a bit better.

Commit with the changes in step 11: https://github.com/WildaSoftware/FootballGroupCalculator/commit/bb5126d6a751f81a9eb6d3ed5e77281dae1d4404

Step 12: finally doing something about the comparison

For dessert we left something that already smells of a need for refactoring from afar. The ladder of conditional statements with the repeated swapOrder call and nested ifs checking for equality may work, but it looks terrible. In addition, a change in the rules for determining placings becomes hard to make in the program. What can we do about it?

Looking more broadly, we also see a bubble sort algorithm at work here, which is a paradox of its own: it is neither intuitive nor fast, yet it often comes to mind first for a programmer who has to write the sorting by hand. Let us leave that for now, because although PHP has its own functions for sorting arrays, it may not be entirely clear yet how we can use them here. Let us focus on the conditions themselves.

Knowledge of sorting mechanisms in programming languages tells us that so-called comparison functions, or even whole comparator classes, can be applied here. They usually check individual conditions, returning -1 (when the left object should come earlier in the order), 1 (in the opposite situation) or 0 (when the elements are equal). Here we will do something similar and introduce a TeamComparator class that contains methods for the individual criteria: points, goal difference, goals scored and the fair play ranking. Note that since the conditions for the mini-table are almost identical, there is no need to write them again.

class TeamComparator {

    private $teamTable;

    public function __construct(TeamTable $teamTable) {
        $this->teamTable = $teamTable;
    }

    public function comparePoints(Team $team1, Team $team2): int {
        if($team2->points == $team1->points) {
            return 0;
        }

        return $team2->points > $team1->points ? 1 : -1;
    }

    public function compareGoalsBalance(Team $team1, Team $team2): int {
        if($team2->goalsBalance == $team1->goalsBalance) {
            return 0;
        }

        return $team2->goalsBalance > $team1->goalsBalance ? 1 : -1;
    }

    public function compareScoredGoals(Team $team1, Team $team2): int {
        if($team2->scoredGoals == $team1->scoredGoals) {
            return 0;
        }

        return $team2->scoredGoals > $team1->scoredGoals ? 1 : -1;
    }

    public function compareFairPlayResults(Team $team1, Team $team2): int {
        $fp1 = $this->teamTable->getGroup()->getTeamFairPlayResultBySymbol($team1->symbol);
        $fp2 = $this->teamTable->getGroup()->getTeamFairPlayResultBySymbol($team2->symbol);

        if($fp2 == $fp1) {
            return 0;
        }

        return $fp2 > $fp1 ? 1 : -1;
    }
}

This form of comparator is an intermediate step. We see that although the ladder of conditional statements remains, the code seems much more pleasant. It is, however, a prelude to the next step.

Commit with the changes in step 12: https://github.com/WildaSoftware/FootballGroupCalculator/commit/f35f03ffc3c53fa6b385fe6923680a74347c5826

Step 13: a flexible comparator and shorter code

Now we will see the power of TeamComparator. Taking advantage of the fact that, apart from the fair play moment, the ranking criteria are the same and are given in the same order for the big and the small table, let us write a single compare method that gathers these conditions and, what is more, makes it easy to change their order in the future. We will use another characteristic feature of PHP here, namely the reflection mechanism, that is, calling code by name. This way we can call the methods for the successive criteria in a loop and check each time whether we can stop, because the result is settled. Of course, reflection has its drawbacks, but in some cases it makes writing code much more pleasant.

class TeamComparator {

    private $teamTable;

    public function __construct(TeamTable $teamTable) {
        $this->teamTable = $teamTable;
    }

    public function compare(Team $team1, Team $team2): int {
        $conditions = ['points', 'goalsBalance', 'scoredGoals'];
        $conditionsForSmallTable = ['fairPlayResults'];

        $result = 0;
        foreach($conditions as $condition) {
            $methodName = 'compare'.ucwords($condition);
            $result = $this->{$methodName}($team1, $team2);

            if(!empty($result)) {
                return $result;
            }
        }

        if(!empty($this->teamTable->getParentTable())) {
            foreach($conditionsForSmallTable as $conditionSt) {
                $methodName = 'compare'.ucwords($conditionSt);
                $result = $this->{$methodName}($team1, $team2);
    
                if(!empty($result)) {
                    return $result;
                }
            }
        }

        return $result;
    }

    private function comparePoints(Team $team1, Team $team2): int {
        if($team2->points == $team1->points) {
            return 0;
        }

        return $team2->points > $team1->points ? 1 : -1;
    }

    private function compareGoalsBalance(Team $team1, Team $team2): int {
        if($team2->goalsBalance == $team1->goalsBalance) {
            return 0;
        }

        return $team2->goalsBalance > $team1->goalsBalance ? 1 : -1;
    }

    private function compareScoredGoals(Team $team1, Team $team2): int {
        if($team2->scoredGoals == $team1->scoredGoals) {
            return 0;
        }

        return $team2->scoredGoals > $team1->scoredGoals ? 1 : -1;
    }

    private function compareFairPlayResults(Team $team1, Team $team2): int {
        $fp1 = $this->teamTable->getGroup()->getTeamFairPlayResultBySymbol($team1->symbol);
        $fp2 = $this->teamTable->getGroup()->getTeamFairPlayResultBySymbol($team2->symbol);

        if($fp2 == $fp1) {
            return 0;
        }

        return $fp2 > $fp1 ? 1 : -1;
    }
}

In addition, since the rest of the conditions no longer need to be visible from the outside, we can change the visibility of methods like comparePoints to private. The real revolution, however, awaits us in calculateOrder. This is what it used to look like:

public function calculateOrder() {
	// ...

	for($i = 0; $i < count($this->teams) - 1; ++$i) {
		for($j = $i + 1; $j < count($this->teams); ++$j) {
			if($i == $j) {
				continue;
			}
			
			$team1 = $this->teams[$i];
			$team2 = $this->teams[$j];
			$comparator = new TeamComparator($this);
			
			if($comparator->comparePoints($team1, $team2) > 0) {
				$this->swapOrder($i, $j);
			}
			elseif($comparator->comparePoints($team1, $team2) == 0) {
				if($comparator->compareGoalsBalance($team1, $team2) > 0) {
					$this->swapOrder($i, $j);
				}
				elseif($comparator->compareGoalsBalance($team1, $team2) == 0) {
					if($comparator->compareScoredGoals($team1, $team2) > 0) {
						$this->swapOrder($i, $j);
					}
					elseif($comparator->compareScoredGoals($team1, $team2) == 0) {
						if(!empty($this->parentTable)) {
							if($comparator->compareFairPlayResults($team1, $team2) > 0) {
								$this->swapOrder($i, $j);
							}
						}
						else {
							$hash = md5($team2->points.$team2->goalsBalance.$team2->scoredGoals);
							if(!array_key_exists($hash, $smallTables)) {
								$smallTables[$hash] = new TeamTable($this->group, $this);
							}
							
							$smallTables[$hash]->addTeam($team1);
							$smallTables[$hash]->addTeam($team2);
						}
					}
				}
			}
		}
	}
	
	// ...
}

And this is what it looks like now:

public function calculateOrder() {
	// ...

	for($i = 0; $i < count($this->teams) - 1; ++$i) {
		for($j = $i + 1; $j < count($this->teams); ++$j) {
			if($i == $j) {
				continue;
			}
			
			$team1 = $this->teams[$i];
			$team2 = $this->teams[$j];
			$comparator = new TeamComparator($this);

			$compareResult = $comparator->compare($team1, $team2);
			if($compareResult > 0) {
				$this->swapOrder($i, $j);
			}
			elseif($compareResult == 0) {
				$hash = md5($team2->points.$team2->goalsBalance.$team2->scoredGoals);
				if(!array_key_exists($hash, $smallTables)) {
					$smallTables[$hash] = new TeamTable($this->group, $this);
				}
				
				$smallTables[$hash]->addTeam($team1);
				$smallTables[$hash]->addTeam($team2);
			}
		}
	}
	
	// ...
}

You have to admit it is an improvement.

Commit with the changes in step 13: https://github.com/WildaSoftware/FootballGroupCalculator/commit/fca9ffcb14bdfe261749c2d7be6c41e1d576105b

Is this the end of refactoring?

No, and what is more, developers analyzing the process above surely thought "I would have done it differently" at a few points. Step 9, for instance, could be done another way, or you could replace the bubble sort with a different algorithm. Refactoring does not have to be identical in every case. Here it is worth drawing on your own experience, but also adapting your actions to the context, the type of project, the business conditions, the habits of the team (as long as they are good) and so on. You saw yourselves that along the way I introduced a controversial array for the fair play results, while it could probably have been solved differently. We could also have carried out further transformations and created truly perfect code. But that is not always possible or desirable. Sometimes the "good enough" mentioned earlier is enough. This also gives you a good base for exercises of your own ;)

Summary

In this article we tried to show what refactoring is and when it is done. We presented its basic benefits, but also the side effects you have to face, and we discussed matters related to the business environment. In the second part we analyzed an example of refactoring a script that calculates the order of teams in a group at a football tournament. I hope you had fun.

Regards and thank you, Jakub Rojek.