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

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

    +74

    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
    public class BeanWrapperImpl extends AbstractPropertyAccessor implements BeanWrapper {
             @SuppressWarnings("unchecked")
             private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
    		String propertyName = tokens.canonicalName;
    		String actualName = tokens.actualName;
    
    		if (tokens.keys != null) {
    			// Apply indexes and map keys: fetch value for all keys but the last one.
    			PropertyTokenHolder getterTokens = new PropertyTokenHolder();
    			getterTokens.canonicalName = tokens.canonicalName;
    			getterTokens.actualName = tokens.actualName;
    			getterTokens.keys = new String[tokens.keys.length - 1];
    			System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
    			Object propValue;
    			try {
    				propValue = getPropertyValue(getterTokens);
    			}
    			catch (NotReadablePropertyException ex) {
    				throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
    						"Cannot access indexed value in property referenced " +
    						"in indexed property path '" + propertyName + "'", ex);
    			}
    			// Set value for last key.
    			String key = tokens.keys[tokens.keys.length - 1];
    			if (propValue == null) {
    				throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
    						"Cannot access indexed value in property referenced " +
    						"in indexed property path '" + propertyName + "': returned null");
    			}
    			else if (propValue.getClass().isArray()) {
    				PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
    				Class requiredType = propValue.getClass().getComponentType();
    				int arrayIndex = Integer.parseInt(key);
    				Object oldValue = null;
    				try {
    					if (isExtractOldValueForEditor()) {
    						oldValue = Array.get(propValue, arrayIndex);
    					}
    					Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
    							new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType));
    					Array.set(propValue, arrayIndex, convertedValue);
    				}
    				catch (IndexOutOfBoundsException ex) {
    					throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
    							"Invalid array index in property path '" + propertyName + "'", ex);
    				}
    			}
    			else if (propValue instanceof List) {
    				PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
    				Class requiredType = GenericCollectionTypeResolver.getCollectionReturnType(
    						pd.getReadMethod(), tokens.keys.length);
    				List list = (List) propValue;
    				int index = Integer.parseInt(key);
    				Object oldValue = null;
    				if (isExtractOldValueForEditor() && index < list.size()) {
    					oldValue = list.get(index);
    				}
    				Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
    						new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType));
    				if (index < list.size()) {
    					list.set(index, convertedValue);
    				}
    				else if (index >= list.size()) {
    					for (int i = list.size(); i < index; i++) {
    						try {
    							list.add(null);
    						}
    						catch (NullPointerException ex) {
    							throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
    									"Cannot set element with index " + index + " in List of size " +
    									list.size() + ", accessed using property path '" + propertyName +
    									"': List does not support filling up gaps with null elements");
    						}
    					}
    					list.add(convertedValue);
    				}
    			}
    			else if (propValue instanceof Map) {
    			      //...
                             }
                      }
             }
    }

    Spring...

    nikelin, 12 Апреля 2011

    Комментарии (10)
  3. Куча / Говнокод #5555

    +74

    Pony!

    xXx_totalwar, 06 Февраля 2011

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

    +74

    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
    @Name("solr")
    @AutoCreate
    public class SolrClient {
        @Create
        public void init() {
            try {
                server = startRemoteSolr();
            } catch (Exception e) {
                log.error(e, e);
            }
        }
    
        public SolrServer startRemoteSolr() throws MalformedURLException, SolrServerException {
            CommonsHttpSolrServer solr = new CommonsHttpSolrServer("http://localhost:8983/solr");
            solr.setRequestWriter(new BinaryRequestWriter());
            return solr;
        }
    
    }

    Seam. Перевод для непричастного: на старте сайта вызывается метод startRemoteSolr(). Solr - это поисковый движок. Если он не запустится, на сайте не будет работать поиск. И если на запуске Solr будет ошибка, то в лог она попадёт просто как exception + stack trace.

    Что не так в коде? Очевидно, его писали люди, не задумываясь об эксплуатации, что свойственно новичкам. А ведь устранение проблем в рабочем сайте - это приоритет номер один. Сама разработка сайта, сидя в удобном кресле с кашкой кофе - где-то сильно ниже.

    Так вот, что не так?

    1. При выводе ошибок надо писать - что это за ошибка. В данном случае: "Запуск поисковика неудался, ПОИСК НА САЙТЕ РАБОТАТЬ НЕ БУДЕТ." И уже потом - stack trace.

    2. Если некая ошибка связана с ресурсами - сетевыми, или на файловой системе, в логе надо также описывать этот ресурс. Т.е. "Не удалось запустить клиент поисковика по адресу http://localhost:8983/solr". Что бы из логов сразу было видно, что порт указан правильно или нет, хост и тд.

    Но выпускникам ВМК МГУ такие вещи неведомы, они слишком крутые что бы опускаться до таких мелочей. Чайники, хуле.

    yvu, 12 Января 2011

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

    +74

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    cmd = new byte[2]; //name length
    is.read(cmd);
    int fnamel = cmd[0] << 8 | cmd[1];
    cmd = new byte[fnamel];
    is.read(cmd);
    char[] name = byteToChar(cmd);
    cmd = new byte[4];
    is.read(cmd);
    len = (cmd[0] << 24 & 0xFF000000) | (cmd[1] << 16 & 0xFF0000) | (cmd[2] << 8 & 0xFF00) | (cmd[3] & 0xFF);
    System.out.println("FIO requested: "+new String(name)+"; Size: "+len+" bytes;");

    писал (и пишу уже 1 час (планирую через час же закончить)) микро-сетевой аплоадер файлов.

    danilissimus, 23 Октября 2010

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

    +74

    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
    public void reset() {
    			if (types.size() > 0) {
    				for (int i = 0; i < types.size(); i++) {
    					if (types.get(i).getChequeTypeId().equals(1L)) {
    						if (parent.getItemCount() > i
    								&& parent.getSelectedIndex() != i) {
    							parent.setSelectedIndex(i);
    						}
    						if (selectedType == null)
    							selectedType = getElementAt(i).toString();
    						return;
    					}
    				}
    				parent.setSelectedIndex(0);
    				if (selectedType == null)
    					selectedType = getElementAt(0).toString();
    			}
    }

    Код из реального java SE проекта:)
    types это ArrayList со всеми типами валют; в данном методе устанавливается валюта по умолчанию - рубли:)

    vov4a, 10 Сентября 2010

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

    +74

    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
    public static int count(String s) {
        int res = 0;
        for (int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == '1') res++;
        }
        return res;
    }
    
    public List<VDictLiability> get(String currency_id, String usedTrailer, Date actualDate, String contract_class_id, String product_id, String risk_object_type_id) {
        for(int i = 0;i<5;i++){
            int j = 0;
            while(j < 32) {
                if(count(Integer.toBinaryString(j)) == i) {
                    String s = Integer.toBinaryString(j);
                    while (s.length() != 5) {
                        s = "0" + s;
                    }
                    List<VDictLiability> result = get(currency_id, usedTrailer, actualDate, contract_class_id, product_id, risk_object_type_id, s);
                    if(result.size() > 0) return result;
                }
                j++;
            }
        }
        return Collections.EMPTY_LIST;
    }
    
    public List<VDictLiability> get(String currency_id, String usedTrailer, Date actualDate, String contract_class_id, String product_id, String risk_object_type_id, String mask) {
        String territoryCode = App.config.getCurrentBrunchCode().substring(1, 3);
        
    ...
        
        HashMap<Double, VDictLiability> map = new HashMap<Double, VDictLiability>();
        for (VDictLiability liabilityRow : get()) {
            if(!territoryType.equals(liabilityRow.getterritory_type_id()) && !(mask.charAt(4) == '1' && liabilityRow.getterritory_type_id() == null)){
                continue;
            }
            if(actualDate != null && !CompareUtil.isInside(liabilityRow.getstart_date(), liabilityRow.getend_date(), actualDate)){
                continue;
            }
            if(((risk_object_type_id != null && !CompareUtil.isEquals(liabilityRow.getrisk_object_type_id(), risk_object_type_id)) && !(mask.charAt(0) == '1' && liabilityRow.getrisk_object_type_id() == null))){
                continue;
            }
            if(((product_id != null && !CompareUtil.isEquals(liabilityRow.getproduct_id(), product_id)) && !(mask.charAt(1) == '1' && liabilityRow.getproduct_id() == null))){
                continue;
            }
            if(((contract_class_id != null && !CompareUtil.isEquals(liabilityRow.getcontract_class_id(), contract_class_id)) && !(mask.charAt(2) == '1' && liabilityRow.getcontract_class_id() == null))){
                continue;
            }
            if((liabilityRow.getcurrency_id() != null & !CompareUtil.isEquals(liabilityRow.getcurrency_id(), currency_id)) && !(mask.charAt(3) == '1' && liabilityRow.getcurrency_id() == null)){
                continue;
            }
            if(liabilityRow.getis_used_trailer() != SQLUtils.NULL_INTEGER_VALUE & !CompareUtil.isEquals(""+liabilityRow.getis_used_trailer(), usedTrailer)){
                continue;
            }
            map.put(liabilityRow.getvalue(), liabilityRow);
        }
        
        ArrayList<VDictLiability> result = new ArrayList<VDictLiability>();
        result.addAll(map.values());
    ...
        return result;
    }
    
    public List<VDictLiability> get(String currency_id, boolean usedTrailer, Date actualDate, String contract_class_id, String product_id, String risk_object_type_id) {
        return get(currency_id, usedTrailer?"1":"0", actualDate, contract_class_id, product_id, risk_object_type_id);
    }

    Это ад

    borka, 03 Августа 2010

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

    +74

    1. 1
    for (Integer i = 0; i<_pwiList.size(); i++)

    Вот к чему приводит бездумное использование классов-обёрток "для унификации". Конечно, оптимизатор может здесь сообразить, но не факт. А если данный фрагмент трактовать буквально, то i++ приведёт к unboxing, увеличению и последующему boxing.

    konsoletyper, 30 Июля 2010

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

    +74

    1. 1
    2. 2
    3. 3
    public static int indexOf(String str, String... array) {
    		return ArrayUtils.indexOf(array, str);
    }

    cdf_easy, 07 Июля 2010

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

    +74

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    protected void setPhones(ArrayList<MBPhone> phones) {
        if(phones!=null) 
            this.phones=phones;
        else 
            phones.clear();
    }

    Код из одного западного вэб-сервиса для профессионалов в сфере недвижимости.
    Мораль: не надо игнорировать подсказки IDE. Автор на самом деле хотел очистить this.phones. И Intelij Idea подсказывает, что в этом месте может быть брошен NullPointerException. Увидеть эту проблему можно было только используя аннотацию @SuppressWarnings. Потому что варнингов так много, что различить среди них опасные очень сложно.

    vladimir.loshchin, 10 Июня 2010

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

    +74

    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
    private void StreamToBytes()throws Exception
        {
            int i;
            InputStream in=getStream();
            ArrayList<Integer> byt=new ArrayList<Integer>();
            while((i=in.read())!=-1)
            {
                byt.add(i);
            }
            in.close();
            b=new byte[byt.size()];
            for(int j=0;j<b.length;j++)
            {
                b[j]=byt.get(j).byteValue();
            }
        }

    хуита, 04 Июня 2010

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