Sorry again if this feels like I’m singling you out, I’m not. Your article appears in my feed, I read it, I tell you what I think.
Once again your "wrong" isn't all that wrong, particularly compared to what you call right as your test case misses the actual usage case for the former.
Calling the dictionary to check it more than once!
If you put it into the conditional call each and every blasted time you call it, you aren't leveraging what a Dictionary class is even for! Worse, you're wasting massive amounts of time redeclaring the same values meaning more memory thrashing, copying, etc, etc.
In that way I'd say the Dictionary class isn't wrong, the test is. In both versions. Becasue they do not repesent what a dictionary class would be used for. I mean feed it something like:
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris vitae risus vitae lorem euismod accumsan viverra id sapien. Praesent congue, purus quis placerat finibus, magna enim ultricies eros, at auctor eros justo sed tellus. Aenean dapibus ultrices semper. Sed eget ligula a massa fermentum tempus eu sed velit. Aenean quis lectus enim. Nam eu fermentum massa, et tempus nunc. Maecenas sem neque, egestas pulvinar mi a, posuere vestibulum diam. Curabitur pellentesque lacus quis magna commodo vehicula. Cras sit amet ante ultricies, cursus sapien non, laoreet erat. Vestibulum sapien mauris, rutrum sed tortor eget, dapibus finibus risus. Vivamus sed diam semper, placerat ligula et, ultrices erat. Pellentesque placerat lorem ex, et efficitur eros dictum et. In dictum lacinia massa, at hendrerit ex tempus vel. Aenean suscipit, urna vel elementum rhoncus, mi diam mollis tortor, id molestie eros dui vitae augue. Donec in enim dolor. In rhoncus sit amet tortor at luctus.';$words = preg_split("/\w+/", $text, PREG_SPLIT_NO_EMPTY);
$newText = '';foreach ($words as $word) {
if (Dictionary->includesWord($word) $newText .= $word;
else $newText .= '<mark>' . $word . '</mark>';
$newText .= ' '; // real code would insert the actual split char here
}
And see how well your reinterpretation holds up. More so if you have Dictionary being used AFTER it's populated all over your codebase in different places. The very reason it gets stored locally by the constructor in the first huffing place! You make it once because you’re going to use it many times all over the place and don’t want to constantly be screwing around with wondering why your performance goes to hell due to memory thrashing. The moment the same dictionary is used in disparate places, what you’re suggesting goes bits-up face-down.
It's also funny you're using PHP 8's pointless typecasting (amazing an old Pascal and Ada hound like me calling it pointless, but there it is!), but not its hyper-useful constructor property promotion. Instead of:
private $words;
function __construct(array $words) {
$this->words = $words;
}
You can now do:
function __construct(private array $words) {}
Which is pretty dang neat... and way overdue.