Jump to content


Member Since 06 May 2003
Offline Last Active Today, 04:50 AM

#1519292 Refactoring Code: does the concept of refactoring exist purely because human...

Posted by gizmola on 20 August 2015 - 01:16 AM

Here's what often happens:


You join a company/project that is trying to build some software to do a number of things, as set out in the goals/design/specifications.  


You break things up into tasks and different members of the team start working on them.


Frequently there is a framework being used, and hopefully some conventions, but frequently there is a lot of uncertainty.


People start plowing away, and the way Programmer A does things vs. Programmer B might be substantial.


Now you have 2-3 semi-working pieces of the product and you start looking at the code, and right away it's obvious that this code was produced by two different people.  


As "hypothetically" I might have been one of the people involved, even as I was coding my piece, I realized along the way that there were some things my code did, where given more time I might have made it more reusable, or had a better design, so if I'm lucky I might stashed a few comments or TODO in my code.


Now we're on to more items, and programmer 2 is doing something very similar to the first item, and there's a lot of copy and pasting involved.


We do some code reviewing, and it's clear to everyone that this is not DRY.  There is a lot of code being repeated.


Programmer 3 just joined, and now has to do something very similar to what Programmer 1 did, and I did, but the problem is, that even though they are similar items, the team has not agreed which is the best way to do it, so Programmer 3 basically has to just pick someone to emulate (if we're lucky) or maybe decides that everyone else was an idiot and does the new component in a completely different way than the two previous components.


The PM and QA are reviewing things, and everyone is super excited because we're only three weeks behind the original schedule (of completion in 6 hours) and the system basically seems to do the things that it was supposed to do.


The only problem is, that the underlying code now looks like it was assembled by a chimp with ADD, and there are 12 new features planned for next week....



If you're lucky, maybe there's a lead dev, who goes in and adds a couple of much needed unit tested components, and redoes one of the sections and this then becomes "the reference" for how to do something similar.  


If you're lucky, there's some design patterns being used.


If you're lucky there are code reviews.


If you're lucky people go back before anyone notices and refactor things to be consistent.


If you're lucky you have appropriate roles and responsibilities and some division of labor.


Programmers that care about the overall quality of the underlying design, or are incented to insure it has minimal bugs, or have to maintain it or keep it running are going to be interested in refactoring.


Then there are situations where someone is brought in to start working on legacy code, and they realize that what they've just been assigned to work on is a rat's nest of rotten spaghetti, and those three things that "the old guy never got around to adding but should be easy right?" are actually close to impossible to add given the original architecture (or lack thereof) and the fact that doing just about anything to it has the potential to create side-effects that will break unknown areas of the system, causing everyone to question the new programmer's basic competence.


No, I would not say that refactoring is related to understanding someone else's code, and thus used as an excuse because you can't understand what they were thinking.  

#1519215 i must be missing something...

Posted by gizmola on 18 August 2015 - 10:18 PM

Don't concern yourself with closing the database connection, especially when using MySql.

When the script is done executing all handles are closed for you.

There are very few situations where you need to worry about opening and closing individual database connections within a script.

#1519020 Implementing captcha to my dynamically generated forms

Posted by gizmola on 16 August 2015 - 07:16 PM

In your function comment_form($id, $captcha), you added the $captcha as a param but you never use it in function.

Probably after this line you would use it:

<input type='hidden' name='blog_id' value='$id'>
<input type='submit' name='submit' id='post' value='post'>

#1519015 Implementing captcha to my dynamically generated forms

Posted by gizmola on 16 August 2015 - 06:49 PM

Heredocs will interpolate variables.

So something like this should work:

function comment_form($id, $captcha) {
    global $user_data;
    if (logged_in() === true) {
        return <<<EOT
        <form method='post' action='' class='comments_form'>
            <input type='text' name='username' placeholder='your name... *' id='name' value='{$user_data['username']}'>
            <textarea name='comments' id='textarea' placeholder='your comment... *' cols='30' rows='6'></textarea>
            <input type='hidden' name='blog_id' value='$id'>
            <input type='submit' name='submit' id='post' value='post'>
        <hr class='artline'>

$captcha = create_captcha();
echo comment_form($id, $captcha)

Of course you need to alter the create_captcha function so that it returns a string rather than echoing out the markup directly, but that is a general pattern you should be using in all your functions. It will start to improve the separation of concerns.

#1518974 Reverse words in a sentence without using PHP functions

Posted by gizmola on 15 August 2015 - 08:31 PM

The key to requinix's ingenious solution is the use of the '@' error suppression operator.

for ($i = 0; @$input[$i] != ""; $i++) {
This allows him to for-loop character by character through the input by treating the string as a character array, and then by reading beyond the end of the string. That allows him to avoid the use of the strlen() built-in used by Scootsah.

From there it's just concatenating the strings he finds in reverse order. Nice!

With that said, I think what they wanted you to do was use a stack, given the way the question was posed. An array works pretty well for this, so Scootsah's solution is basically what I think they expected.

He reads the words and adds them to the array using "$array[] = $word". You get a numerically ordered "stack".

Then it's just a matter of for looping through the array in reverse order.

So just for fun, here's a way you could walk through the array in reverse order without using a negative for loop to duplicate the array into a reversed form, based on Scootsah's solution:

function reverseString($input)
    $currentWord = '';
    $words = array();

    for ($i = 0; $i < strlen($input); $i++) {
        if ($input[$i] == ' ') {
            $words[] = $currentWord;
            $currentWord = '';

        $currentWord .= $input[$i];

        if ($i == (strlen($input) - 1)) {
            $words[] = $currentWord;

    if (!empty($words)) {
        $output = '';

	for (end($words); key($words) !== null; prev($words)) {
  		$output .= current($words) . ' ';
        return trim($output);

$input = 'this is phpfreaks';
$output = reverseString($input);

echo "Input: $input<br />Output: $output";

#1518965 Greetings!

Posted by gizmola on 15 August 2015 - 07:13 PM

All of the above.

In general terms, the most important thing is to make sites.

You will learn more by doing than all the other methods combined.

#1515933 Replace Characters Algorithm with O(n) Time/Complexity Notation

Posted by gizmola on 09 July 2015 - 01:13 AM

Seems like the mystery is solved.  Nice thread guys!

#1514157 Empty $_POST on form submission?

Posted by gizmola on 17 June 2015 - 08:38 AM

In the future, the fact that you were doing this as a wordpress customization would have been good to know.

#1509180 how to make my website fast ?

Posted by gizmola on 16 April 2015 - 04:45 PM

Neil, you left out:


  • Make a sandwich
  • Take power nap
  • $$$ Profit!

#1508998 URGENT: I could use 5 minutes of your time! Please read

Posted by gizmola on 14 April 2015 - 04:52 AM

Over a decade of involvement with phpFreaks, I have answered something like ten thousand questions, moderated thousands more, written a number of tutorials and spent days of my life providing system administration help. I've also personally donated a few hundred dollars over the years to help keep the site running. I'm just one of many volunteers who have done as much or more.

Many people don't understand that the people who make this place run are all volunteers who do what we do for the love of the PHP language, web development and open source ecosystem, and this is a way we can give back in our own small way.

With that said, for the first time in my many years here, I have a personal request.

My son plays Ice Hockey at our local rink in Burbank California. There aren't many rinks in this area, and Pickwick is one of the older rinks, having been built in the 1950's.

We love the sport, and the rink, but it has seen better days. The compression system doesn't work very well, the boards need repairs, and the facilities in general are not in great shape.

Kraft has a Hockeyville contest that is providing money to community hockey rinks for maintenance and upgrades, and Pickwick is a finalist. We are now looking to advance to the semi finals.

If this community has helped you, I'm asking that you simply go to this site and vote for our rink "Pickwick". You do have to register (Facebook makes it easy) or you can text. You have to be a US resident to do this.

You can call, text or use the website, and can vote up to 50x via each method.

If you've ever felt an interest in thanking me, or the folks who keep the site humming, here's a way you can do so that will only cost a few minutes of your time and nothing more.

You literally have to do this TODAY Tuesday April 13th EST. Voting is open as we speak!

Here's the Link: https://www.krafthockeyville.com/#

Choose Pickwick form the West column. THANK YOU.

Here's some information on other ways to vote if you are willing:


#1508590 scandir()

Posted by gizmola on 09 April 2015 - 04:52 PM

Thanks Barand -- I should have said "practically".  


Also more good reasons why people use echo instead.

#1508588 if (isset($_SESSION['un']) && isset($_SESSION[...

Posted by gizmola on 09 April 2015 - 04:46 PM

Yes, http://php.net/manua...okie-params.php can be issued in the code.  The problem is that you will need this call to occur just before the session_start() call.


Hopefully your system has that occur in a shared class, function or included file where you can make the change and have it seen throughout the scripts.


You might already have surmised that sessions depend on cookies, and this is really a mechanism of how cookies work and the built in protections.


You can do some investigation in advance of trying this, by looking at your cookies and seeing what the specific cookie(s) are that are being pushed from your server to determine if this might be the problem or not.

#1508581 scandir()

Posted by gizmola on 09 April 2015 - 03:43 PM

Great.  Also just a tip, Print and echo are the same function.  Most people use echo, because it's shorter.  


Printf came over from the 'C' language  and uses formatting placeholders and parameters.  There are some cases when you want to control things like the exact format of a number where printf can be attractive, although there are often a number of different ways to accomplish the same thing in php, and for the most part it's personal preference.

#1496425 What's the fastest way to search INNODB tables?

Posted by gizmola on 12 November 2014 - 07:33 PM

MySQL is an odd database because it has pluggable engines that can work entirely differently.  MyISAM is the base engine and of course InnoDB was a pluggable engine that became very popular.  


Just about all DB's have some form of caching for queries.  In the case of MyISAM this extends to the parsing of the queries themselves but not the actual data.  With the buffer_pool in innodb -- the actual data retrieved is cached.  So, in terms of what you were asking, when you do a LIKE '%...' query, the table will have to be scanned starting at row 1 and continuing to the last row in order to return a result.  With Innodb and a large enough buffer pool, essentially the data will already be in memory and the tablescan process will be much faster than it would be reading the data from disk.


Unfortunately, with shared hosting, you are not in control of those parameters as you're sharing a mysql server your hosting company provides, either on your server or some secondary server they host.


In the shared host scenario, I would advise you to implement Barand's suggestion.  

#1495852 What's the fastest way to search INNODB tables?

Posted by gizmola on 05 November 2014 - 08:00 PM

There are other reasons to utilize innodb besides the ones mentioned.  I highly recommend you stay with it.  


You could use Barand's suggestion -- have a denormalized search table, where you simply replicate the values into a small myisam table for the benefit of the search.   The coding and interruption required would be minimal. You'd simply need to write the replication script and schedule it in cron.  


To your original question one of the benefits of innodb is that it has a true data cache.  It's called the "buffer pool".  If you have sufficient resources on your server, you could increase the size of the buffer pool to insure that data is coming from cache.  It is often possible with a small fairly stable database like the one you describe where you are almost entirely "READ/SELECT" based, to have a pool where the data and indexes for the entire table will be in the buffer pool.  


At that point a SELECT '%...' will be far less disruptive than normally because it will be coming from memory.  An 8-10k row table is tiny in the database world.


You would have to invest some time trying to figure out the size of your overall database and the tables in particular, and you'd need to understand your overall memory usage to determine if you could allocate more RAM to mysql that you currently do.


You can start by looking at http://dev.mysql.com...uffer-pool.html


The innodb_buffer_pool_size and innodb_buffer_pool_instances are the only params you really need to understand and possibly change.   Whatever you do, these are good params to understand.  Although it might be a stretch if you are a novice sysadmin, the free tool, innotop is fantastic for making it easy to monitor the effectiveness of your caching and figuring out your cache hit ratio.  I would think based on your description that you should be aiming for close to 100% cache hit with your innodb tables.