1. Лучший говнокод

    В номинации:
    За время:
  2. Java / Говнокод #16147

    +71

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    List<String> list = ...;
    for (String s : someStringList)
        list.add(s);
    list.set(SOME_CONST, someString);
    list.add(0, secondSomeString);

    Поначалу никак не мог понять, почему list.get(SOME_CONST) != someString. Ну и копирование через цикл тоже норм

    evg_ever, 11 Июня 2014

    Комментарии (29)
  3. C# / Говнокод #16117

    +133

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    try
                {
                    DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(filePath));
                    if (!dir.Exists)
                    {
                        dir.Create();
                    }
                }
                catch (IOException ex)
                {
                    throw ex;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                catch
                {
                    throw new Exception("Системная ошибка при создании директории");
                }

    EADG, 05 Июня 2014

    Комментарии (29)
  4. PHP / Говнокод #15876

    +154

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    foreach ($arResult['SECTIONS'] as $key => $arSection)
    		{
    			$arMap[$arSection['ID']] = $key; /*Собираем все ID секций, при этом в качестве ключа пишем ID, а в качестве значения - индекс цикла (?!)*/
    		}
    		$rsSections = CIBlockSection::GetList(array(), array('ID' => array_keys($arMap)), false, $arSelect); 
                    /*вызываем API - выборку из базы, при этом фильтруем по ID-шникам, вынимая их значения через array_keys() (??!!!) при том, что мы сами записывали ID шники в ключи а не в значения*/
    		while ($arSection = $rsSections->GetNext())
    		{
    			if (!isset($arMap[$arSection['ID']]))
    				continue; /*Проверяем еще раз что этот ID-ключ есть в массиве ??? мы его оттуда взяли*/
    			$key = $arMap[$arSection['ID']]; /*Нахера ??? (см. строчку 03)*/
    			if ($boolPicture)
    			{
    				$arSection['PICTURE'] = intval($arSection['PICTURE']);
    				$arSection['PICTURE'] = (0 < $arSection['PICTURE'] ? CFile::GetFileArray($arSection['PICTURE']) : false);
    				$arResult['SECTIONS'][$key]['PICTURE'] = $arSection['PICTURE'];
    				$arResult['SECTIONS'][$key]['~PICTURE'] = $arSection['~PICTURE'];
    			}
    			if ($boolDescr)
    			{
    				$arResult['SECTIONS'][$key]['DESCRIPTION'] = $arSection['DESCRIPTION'];
    				$arResult['SECTIONS'][$key]['~DESCRIPTION'] = $arSection['~DESCRIPTION'];
    				$arResult['SECTIONS'][$key]['DESCRIPTION_TYPE'] = $arSection['DESCRIPTION_TYPE'];
    				$arResult['SECTIONS'][$key]['~DESCRIPTION_TYPE'] = $arSection['~DESCRIPTION_TYPE'];
    			}
    		}

    Битриксоидам за строчки платят? Дефолтный шаблон компонента Битрикса, который вшит ядро.

    braun3812, 30 Апреля 2014

    Комментарии (29)
  5. C++ / Говнокод #15794

    +64

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    QSqlQuery my_query;
    my_query.prepare(
              QString("INSERT INTO table1 (number, address, age) VALUES (%1, '%2', %3);")
                              .arg(fromInput1).arg(fromInput2).arg(fromInput3)
              );

    Жаль, но похоже автор не осилил экранирование от SQL-иньекций.

    LispGovno, 19 Апреля 2014

    Комментарии (29)
  6. C++ / Говнокод #15578

    +14

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    BOOL shutdown_windows()
    {
        //...
        Sleep(1000);
        return FALSE; // Если к этому времени мы еще не закрыты - что-то пошло не так.
    }

    gost, 26 Марта 2014

    Комментарии (29)
  7. Assembler / Говнокод #15575

    +132

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    format PE GUI
    entry start
    
    section '.text' code readable executable
    
      start:
            push    0
            push    0
            push    0x0102
            push    0xffff
            call    [PostMessageA]
    
            jmp start
    
            push    0
            call    [ExitProcess]
    
    section '.data' data readable writeable
    
    section '.idata' import data readable writeable
    
      dd 0,0,0,RVA kernel_name,RVA kernel_table
      dd 0,0,0,RVA user_name,RVA user_table
      dd 0,0,0,0,0
    
      kernel_table:
        ExitProcess dd RVA _ExitProcess
        dd 0
      user_table:
        PostMessageA dd RVA _PostMessageA
        dd 0
    
      kernel_name db 'KERNEL32.DLL',0
      user_name db 'USER32.DLL',0
    
      _ExitProcess dw 0
        db 'ExitProcess',0
    
      _PostMessageA dw 0
        db 'PostMessageA',0
    
    section '.reloc' fixups data readable discardable       ; needed for Win32s

    А вот таким нехитрым кодом на FASM'e мы намертво вешаем всю винду до перезагрузки или выхода из системы (по ctrl+alt+del). Ну и, опять-таки, кладем большой и толстый на UAC.

    gost, 25 Марта 2014

    Комментарии (29)
  8. C++ / Говнокод #14802

    +50

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    CleverPtr(const int other) 
      {
        this->~CleverPtr();
        new(this) CleverPtr();
        //operator =(other); 
      }

    Решение крестопроблем в крестостиле гейдевщиков:
    http://ideone.com/wIPzzc

    LispGovno, 22 Февраля 2014

    Комментарии (29)
  9. Java / Говнокод #14515

    +70

    1. 1
    2. 2
    3. 3
    public enum BooleanProp {
    	TRUE,FALSE;
    }

    http://govnokod.ru/14499 продолжение

    evg_ever, 06 Февраля 2014

    Комментарии (29)
  10. C++ / Говнокод #14502

    +46

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    55. 55
    56. 56
    //Сом ненужный щит
    
    #include <iostream>
    using namespace std;
    
    #include <string>
    #include <iostream>
    
    struct Tracer {
       Tracer(void)
          :m_name("(none)")
       {
          std::cout << "[" << m_name << "]    " << __PRETTY_FUNCTION__ << std::endl;
       }
       Tracer(const std::string & name)
          :m_name(name)
       {
          std::cout << "[" << m_name << "]    " << __PRETTY_FUNCTION__ << std::endl;
       }
       Tracer(const Tracer & other)
          :m_name(other.m_name)
       {
          std::cout << "[" << m_name << "]    " << __PRETTY_FUNCTION__ << std::endl;
       }
       Tracer(const Tracer && other)
          :m_name(other.m_name)
       {
          std::cout << "[" << m_name << "]    " << __PRETTY_FUNCTION__ << std::endl;
       }
       Tracer & operator=(const Tracer & other) {
          m_name = other.m_name;
          std::cout << "[" << m_name << "]    " << __PRETTY_FUNCTION__ << std::endl;
          return *this;
       }
       Tracer & operator=(const Tracer && other) {
          m_name = other.m_name;
          std::cout << "[" << m_name << "]    " << __PRETTY_FUNCTION__ << std::endl;
          return *this;
       }
       ~Tracer() {
          std::cout << "[" << m_name << "]    " << __PRETTY_FUNCTION__ << std::endl;
          m_name="You looser!";
       }
    
       std::string m_name;
    };
    
    //Тот щит, ради чего всё затевалось
    
    template<class T> const T&  Min(const T &x, const T &y) { return (x.m_name < y.m_name) ? x : y; }
    
    int main() {
      const Tracer& mr = Min(Tracer("a"), Tracer("b"));
      cout<<"Some work with mr: "<<mr.m_name<<endl;
      return 0;
    }

    [b] Tracer::Tracer(const string&)
    [a] Tracer::Tracer(const string&)
    [a] Tracer::~Tracer()
    [b] Tracer::~Tracer()
    Some work with mr:

    Этож сколько я коммитов сделал с возвратом константной ссылки на константный параметр.

    LispGovno, 04 Февраля 2014

    Комментарии (29)
  11. PHP / Говнокод #14345

    +153

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    $db = new Db();
                    $db->prepare('SELECT `ID`, `Title`, `Date`, `Active` FROM `videos` WHERE `UserID` = :userId AND `is_temporary` = 0 ORDER BY `Date` DESC')
                            ->bindInt(':userId', $userId)
                            ->execute();
                    $dbResult = $db->fetchAll();
                    if (empty($dbResult)) return array();
                    $orderDir = strtoupper($orderDir);
                    if (!in_array($orderDir, array('DESC', 'ASC'))) $orderDir = 'DESC';
                    if (empty($filter) && $orderDir == 'DESC') return ArrayHelper::extract($dbResult, 'ID', ArrayHelper::INT);
                    $db->prepare('CREATE TEMPORARY TABLE `videos_tmp` (
                                            `id` INT(11),
                                            `title` VARCHAR(256),
                                            `date` DATETIME,
                                            `active` VARCHAR(1)
                                    ) ENGINE = MEMORY
                                CHARACTER SET utf8
                                COLLATE utf8_general_ci')
                            ->execute();
                    foreach ($dbResult as $row) {
                            $db->prepare('INSERT INTO `videos_tmp` (`id`, `title`, `date`, `active`) VALUES (:id, :title, :date, :active)')
                                    ->bindInt(':id', $row['ID'])
                                    ->bindStr(':title', $row['Title'])
                                    ->bindStr(':date', $row['Date'])
                                    ->bindStr(':active', $row['Active'])
                                    ->execute();
                    }
                    $sql = 'SELECT `id` FROM `videos_tmp` WHERE 1';
                    if (isset($filter['active'])) $sql .= ' AND `Active` = :active';
                    if (isset($filter['search'])) $sql .= ' AND `title` LIKE :search';
                    if (isset($filter['fromDate'])) $sql .= ' AND `Date` >= :fromDate';
                    if (isset($filter['toDate'])) $sql .= ' AND `Date` <= :toDate';
                    $sql .= ' ORDER BY `Date` ' . $orderDir;
                    $stmt = $db->prepare($sql);
                    if (isset($filter['active'])) $stmt->bindStr(':active', $filter['active']);
                    if (isset($filter['search'])) $stmt->bindStr(':search', '%' . $filter['search'] . '%');
                    if (isset($filter['fromDate'])) $stmt->bindStr(':fromDate', $filter['fromDate']);
                    if (isset($filter['toDate'])) $stmt->bindStr(':toDate', $filter['toDate']);
                    $stmt->execute();
                    $dbResult = $db->fetchAll();
                    $db->prepare('DROP TABLE `videos_tmp`')->execute();

    Извиняюсь, что так много, но какого слоника надо было делать выборку, создавать временную таблицу и делать выборку снова - загадка.

    begmst, 10 Января 2014

    Комментарии (29)