¿Cuál fue el peor fragmento de código del que te enorgulleces? [cerrado]


14

He tenido algunos de los que estoy orgulloso y algunos de ellos fueron escritos por mí hace unos años. No tiene que ser necesariamente con errores, solo código incorrecto.


8
Demasiados para publicar, ¿puedo enviarte mi historial SVN? ;)
Nicole el

Respuestas:


20

No sé si estar orgulloso de la solución porque era muy obvio, pero el código más horrible que recuerdo fue el siguiente.

if (userName=="John O'Reily") { userName= "John O''Reily";}
if (userName=="Stacy O'Neil") { userName= "Stacy O''Neil";}
if (userName=="Finnegan O'Connor") { userName= "Finnegan O''Connor";}
...
someSQL = "SELECT * from Users where UserName='" + userName + "'";

Aparentemente, el desarrollador anterior seguía agregando nuevas líneas cada vez que un nuevo usuario (generalmente irlandés) comenzaba a recibir errores en la aplicación.

Lo dejaré como un ejercicio para la clase sobre cómo se solucionó.


Tomo SQL concatena dos literales de cadena adyacentes, ¿verdad?
Amarghosh

1
@Amarghosh: ¿Eh?
JohnFx

2
@Amarghosh: es un escape. Las comillas simples dobles se reducen a comillas simples dentro de un literal de cadena.
Mason Wheeler

Gracias @Mason, pensé que UserName='John O''Reily'se volvería UserName='John OReily'(como cómo C concatena literales de cadena adyacentes), pero no pensé en lo que faltaba ':(
Amarghosh

1
@JohnFx - ¿Supongo que su corrección convirtió la declaración SQL original en SQL parametrizado para eliminar la inyección SQL?
Melioratus

7

Realmente no debería estar orgulloso de esto, pero por alguna razón, fue satisfactorio.

Aparte de tener COBOL en la escuela, no tenía experiencia, pero era un hombre bajo en el tótem, y necesitábamos proporcionar el código fuente de compilación a un proveedor externo para la verificación de Y2K. Teníamos un solo archivo COBOL con múltiples rutinas que se llamaban entre sí en el archivo, tipo espagueti, y era demasiado grande para cargarlo en nuestro IDE actual para compilarlo. Necesitaba separarse en al menos dos archivos físicos, y esos archivos, por supuesto, necesitaban tener todo lo que necesitaban en su propio archivo. (O tal vez, había una manera de vincularlos, pero realmente no conocía COBOL).

De todos modos, tomé este archivo de aproximadamente 100,000 líneas, y separé suavemente las docenas y docenas de rutinas para encontrar dos conjuntos de rutinas que eran independientes entre sí, y por lo tanto podrían existir en dos archivos separados, cada uno de aproximadamente 50,000 líneas. (Creo que el máximo que el compilador podía manejar era de aproximadamente 80,000 líneas, por lo que necesitaba ser bastante parejo).

Estaba leyendo un idioma antiguo que no sabía, y todavía tenía éxito en la tarea.


55
Entonces estabas diseccionando un fósil escrito en un dinosaurio. O realizar una cirugía de roca. O ... mi analogía se vino abajo. ¡Ayuda!
Jon Purdy

2
¡Uno para la legibilidad de COBOL!

¿Cuál fue el IDE que tenía un límite de línea?
Torre

Somos una tienda de Cobol y hay un límite estricto con una de las herramientas (compilador o editor, no estoy seguro) con 65535 líneas. Podría ser algo similar.

6

Saqué un cursor de un gatillo y reduje el tiempo para insertar 40,000 nuevos registros de una hora a menos de un minuto. Finalmente, esto me permitió insertar 21 millones de registros en algo menos que tiempo glacial, pero nunca intentamos la importación de 20 millones de registros hasta después de la corrección, por lo que no tengo estadísticas sobre cuánto tiempo ahorramos.


2
¿Y, por supuesto, alguien en marketing reclamó crédito por acelerarlo? :-)
The Tin Man

4

Había una clase base para crear cuadros de diálogo de confirmación para diferentes operaciones en nodos de árbol. Solo necesitaría proporcionar un mensaje para que se muestre en el cuadro de diálogo y la acción a ejecutar si se confirmó. Buen sistema, pero no permitió un manejo especial en caso de que no haya seleccionado un nodo de árbol. Como resultado, el texto en uno de los cuadros de diálogo decía: "Seleccione no". Si seleccionó sí, arrojó una excepción. Muy buena experiencia de usuario, de hecho.

Lo arreglé deshabilitando las operaciones no válidas.


1
Debería haber seleccionado 'no' entonces!
Alan Pearce

2

Lo peor que he visto fue un código Java para extraer oraciones clave de un corpus de texto.

  • El código tenía pocos comentarios (además de los comentarios de código deshabilitado) y tenía nombres pobres.
  • El estado del algoritmo se almacenó en vectores estáticos públicos.
  • En lugar de almacenar valores en los vectores, almacenó sus representaciones de cadena.
  • Los vectores eran clases de pobres (eran paralelos, cada índice era una 'instancia')
  • El algoritmo era subóptimo (n ^ 2 en lugar de una versión n log n más fácil de entender)

Para ser justos, esto no es nada en comparación con algunas de las cosas que están allí, pero todavía hay una gran diferencia en la calidad antes y después. Considere el siguiente código real antes y después de una función:

Antes (¡intenta averiguar qué hace antes de mirar Después!):

public static void getCluster() {
    count = new Vector();
    for (int i = 0; i < begin.size(); i ++)
        count.add("1");
    if (begin.size() > 1) {
        for (int i = 0; i < begin.size() - 1; i ++) {
            for (int j = i + 1; j < begin.size(); j ++) {
                int b1 = Integer.parseInt(begin.get(i).toString());
                int e1 = Integer.parseInt(end.get(i).toString());
                double w1 = Double.parseDouble(wght.get(i).toString());
                int c1 = Integer.parseInt(count.get(i).toString());
                int b2 = Integer.parseInt(begin.get(j).toString());
                int e2 = Integer.parseInt(end.get(j).toString());
                double w2 = Double.parseDouble(wght.get(j).toString());
                int c2 = Integer.parseInt(count.get(j).toString());
                int max = Math.max(e1, e2);
                boolean toRemove = true;
                if (b1 == b2) end.set(i, Integer.toString(max));
                if (b1 < b2) {
                    if (b2 < e1) end.set(i, Integer.toString(max));
                    else {
                        if ((b2 - e1) <= 3) end.set(i, Integer.toString(e2));
                        else toRemove = false;
                    }
                }
                if (b1 > b2) {
                    if (e2 >= b1) {
                        begin.set(i, Integer.toString(b2));
                        end.set(i, Integer.toString(max));
                    } else {
                        if ((b1 - e2) <= 3) {
                            begin.set(i, Integer.toString(b2));
                            end.set(i, Integer.toString(e1));
                        } else toRemove = false;
                    }
                }
                //System.out.println(b1 + ", " + e1 + ", " + b2 + ", " + e2 + " ---> " + begin.get(i).toString() + ", " + end.get(i).toString());
                if (toRemove) {
                    wght.set(i, Double.toString(w1 + w2));
                    count.set(i, Integer.toString(c1 + c2));
                    begin.removeElementAt(j);
                    end.removeElementAt(j);
                    wght.removeElementAt(j);
                    count.removeElementAt(j);
                    j --;
                } //end of if
            } //end of for j
        } //end of for i
    } //end of if
    //System.out.println(begin);
    //System.out.println(end);
    //System.out.println(wght);
    //System.out.println(count);
}

Después:

/** Returns the result of merging all overlapping-with-leeway clusters into single combined clusters.
 * @param leeway The minimum number of word-spaces which must separate two clusters in order for them to not be overlapping.
 * @requires clusters != null
 * @requires leeway >= 0
 * @ensures result != null */ 
private static List<TermCluster> combineOverlappingClusters(Iterable<TermCluster> clusters, int leeway) {
    if (clusters == null) throw new NullPointerException("clusters");
    if (leeway < 0) throw new IllegalArgumentException("leeway < 0");

    //Sort to allow linear folding
    List<TermCluster> sortedClusters = Iter.sort(clusters, new Comparator<TermCluster>() {
        @Override public int compare(TermCluster o1, TermCluster o2) {
            return new Integer(o1.begin).compareTo(o2.begin);
        }
    });
    if (sortedClusters.size() == 0)
        return sortedClusters;

    //Combine left-to-right
    List<TermCluster> result = new ArrayList<TermCluster>();
    TermCluster acc = sortedClusters.get(0);
    for (TermCluster cluster : sortedClusters.subList(1, sortedClusters.size())) {
        if (acc.isOverlappingWithLeeway(cluster, leeway)) {
            //combine
            acc = acc.combineWith(cluster);
        } else {
            //next
            result.add(acc);
            acc = cluster;
        }            
    }
    result.add(acc); //leftovers

    return result;
}

1

Mi primer trabajo de programación fue escribir instaladores en InstallShield. Heredé un script que tenía miles de líneas sin funciones , solo gotos. Fue alucinante. Lo reescribí, lo hice todo bonito y modular y basado en datos, para que me pudieran dar binarios / arte / etc. y obtener un nuevo instalador en menos de una hora, en lugar de la semana que le llevó al tipo anterior. Estaba muy orgullosa de mí misma.


0

Creo que nada se acerca a esto :

function pmn_Sort(strBy)

local tblA = {};
local tblB = {};
local tblC = {};
local tblD = {};
local tblE = {};
local tblF = {};
local tblG = {};
local tblH = {};
local tblI = {};
local tblJ = {};
local tblK = {};
local tblL = {};
local tblM = {};
local tblN = {};
local tblO = {};
local tblP = {};
local tblQ = {};
local tblR = {};
local tblS = {};
local tblT = {};
local tblU = {};
local tblV = {};
local tblW = {};
local tblX = {};
local tblY = {};
local tblZ = {};
local tblOT = {};

local iA = 0;
local iB = 0;
local iC = 0;
local iD = 0;
local iE = 0;
local iF = 0;
local iG = 0;
local iH = 0;
local iI = 0;
local iJ = 0;
local iK = 0;
local iL = 0;
local iM = 0;
local iN = 0;
local iO = 0;
local iP = 0;
local iQ = 0;
local iR = 0;
local iS = 0;
local iT = 0;
local iU = 0;
local iV = 0;
local iW = 0;
local iX = 0;
local iY = 0;
local iZ = 0;
local iOT = 0;

    if strBy == "Name" then

        strSort = "Name";
        numPlcount = ListBox.GetCount("Playlist");
        numPLitem = 1;
        numPLadd = 0;
        while numPLitem &lt;= numPlcount do

            strPLtxt = ListBox.GetItemText("Playlist", numPLitem);
            strPLdata = ListBox.GetItemData("Playlist", numPLitem);
            strPLleft = String.Left(strPLtxt, 1);
            if strPLleft == "a" or strPLleft == "A" then

            iA = iA + 1;
            tblA[iA] = strPLdata;

            elseif strPLleft == "b" or strPLleft == "B" then

            iB = iB + 1;
            tblB[iB] = strPLdata;

            elseif strPLleft == "c" or strPLleft == "C" then

            iC = iC + 1;
            tblC[iC] = strPLdata;

            elseif strPLleft == "d" or strPLleft == "D" then

            iD = iD + 1;
            tblD[iD] = strPLdata;

            elseif strPLleft == "e" or strPLleft == "E" then

            iE = iE + 1;
            tblE[iE] = strPLdata;

            elseif strPLleft == "f" or strPLleft == "F" then

            iF = iF + 1;
            tblF[iF] = strPLdata;

            elseif strPLleft == "g" or strPLleft == "G" then

            iG = iG + 1;
            tblG[iG] = strPLdata;

            elseif strPLleft == "h" or strPLleft == "H" then

            iH = iH + 1;
            tblH[iH] = strPLdata;

            elseif strPLleft == "i" or strPLleft == "I" then

            iI = iI + 1;
            tblI[iI] = strPLdata;

            elseif strPLleft == "j" or strPLleft == "J" then

            iJ = iJ + 1;
            tblJ[iJ] = strPLdata;

            elseif strPLleft == "k" or strPLleft == "K" then

            iK = iK + 1;
            tblK[iK] = strPLdata;

            elseif strPLleft == "l" or strPLleft == "L" then

            iL = iL + 1;
            tblL[iL] = strPLdata;

            elseif strPLleft == "m" or strPLleft == "M" then

            iM = iM + 1;
            tblM[iM] = strPLdata;

            elseif strPLleft == "n" or strPLleft == "N" then

            iN = iN + 1;
            tblN[iN] = strPLdata;

            elseif strPLleft == "o" or strPLleft == "O" then

            iO = iO + 1;
            tblO[iO] = strPLdata;

            elseif strPLleft == "p" or strPLleft == "P" then

            iP = iP + 1;
            tblP[iP] = strPLdata;

            elseif strPLleft == "q" or strPLleft == "Q" then

            iQ = iQ + 1;
            tblQ[iQ] = strPLdata;

            elseif strPLleft == "r" or strPLleft == "R" then

            iR = iR + 1;
            tblR[iR] = strPLdata;

            elseif strPLleft == "s" or strPLleft == "S" then

            iS = iS + 1;
            tblS[iS] = strPLdata;

            elseif strPLleft == "t" or strPLleft == "T" then

            iT = iT + 1;
            tblT[iT] = strPLdata;

            elseif strPLleft == "u" or strPLleft == "U" then

            iU = iU + 1;
            tblU[iU] = strPLdata;

            elseif strPLleft == "v" or strPLleft == "V" then

            iV = iV + 1;
            tblV[iV] = strPLdata;

            elseif strPLleft == "w" or strPLleft == "W" then

            iW = iW + 1;
            tblW[iW] = strPLdata;

            elseif strPLleft == "x" or strPLleft == "X" then

            iX = iX + 1;
            tblX[iX] = strPLdata;

            elseif strPLleft == "y" or strPLleft == "Y" then

            iY = iY + 1;
            tblY[iY] = strPLdata;

            elseif strPLleft == "z" or strPLleft == "Z" then

            iZ = iZ + 1;
            tblZ[iZ] = strPLdata;

            else

            iOT = iOT + 1;
            tblOT[iOT] = strPLdata;

            end

            numPLitem = numPLitem + 1;

        end

        ListBox.DeleteItem("Playlist", LB_ALLITEMS);

        for ii, id in tblA do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblB do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblC do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblD do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblE do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblF do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblG do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblH do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblI do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblJ do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblK do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblL do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblM do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblN do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblO do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblP do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblQ do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblR do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblS do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblT do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblU do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblV do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblW do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblX do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblY do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end     

        for ii, id in tblZ do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

        for ii, id in tblOT do

            if id ~= "" then

                numPLadd = numPLadd + 1;
                strPLtxt = String.SplitPath(id).Filename..String.SplitPath(id).Extension
                ListBox.AddItem("Playlist", strPLtxt, id);

            end

        end

    elseif strBy == "Type" then

        strSort = "Type";

        if File.DoesExist(_ProgramFilesFolder.."\\MediaX\\playlist.mx") == true then

            play_file2 = TextFile.ReadToTable(_ProgramFilesFolder.."\\MediaX\\playlist.mx");

            if play_file2 then
                ListBox.DeleteItem("Playlist", -1);

                for rl,rPath in play_file2 do
                    r2Path = String.TrimLeft(rPath, nil);
                    ListBox.AddItem("Playlist", String.SplitPath(r2Path).Filename..String.SplitPath(r2Path).Extension, r2Path);
                end
            end
        end
    end
end

¿La solución? Eh, eso no debería requerir mucha explicación.

Al usar nuestro sitio, usted reconoce que ha leído y comprende nuestra Política de Cookies y Política de Privacidad.
Licensed under cc by-sa 3.0 with attribution required.