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

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

    +73

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    public static <T extends Comparable<T>> boolean isLessThan(T a, T b, double numericTolerance) {
        if (a == null) {
            return b != null;
        }
        boolean isLessThan = a.compareTo(b) < 0;
        if (!isLessThan && a instanceof Number && b instanceof Number) {
            isLessThan = ((Comparable) (((Number) a).doubleValue() - numericTolerance)).compareTo(((Number) b).doubleValue()) < 0;
        }
        return isLessThan;
    }

    Один из методов сравнения значений в пределах допустимой погрешности (последняя только для чисел).
    Вроде бы и проще никак, но чувство говна не покидает. Советы по упрощению приветствуются.

    Actine, 16 Сентября 2014

    Комментарии (5)
  3. Java / Говнокод #16646

    +73

    1. 1
    Class <? extends Object> currentClass = Class.forName( clazz )

    Продолжаем разговор...

    sakkath, 05 Сентября 2014

    Комментарии (3)
  4. Java / Говнокод #16471

    +73

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    Integer pageNumber = firstPosition / pageSize;
    if (firstPosition % pageSize != 0 || pageNumber == 0) {
      pageNumber++;
    }
    personFilter.setPageNumber(pageNumber - 1);

    Магия пейдженации

    forn, 04 Августа 2014

    Комментарии (0)
  5. Java / Говнокод #16347

    +73

    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
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    import java.awt.AWTEvent;
    import java.awt.Component;
    import java.awt.event.MouseEvent;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.swing.JLayeredPane;
    
    public class ContainerOperations extends JLayeredPane {
    	private static final long serialVersionUID = 1L;
    
    	private CardPositionInContainer cardPosition;
    	private List<Card> rem = new ArrayList<Card>();	
    	
    	public List<Card> getRem() {
    		return rem;
    	}
    
    	public ContainerOperations() {
    		enableEvents(AWTEvent.MOUSE_EVENT_MASK);
    	}
    
    	public void addFromListInToContainer(List<Card> list) {
    		if (getComponentCount() == 0)
    			addInToEmpty(list);
    		else
    			appendIfContains(list);
    	}
    
    	private void appendIfContains(List<Card> list) {
    		int fromIndex = highestLayer() + 1;
    		int toIndex = highestLayer() + 1 + list.size();
    		appendFromLayerToLayer(list, fromIndex, toIndex);
    	}
    
    	private void addInToEmpty(List<Card> list) {
    		int fromIndex = 0;
    		int toIndex = list.size();
    		cardPosition.setCardPosition(0);
    		appendFromLayerToLayer(list, fromIndex, toIndex);
    	}
    
    	private void appendFromLayerToLayer(List<Card> list, int fromIndex,
    			int toIndex) {
    		int listIndex = 0;
    		for (int layer = fromIndex; layer < toIndex; layer++) {
    			Card card = list.get(listIndex++);
    			cardPosition.setCardPosition(layer);
    			card.setLocation(cardPosition.getCardPosition());
    			add(card, new Integer(layer));
    		}
    	}
    	
    	@Override
    	protected void processMouseEvent(MouseEvent e) {
    		rem.clear();
    		if (e.getID() == MouseEvent.MOUSE_PRESSED) {
    			Component comp = getComponentAt(e.getPoint());
    			addInToRemListIfMousePressed(comp);
    		} 
    	}
    
    
    	private void  addInToRemListIfMousePressed(Component comp){
    		if (comp instanceof Card) {
    			Component mark = (Card) comp;
    			int markedLayer = getMarkedLayer(mark);
    			addInToRemList(markedLayer);		
    		}
    	}
    	
    	private Integer getMarkedLayer(Component marked) {
    		return getComponentCount() - getComponentZOrder(marked) - 1;
    	}
    
    	private void addInToRemList(int layerOfmark) {
    		for (int i = layerOfmark; i < highestLayer() + 1; i++) {
    			Component[] card = getComponentsInLayer(i);
    			rem.add((Card) card[0]);
    		}
    	}
    
    }

    spivti, 15 Июля 2014

    Комментарии (0)
  6. Java / Говнокод #16277

    +73

    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
    @SuppressWarnings("unchecked")
    	private <T> T convert(final String p, final Class<T> type) {
    		if (p == null) {
    			return null;
    		}
    		if (type == String.class) {
    			return (T) String.valueOf(p);
    		} else if (type == Integer.class) {
    			return (T) Integer.valueOf(p);
    		} else if (type == Boolean.class) {
    			return (T) Boolean.valueOf(p);
    		} else if (type == Double.class) {
    			return (T) Double.valueOf(p);
    		} else if (type == Long.class) {
    			return (T) Long.valueOf(p);
    		} else if (type == Float.class) {
    			return (T) Float.valueOf(p);
    		} else if (type == Short.class) {
    			return (T) Short.valueOf(p);
    		} else if (type == Byte.class) {
    			return (T) Byte.valueOf(p);
    		}
    		throw new UnsupportedOperationException(String.format("Cannot convert \"%s\" to %s", p, type));
    	}

    распарсь мне строку...

    Lure Of Chaos, 04 Июля 2014

    Комментарии (32)
  7. Java / Говнокод #16193

    +73

    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
    // Current Month Days
                for (int i = 1; i <= _nDaysInMonth; i++) {
                    if (_myPrefs.getIfConfigured()) {
                        if (_regionWithHolidays != null && _regionWithHolidays.length > 0) {
    
                            String holidayDateStringFormat = String.valueOf(i) + "-" + getMonthAsString(nCurrentMonth) + "-" + _strCurrentSelectedYear;
                            for (int index = 0; index < _regionWithHolidays.length; index++) {
                                if (_regionWithHolidays[index].getHolidayDate().equals(holidayDateStringFormat)) {
                                    list.add(String.valueOf(i) + "-RED" + "-" + getMonthAsString(nCurrentMonth) + "-" + yy);
                                }
                            }
                        }
                    }
    
                    if (i == getCurrentDayOfMonth()) {
                        list.add(String.valueOf(i) + "-BLUE" + "-" + getMonthAsString(nCurrentMonth) + "-" + yy);
                    } else {
                        list.add(String.valueOf(i) + "-WHITE" + "-" + getMonthAsString(nCurrentMonth) + "-" + yy);
                        if (_myPrefs.getIfConfigured()) {
                            if (_regionWithHolidays != null && _regionWithHolidays.length != 0) {
                                String otherDates = String.valueOf(i) + "-" + getMonthAsString(nCurrentMonth) + "-" + _strCurrentSelectedYear;
                                for (int index = 0; index < _regionWithHolidays.length; index++) {
                                    if (_regionWithHolidays[index].getHolidayDate().equals(otherDates)) {
                                        list.remove(String.valueOf(i) + "-WHITE" + "-" + getMonthAsString(nCurrentMonth) + "-" + yy);
                                    }
                                }
                            }
                        }
                    }
                }
    
                // some code
    
                for (int i = 1; i <= _nDaysInMonth; i++) {
                    String[] day_color = list.get(i).split("-");
                    if (day_color[1].equals("WHITE")) {
                        //active dates in current month
                        dayNumberView.setTextColor(getResources().getColor(R.color.darkGrey_font));
                    } else if (day_color[1].equals("BLUE")) {
                        //current date in current month
                        holder.tvTime.setTextColor(getResources().getColor(R.color.whitetranslucent));
                        dayNumberView.setTextColor(getResources().getColor(R.color.whitetranslucent));
                        cell.setBackgroundResource(R.color.blue_font);
                    } else if (day_color[1].equals("RED")) {
                        //active dates in current month
                        dayNumberView.setTextColor(getResources().getColor(R.color.red));
                    }
                }

    Это приложение с десятками тысяч пользователей. Мне выпала честь править в нем баги. На сколько я могу судить задача этого куска была отобразить календарь на текущий месяц на экране и подсветить WHITE - обычные дни, BLUE - текущий, RED - выходные и праздничные. Итак в чем соль:
    1) сама соль метода - в одном цикле создается список строк вида НОМЕР-ЦВЕТ-МЕСЯЦ-ГОД, чуть ниже в аналогичном цикле эти строки разбиваются по "-" и сравнивается по строковому значению цвета. Кроме того день может быть или текущим или праздничным, но никак не одновременно.
    2) два практически одинаковых куска кода по 10 строк - строки 4-13 и 19-28, первый при определенных условия добавляет ПРАЗДНИЧНЫЙ день в календарь, потом день в 16-18 строках день всегда добавляется еще раз этот день, либо обычный(WHITE) либо текущий(BLUE), и выполняется второй кусок и если проходят те же условия т.е. фактические если был добавлен праздничный день(RED) то удаляется добавленный ОБЫЧНЫЙ день. Баг был в том что если текущий день был еще и праздничным то они задваивались. Сделать по нормальному - если день уже добавлен, не добавлять еще раз или сделать continue главному циклу. Не говоря уже о том чтобы добавить break после 9 строки, видно автор не знал про эти операторы.

    TAX, 19 Июня 2014

    Комментарии (5)
  8. Java / Говнокод #16090

    +73

    1. 001
    2. 002
    3. 003
    4. 004
    5. 005
    6. 006
    7. 007
    8. 008
    9. 009
    10. 010
    11. 011
    12. 012
    13. 013
    14. 014
    15. 015
    16. 016
    17. 017
    18. 018
    19. 019
    20. 020
    21. 021
    22. 022
    23. 023
    24. 024
    25. 025
    26. 026
    27. 027
    28. 028
    29. 029
    30. 030
    31. 031
    32. 032
    33. 033
    34. 034
    35. 035
    36. 036
    37. 037
    38. 038
    39. 039
    40. 040
    41. 041
    42. 042
    43. 043
    44. 044
    45. 045
    46. 046
    47. 047
    48. 048
    49. 049
    50. 050
    51. 051
    52. 052
    53. 053
    54. 054
    55. 055
    56. 056
    57. 057
    58. 058
    59. 059
    60. 060
    61. 061
    62. 062
    63. 063
    64. 064
    65. 065
    66. 066
    67. 067
    68. 068
    69. 069
    70. 070
    71. 071
    72. 072
    73. 073
    74. 074
    75. 075
    76. 076
    77. 077
    78. 078
    79. 079
    80. 080
    81. 081
    82. 082
    83. 083
    84. 084
    85. 085
    86. 086
    87. 087
    88. 088
    89. 089
    90. 090
    91. 091
    92. 092
    93. 093
    94. 094
    95. 095
    96. 096
    97. 097
    98. 098
    99. 099
    100. 100
    int a = 1;
        int b = 2;
        int c = 2;
        String d = " ";
        System.out.print(a+d);
        System.out.print(b+d);
        System.out.print(b+a+d);
        System.out.print(4+d);
        System.out.print(5+d);
        System.out.print(6+d);
        System.out.print(7+d);
        System.out.print(8+d);
        System.out.print(9+d);
        System.out.println(10+d);
        System.out.print(2+d);
        System.out.print(4+d);
        System.out.print(6+d);
        System.out.print(8+d);
        System.out.print(10+d);
        System.out.print(12+d);
        System.out.print(14+d);
        System.out.print(16+d);
        System.out.print(18+d);
        System.out.println(20+d);
        System.out.print(3+d);
        System.out.print(6+d);
        System.out.print(9+d);
        System.out.print(12+d);
        System.out.print(15+d);
        System.out.print(18+d);
        System.out.print(21+d);
        System.out.print(24+d);
        System.out.print(27+d);
        System.out.println(30+d);
        System.out.print(4+d);
        System.out.print(8+d);
        System.out.print(12+d);
        System.out.print(16+d);
        System.out.print(20+d);
        System.out.print(24+d);
        System.out.print(28+d);
        System.out.print(32+d);
        System.out.print(36+d);
        System.out.println(40+d);
        System.out.print(5+d);
        System.out.print(10+d);
        System.out.print(15+d);
        System.out.print(20+d);
        System.out.print(25);
        System.out.print(30+d);
        System.out.print(35+d);
        System.out.print(40+d);
        System.out.print(45+d);
        System.out.println(50+d);
        System.out.print(6+d);
        System.out.print(12+d);
        System.out.print(18+d);
        System.out.print(24+d);
        System.out.print(30+d);
        System.out.print(36+d);
        System.out.print(42+d);
        System.out.print(48+d);
        System.out.print(54+d);
        System.out.println(60+d);
        System.out.print(7+d);
        System.out.print(14+d);
        System.out.print(21+d);
        System.out.print(28+d);
        System.out.print(35+d);
        System.out.print(42+d);
        System.out.print(49+d);
        System.out.print(56+d);
        System.out.print(63+d);
        System.out.println(70+d);
        System.out.print(8+d);
        System.out.print(16+d);
        System.out.print(24+d);
        System.out.print(32+d);
        System.out.print(40+d);
        System.out.print(48+d);
        System.out.print(56+d);
        System.out.print(64+d);
        System.out.print(72+d);
        System.out.println(80+d);
        System.out.print(9+d);
        System.out.print(18+d);
        System.out.print(27+d);
        System.out.print(36+d);
        System.out.print(45+d);
        System.out.print(54+d);
        System.out.print(63+d);
        System.out.print(72+d);
        System.out.print(81+d);
        System.out.println(90+d);
        System.out.print(10+d);
        System.out.print(20+d);
        System.out.print(30+d);
        System.out.print(40+d);
        System.out.print(50+d);
        System.out.print(60+d);

    Пытался таблицу умножения сделать в детстве...

    thematver, 31 Мая 2014

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

    +73

    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
    public static int getWordCount(String getInput, int e){
        int numberOfWords = 0;
        char l1 = 0;
        char l2 = 0;
        StringBuilder convertInput = new StringBuilder(getInput);
        System.out.println(convertInput);
        for (int i = 0, i1 = 1; i < getInput.length();i++, i1++){
            l2 = convertInput.charAt(i);
            if (l2 == ' '){
                numberOfWords += 1;
                l1 = convertInput.charAt(i1);
            }
            if (i == getInput.length() - 1){
                numberOfWords += 1;
            }
            if (l2 == ' ' && l1 == ' '){
                numberOfWords -= 1;
            }
        }
        return numberOfWords;
     } // end of getWordCount method

    http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html да и просто регексп на крайняк как видно запрещены религией.

    kostoprav, 13 Мая 2014

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

    +73

    1. 1
    http://bnw.im/p/JCBN9N

    https://bnw.im/u/j123123

    j123123, 04 Мая 2014

    Комментарии (10)
  11. Java / Говнокод #15751

    +73

    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
    StartElement startElement = event.asStartElement();
    if(startElement.getName().getLocalPart().equals(REPORT)){
    	report = new Report();
    }else if (startElement.getName().getLocalPart().equals(CODE)){
    	event = eventReader.nextEvent();
    	report.setCode(event.asCharacters().getData());
    	continue;
    }else if(startElement.getName().getLocalPart().equals(SHORT_NAME)){
    	event = eventReader.nextEvent();
    	report.setShortName(event.asCharacters().getData());
    }else if(startElement.getName().getLocalPart().equals(NAME)){
    	event = eventReader.nextEvent();
    	report.setName(event.asCharacters().getData());
    	continue;
    }else if(startElement.getName().getLocalPart().equals(TYPE)){
    	event = eventReader.nextEvent();
    	report.setType(ReportType.valueOf(event.asCharacters().getData()));
    	continue;
    }else if(startElement.getName().getLocalPart().equals(CON_CMN_REPORT)){
    	event = eventReader.nextEvent();
    	String conRepCode = event.asCharacters().getData();
    	report.setConnectedCommonReport(getReportByCode(conRepCode, reports));
    	continue;
    }else if(startElement.getName().getLocalPart().equals(BEFORE)){
    	event = eventReader.nextEvent();
    	report.setAvaliableBefore(Boolean.valueOf(event.asCharacters().getData()));
    	continue;
    }else if(startElement.getName().getLocalPart().equals(QUANTITY)){
    	event = eventReader.nextEvent();
    	report.setQuantity(ReportQuantity.valueOf(event.asCharacters().getData()));
    	continue;
    }else if(startElement.getName().getLocalPart().equals(CREATOR_CLASS_NAME)){
    	event = eventReader.nextEvent();
    	report.setCreatorClassName(event.asCharacters().getData());
    }

    и не лень же было

    evg_ever, 14 Апреля 2014

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