Recent CodeSOD

Code Snippet Of the Day (CodeSOD) features interesting and usually incorrect code snippets taken from actual production code in a commercial and/or open source software projects.

May 2024

A Serial Offender

by in CodeSOD on

Michael has a confession. Once upon a time, a very long time ago, he needed to write some JavaScript to serialize data and send it as part of a request. The challenge for Michael is that he didn't actually know JavaScript or what its built in functions could do and the task was already past the deadline by the time it got assigned to him.

function objectPrepareSave()
{
    for(var _a = 0; _a < aEditfields.length; _a++)
    {
        try
        {
            tinyMCE.execCommand('mceRemoveControl', false, aEditfields[_a]);
        }
        catch(err)
        {
        }
    }

    /* Basic Data */
    var _out = "DATA:{";
    _out += 'online="'+escape(getElementById("objOnline").checked)+'"';
    _out += ';;ref="'+escape(getElementById("objRefnum").value)+'"';
    _out += ';;name="'+escape(getElementById("objName").value)+'"';
    //_out += ';;parent="'+escape(getElementById("objParent").value)+'"';
    //_out += ';;rubric1="'+escape(getElementById("objRubric1").value)+'"';
    //_out += ';;rubric2="'+escape(getElementById("objRubric2").value)+'"';
    //_out += ';;rubric3="'+escape(getElementById("objRubric3").value)+'"';
    _out += ';;category="'+escape(getElementById("objCat").value)+'"';
    _out += ';;stars="'+escape(getElementById("objStars").value)+'"';
    //_out += ';;isle="'+escape(getElementById("objIsle").value)+'"';
    _out += ';;municipio="'+escape(getElementById("objMuni").value)+'"';
    _out += ';;city="'+escape(getElementById("objCity").value)+'"';
    //_out += ';;desc="'+escape(getElementById("objDesc").value)+'"';
    _out += ';;sDesc="'+escape(getElementById("objSDesc").value)+'"';
    //_out += ';;extra="'+escape(getElementById("objXtra").value)+'"';
    _out += ';;addition="'+escape(getElementById("objAdd").value)+'"';
    _out += ';;gifs="'+escape(getElementById("objPicList").innerHTML)+'"';
    _out += '}';
   
    /* Detail Data */
    _out += "::DETAILS:{";
    _out += 'null="null"';
   
    var _tbl = getElementById("detailTable");
    for(var _i = 1; _i < (_tbl.rows.length-1); _i++)
    {  
        var _row = _tbl.rows[_i];
        _out += ';;' + (_i - 1) + '="' + escape(_row.cells[1].textContent + ';' + _row.cells[2].lastChild.value) + '"';
    }
   
    _out += '}';
   
    /* Price Data */
   
    _out += '::PRICE:{';
    _out += 'null="null"';
   
    _tbl = getElementById("priceTable");
    for(var _i = 0; _i < _tbl.rows.length; _i++)
    {
        var _row = _tbl.rows[_i];
        if(_row.cells.length == 1)
        {
            _out += ';;' + _i + '="' + escape(_row.cells[0].textContent) + '"';
        }
        else
        {
            _out += ';;' + _i + '="';
            var _o = "";
           
            for(var _h = 0; _h < _row.cells.length; _h++)
            {
                _o += _row.cells[_h].textContent + ';';
            }
            _o = substr(_o, 0, strlen(_o) - 1);
            _out += escape(_o) + '"';
        }
    }
   
    _out += '}';
   
    _out += '::TPL:{';
    _out += 'null="null"';
   
    _tbl = getElementById("tplTable");
    var _index = 0;
    for(var _i = 0; _i < _tbl.rows.length; _i++)
    {
        var _row =_tbl.rows[_i];
        if(_row.cells.length == 1)
        {
            _out += ';;' + _index + '_' + _row.id + '="';
        }
        else
        {
            var _o = '<'+escape(_row.cells[0].textContent)+'>=<';
            if(_row.cells[1].childNodes[0].tagName)
            {
                if(_row.cells[1].childNodes[0].tagName == "INPUT" || _row.cells[1].childNodes[0].tagName == "TEXTAREA")
                {
                    _o += escape(_row.cells[1].childNodes[0].value);
                }
            }
            else
            {
                _o += escape(_row.cells[1].childNodes[0].nodeValue);
            }
           
            _o += '>';
            _out += escape(escape(_o));
        }
        _index++;
    }
   
    _out += '"}';
   
    aEditfields = new Array();
   
    return _out;
}

Chat about C

by in CodeSOD on

I've known a surprising number of developers who say, "Why use any higher level abstractions, you can just do this all in C, and the code will be cleaner and easier to read." Sometimes, they're right. Other times… not so much. And then there are the developers who find C too abstract for their tastes, and eschew things like structs.

That's what Renee encountered when inheriting a chat server written in C. I'm guessing it was an IRC server, based on some terminology in the code.


Classic WTF: An Ant Pushes a Perl

by in CodeSOD on
It's a holiday in the US today, so as per tradition, we reach back through the archives. Today is a classic of code generation gone horribly, horribly wrong. Original. --Remy

It’s an old joke that Perl is a “write only language”. Despite some of its issues, back in the early 2000s, Perl was one of the best options out there for scripting languages and rapid-development automation.

Speaking of automation, build automation is really important. Back in the early 2000s, before Maven really caught on, your build automation tool for Java was Ant. Ant, like everything invented in the early 2000s, was driven by an XML scripting tool. Since it was tuned specifically for Java, it had some high-level operations to streamline tasks like generating proxy classes for calling web services based on a supplied WSDL file.


Regional Variation

by in CodeSOD on

Visual Studio and the .NET languages support a feature known as "regions". Enclosing a block of code between #region SomeName and #endregion creates collapsible regions in the text editor.

It can, in principle, help you organize your code. It does, in practice, make code like this, from Mark, possible.

A screenshot of Visual Studio, where 770 line function is split up using regions

Delectable Code

by in CodeSOD on

Good method names are one of the primary ways to write self-documenting code. The challenge there, is that documentation often becomes out of date.

Take this delectable PHP nugget, from Nathaniel P, who has previously been tortured by bad date handling.


Scoring the Concatenation

by in CodeSOD on

Today's a simple one. We've all seen code that relies too heavily on string concatenation and eschews useful methods like Join.

Nick L sends us this VB.Net example, written by a slew of mechanical engineers.


A Poorly Pruned Branch

by in CodeSOD on

Juliano had this very non-WTF bit of PHP code:

if (!$path) {
	//do stuff
} else {
	//do other stuff
}

Many Unhappy Returns

by in CodeSOD on

Gavin continues work on the old C++ app he inherited. Today we get a delightful smattering of bad choices.

HRESULT CExAPI::GetPageCacheForFolder( IN  CEntryID *p_cio_Folder, OUT CPageCache **pp_PC )
{
	CEntryID *p_cio_Local = new CEntryID( this, p_cio_Folder );

	switch ( p_cio_Folder->m_uiType )
	{
		case EID_TYPE_EMPTY:
			return S_OK;
			break;
		case EID_TYPE_NORMAL :
			return GetPageCacheForNormalFolder(p_cio_Folder, pp_PC );
			break;
		case EID_TYPE_ADDRESSBOOK :
			return GetPageCacheForABFolder(p_cio_Folder, 0, pp_PC );
			break;
	}

	return S_OK;

	DeleteIfNotNULL( p_cio_Local );
}

Accessed Nulls

by in CodeSOD on

"The attached class connects to an Access database," writes Nicolai. That's always a good start for a WTF. Let's take a look.

public class ResultLoader {

	private static Logger sysLog = Logger.getLogger(ResultLoader.class);
	private static String url = "somePath";

	/**
	 * get the ResultTable from the Access database
	 * 
	 * @param tableName
	 * @return
	 */
	private static Table getResultTable(String tableName) {
		try {
			// create a new file with the path to the table
			File db = new File(url);
			// let Jackcess open the file and return a table
			return Database.open(db).getTable(tableName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * load result from DB
	 */
	public static void loadResult() {
		String tableName = "Result";
		Table resultTable = getResultTable(tableName);

		if (!resultTable.equals(null)) {
			Map<Integer, Float> yearConsumption = new HashMap<Integer, Float>();

			for (Map<String, Object> row : resultTable) {
				/*
				 *  [snip] does something with the table's rows
				 */
			}
			Result result = new Result(00, new Date(), consumptions);
		} else {
			sysLog.info("There is no data object in the Access Database!");
		}
	}
}

Reflect on Your Mistakes

by in CodeSOD on

While Java didn't invent putting a toString method in the base class of every object, it certainly made it mainstream. The nice thing about the method is that it allows you to turn any object into a string, though it's up to the implementor to decide what a good string representation is. But what if you want to ensure that the object you're handed is really and truly a string, not just something you can convert to a string?

teknopaul's co-worker found their own solution:


Suspicious Contents

by in CodeSOD on

While poring through some VB .Net code, John noticed some odd things in their datamodel. For example, a different process would scan files, and log any "suspicious" files into a database. The program John supported would then report on that data.

One of their classes had a property which looked like this:


Spaced Out Replacement

by in CodeSOD on

You have some text, and need to replace every sequence of spaces with a single space. E.g., My text becomes My text. Now, if you're most of us, you ignore the famous quote and reach straight for regexes.

But Samuel's co-worker isn't most of us.


Totally Valid

by in CodeSOD on

Greg's co-worker really wanted to make sure that a variable was correctly set to true or false. So they did this:

if (isValid == true)
{
	isValid = true;
}
else
{
	isValid = false;
}

Metaception

by in CodeSOD on

Meta-programming- programs which generate programs- is a delightful hobby, but usually shouldn't be used in production code. Usually. I mean, if you're working in LISP, 90% of your program is going to be macros.

But if you're using PHP and JavaScript, there's good odds that someone you work with has decided to combine these two tastes together to create something nobody wants to taste.