1. Java / Говнокод #14405

    +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
    if (myTransactions
            .get(i)
            .getTransactionType()
            .name()
            .compareToIgnoreCase(
                    com.mycompany.myproject.common.TransactionType.ENTER
                            .name()) == 0
            || myTransactions
                    .get(i)
                    .getTransactionType()
                    .name()
                    .compareToIgnoreCase(
                                com.mycompany.myproject.common.TransactionType.ENTER_AGAIN
                                        .name()) == 0) {
    
        BigDecimal fee = myTransactions.get(i).
                .getAmount().subtract(
                        myTransactions.get(i)
                                .getContribution());
    // ...
    }
    
    // Notes by Wissenstein
    //
    // package com.mycompany.myproject.common;
    // public enum TransactionType {
    //     ENTER, ENTER_AGAIN, GET, GIVE
    // }
    // ...
    // public class Transaction {
    // ...
    //     public TransactionType getTransactionType() {
    // ...
    //     }
    // }
    // ...
    // List<Transaction> myTransactions;
    // ...
    // P.S. Идентификаторы изменены.

    К тому, что myTransactions.get(i) повторяется, я уже привык и рефакторю это одним махом.
    Однако использованный здесь метод сравнения значений типа enum меня озадачил…

    wissenstein, 23 Января 2014

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

    +174

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    8. 8
    9. 9
    static String asHex(int i){
    		return
    			Joiner.on( " " ).join(
    				Splitter.fixedLength( 4 ).split(
    					String.format("%s8", Integer.toHexString(i))
    						.replace(' ', '0')
    				)
    			);
    }

    LINQ-мышление в жабе.

    3.14159265, 23 Января 2014

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

    −131

    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
    [self
            performSelectorOnMainThread: @selector(_blockCaller:)
            withObject: ^{
                [self _reportAchievement:achievement listener:listener];
            }
            waitUntilDone: YES
        ];
    
    <...>
    
    - (void) _blockCaller:(void(^)())blockHandler {
        blockHandler();
    }

    GCD не в моде.

    krypt, 23 Января 2014

    Комментарии (5)
  4. JavaScript / Говнокод #14402

    +156

    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
    function search(url,param)
                    {
                            $("#rightContent").hide()
                            setBlock("Загрузка")
                            loadLeftMenu()
                            $("#content").load("/search", function(response, status, xhr){
                                $("#Subscription").show()
                                    queryStr=param.split("&")
    
                                    if (queryStr.length==2){
                                            str=(queryStr[0]).replace("querystr=","")
                                            $("#querystr").val(decodeURI(str.replace(/\+/g," ")))
                                            region=((queryStr[1]).replace("region=","")).split(",")
                                            replaceItemInArray(region,"59","59,81")
                                            removeFromArray(region,'81')
                                            replaceItemInArray(region,"75","75,80")
                                            removeFromArray(region,'80')
                                            updateMultiselect("#region", region, "region")
                                    }
                                    if (queryStr.length==3){
                                            str=(queryStr[1]).replace("querystr=","")
                                            $("#querystr").val(decodeURI(str.replace(/\+/g," ")))
                                            region=((queryStr[2]).replace("region=","")).split(",")
                                            replaceItemInArray(region,"59","59,81")
                                            removeFromArray(region,'81')
                                            replaceItemInArray(region,"75","75,80")
                                            removeFromArray(region,'80')
                                            updateMultiselect("#region", region, "region")
                                    }
                                    if (queryStr.length==4){
                        str=(queryStr[0]).replace("querystr=","")
                        $("#querystr").val(decodeURI(str.replace(/\+/g," ")))
    
                        region=((queryStr[1]).replace("region=","")).split(",")
    
                        if (queryStr[2]=='fz94=true'){
                          $('#fz94').attr('checked','checked')
                        }else{
                          $('#fz94').removeAttr('checked')
                        }
    
                        if (queryStr[3]=='fz223=true'){
                          $('#fz223').attr('checked','checked')
                        }else{
                          $('#fz223').removeAttr('checked')
                        }
                                            
                                            replaceItemInArray(region,"59","59,81")
                                            removeFromArray(region,'81')
                                            replaceItemInArray(region,"75","75,80")
                                            removeFromArray(region,'80')
                                            
                                            updateMultiselect("#region", region, "region")
                                    }
                    if (queryStr.length==5){
                        str=(queryStr[1]).replace("querystr=","")
                        $("#querystr").val(decodeURI(str.replace(/\+/g," ")))
    
                        region=((queryStr[2]).replace("region=","")).split(",")
    
                        if (queryStr[3]=='fz94=true'){
                            $('#fz94').attr('checked','checked')
                        }else{
                            $('#fz94').removeAttr('checked')
                        }
    
                        if (queryStr[4]=='fz223=true'){
                            $('#fz223').attr('checked','checked')
                        }else{
                            $('#fz223').removeAttr('checked')
                        }
    
                        replaceItemInArray(region,"59","59,81")
                        removeFromArray(region,'81')
                        replaceItemInArray(region,"75","75,80")
                        removeFromArray(region,'80')
    
                        updateMultiselect("#region", region, "region")
                    }
    
    // Ну и так далее

    Разбор строки запроса

    hdkeeper, 23 Января 2014

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

    +69

    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
    String response = HttpLoader.loadString(params[0]);
    Gson gson = new GsonBuilder().registerTypeAdapter(ArrayList.class,
        new JsonCollectionSerializer<ArrayList<MyClass>>()).
        create();
    
    ArrayList<MyClass> items_generic = new ArrayList<MyClass>() { };
    ArrayList<MyClass> items = gson.fromJson(response, items_generic.getClass().getGenericSuperclass());
    return items;
    
    
    public class JsonCollectionSerializer<E> implements
            JsonSerializer<Collection<E>>, JsonDeserializer<Collection<E>> {
    
        @SuppressWarnings("unchecked")
        public Collection<E> deserialize(JsonElement element, Type type,
                                         JsonDeserializationContext context) throws JsonParseException {
            JsonArray items = element.getAsJsonArray();
            ParameterizedType deserializationCollectionType = ((ParameterizedType) type);
            Type collectionItemType = deserializationCollectionType.getActualTypeArguments()[0];
            Collection<E> list = null;
    
            try {
                list = (Collection<E>) ((Class<?>) deserializationCollectionType.getRawType()).newInstance();
                for (JsonElement e : items) {
                    list.add((E) context.deserialize(e, collectionItemType));
                }
            } catch (InstantiationException e) {
                throw new JsonParseException(e);
            } catch (IllegalAccessException e) {
                throw new JsonParseException(e);
            }
    
            return list;
        }
    }

    Жабоблядство и шаблоны и генерики:
    Чтение из json в коллекцию с шаблонным параметризованным типом.

    chtulhu, 23 Января 2014

    Комментарии (23)
  6. PHP / Говнокод #14400

    +159

    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
    class CHTMLFormGenerator {
    
    	...
    
    	public $formName;
    	const formName = 'form';
    	
    	function GetFormName() {
    		if(isset($this) && $this -> formName)
    			return $this -> formName;
    		else
    			return self::formName;
    	}
    
    	...
    
    }

    clauclauclau, 23 Января 2014

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

    +71

    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
    private byte[] readBytes(InputStream pInputStream, int pLength, int pRetryCounter) throws IOException, WhateverException
    {
        byte[] bytes = new byte[pLength];
        int bytesRead= pInputStream.read(bytes, 0,pLength);
    
        if (bytesRead == -1)
        {
            throw new WhateverException("End of InputStream has been reached");
        }
    
        if (pLength != bytesRead)
        {
            byte[] bytesReadNextAttempt = readBytes(pInputStream, pLength-bytesRead, pRetryCounter + 1);
            if (pLength != bytesRead + bytesReadNextAttempt.length)
            {
                // less bytes available; connection was closed
                throw new WhateverException( ... );
            }
            System.arraycopy(bytesReadNextAttempt, 0, bytes, bytesRead, bytesReadNextAttempt.length);
        }
        return bytes;
    }

    поддержка паршиал ресив. такого "метода" я еще не видел.

    ЗЫ а че в жабе нету никакого MSG_WAITALL?

    Dummy00001, 22 Января 2014

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

    +9

    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
    #include <iostream>
    #include <iterator>
    #include <algorithm>
    #include <array>
    #include <memory>
    using namespace std;
    
    template<size_t N1, size_t N2, class T1, class T2,
    class T = typename common_type<T1, T2>::type>
    T (*concatCArray(const T1(&arr1)[N1], const T2(&arr2)[N2]))[N1+N2]{
      const auto result = (T(*)[N1+N2]) new T[N1+N2];
      copy(arr2, end(arr2), copy(arr1, end(arr1), *result));
      return result;
    }
    template<std::size_t N, class T>
    void viewCArrayPtr(T (*arr)[N]){
      copy(*arr, end(*arr), ostream_iterator<T>(cout, " "));
    }
    template<size_t N1, size_t N2, class T1, class T2,
    class T = typename remove_const<typename common_type<T1, T2>::type>::type>
    array<T, N1+N2> concatArray(const array<T1, N1> &arr1, const array<T2, N2> &arr2){
      array<T, N1+N2> result;
      copy(begin(arr2), end(arr2), copy(begin(arr1), end(arr1), result.begin()));
      return result;
    }
    template<std::size_t N, class T>
    void viewArray(const array<T, N> arr){
      copy(begin(arr), end(arr), ostream_iterator<T>(cout, " "));
    }
    
    int main() {
      int arr1[]{0,1,2,3}, arr2[]{4,5,6};
      auto ca = concatCArray(arr1, arr2);
      unique_ptr<int[]> safe(*ca);
      viewCArrayPtr(ca);
      cout<<endl;
      array<float, 2> a {1,2.5};
      array<int, 3> b{3, 4, 5};
      viewArray(concatArray(a, b));
      return 0;
    }

    От туда.
    http://ideone.com/3KjycI

    LispGovno, 22 Января 2014

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

    +4

    1. 1
    2. 2
    3. 3
    namespace std
    {
      template<class T, class T2> class common_type<::std::shared_ptr<T>, ::std::shared_ptr<T2> >: public ::std::common_type<T, T2>{};

    LispGovno, 22 Января 2014

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

    +3

    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
    class Base
    {
      void fooo() { ... }
    };
    class Derived
    {
      void fooo() { ... }
    };
    void DoSmth (Base& b)
    {
      b.fooo();
    };
    Derived d; 
    DoSmth(d); // полная статика, так что там внутри вызовется метод базы
    void DoSmth (polymorth<Base>& b) // это структура, которая хранит ссылку на объект и ссылку на таблицу методов
    {
      b.fooo();
    };
    polymorth<Base>b = Derived(); 
    // инициализация при объявлении, чтобы было понятно, сколько памяти выделить
    // в структуре записалась таблица методов Derived
    DoSmth(b);  // вызовется метод наследника
    ...
    // в конце вызывается деструктор наследника

    Творчество оттуда.
    "Основная идея - избавить от вопроса "делать ли деструктор виртуальным"

    LispGovno, 22 Января 2014

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