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

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

    +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
    private static File getTmpOutputFile(VirtualFile file) {
            String origPath = file.getRealFile().getAbsolutePath();
            File tmp = new File(origPath + ".tmp");
    
            // If the temp file already exists
            if (tmp.exists()) {
                long tmpLastModified = tmp.lastModified();
                long now = System.currentTimeMillis();
    
                // If the temp file is older than the destination file, or if it is
                // older than the allowed compression time, it must be a remnant of
                // a previous server crash so we can overwrite it
                if (tmpLastModified < file.lastModified()) {
                    return tmp;
                }
                if (now - tmpLastModified > PluginConfig.maxCompressionTimeMillis) {
                    return tmp;
                }
    
                // Otherwise it must be currently being written by another thread,
                // so wait for it to finish
                while (tmp.exists()) {
                    if (System.currentTimeMillis() - now > PluginConfig.maxCompressionTimeMillis) {
                        throw new PressException("Timeout waiting for compressed file to be generated");
                    }
    
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                }
    
                // Return null to indicate that the file was already generated by
                // another thread
                return null;
            }
    
            return tmp;
        }

    Самый вредный говнокод, который я встречал за последний год.
    При определённых условиях может так случиться, что он ждёт (до 60 секунд!), пока предыдущий временный файл не исчезнет. Он не пытается его удалить, не пытается создать новый файл, ничего не логирует - он просто ждёт, пока файл сам исчезнет.

    И у меня как раз так и случилось - из-за совпадения разных событий файл не удалялся, метод ждал 60 секунд, но за это время валились совсем другие вещи по таймауту, и ушло много времени на то, чтобы понять, где же настоящая проблема.

    И весь этот геморрой можно было бы благополучно заменить всего-навсего одной сточкой:
    return File.createTempFile(origPath, "tmp");

    Исходник - плагин play-press:
    https://github.com/dirkmc/press/blob/master/app/press/io/OnDiskCompressedFile.java

    asolntsev, 21 Января 2015

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

    +74

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    private void showProgress() {
        if(mIndProgressVisible && mIndProgress != null && mIndProgress.isShowing()) return;
        if(!mIndProgressVisible && (mIndProgress == null || !mIndProgress.isShowing())) return;
    
        ...
    }

    Не ходите, дети, в Африку гулять

    StanDalone, 30 Декабря 2014

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

    +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
    configRequestTasks = new ConfigRequestRepeatingTask[]{
                    new ConfigRequestRepeatingTask<ApplicationStateModel.ApplicationState>(this) {
                        @Override
                        protected BaseConfigRequest<ApplicationStateModel.ApplicationState> createRequest() {
                            return new ApplicationStateRequest();
                        }
    
                        @Override
                        public ObjectSetting<ApplicationStateModel.ApplicationState> getConfigSetting() {
                            return Config.ApplicationState;
                        }
                    },
                    new ConfigRequestRepeatingTask<MessagesConfigurationModel.MessagesConfiguration>(this) {
                        @Override
                        protected BaseConfigRequest<MessagesConfigurationModel.MessagesConfiguration> createRequest() {
                            return new MessagesConfigurationRequest();
                        }
    
                        @Override
                        public ObjectSetting<MessagesConfigurationModel.MessagesConfiguration> getConfigSetting() {
                            return Config.MessagesConfiguration;
                        }
                    },
                    new ConfigRequestRepeatingTask<HandsetConfigurationModel.FeatureConfiguration>(this) {
                        @Override
                        protected BaseConfigRequest<HandsetConfigurationModel.FeatureConfiguration> createRequest() {
                            return new FeatureConfigurationRequest();
                        }
    
                        @Override
                        public ObjectSetting<HandsetConfigurationModel.FeatureConfiguration> getConfigSetting() {
                            return Config.FeatureConfiguration;
                        }
                    },
                    new ConfigRequestRepeatingTask<FeaturesDetailsModel.FeaturesDetails>(this) {
                        @Override
                        protected BaseConfigRequest<FeaturesDetailsModel.FeaturesDetails> createRequest() {
                            return new FeaturesDetailsRequest();
                        }
    
                        @Override
                        public ObjectSetting<FeaturesDetailsModel.FeaturesDetails> getConfigSetting() {
                            return Config.FeaturesDetails;
                        }
                    },
                    new ConfigRequestRepeatingTask<GeoFenceConfigurationModel.GeoFenceConfiguration>(this) {
                        @Override
                        protected BaseConfigRequest<GeoFenceConfigurationModel.GeoFenceConfiguration> createRequest() {
                            return new GeoFenceConfigurationRequest();
                        }
    
                        @Override
                        public ObjectSetting<GeoFenceConfigurationModel.GeoFenceConfiguration> getConfigSetting() {
                            return Config.GeoFenceConfiguration;
                        }
                    },
     ...

    Вот так мы создаем "очередь" запросов. И это только треть.

    TeTroTro, 04 Декабря 2014

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

    +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
    if (convertView == null || convertView != null) {
                    if (Position2.get(position)) {
                        t.setVisibility(0);
                        b.setVisibility(4);
                        mlp.setMargins(15, 0, 60, 0);
                        y.setBackgroundColor(getResources().getColor(R.color.app_text_white));
                    } else {
                        mlp.setMargins(60, 0, 15, 0);
                        t.setVisibility(4);
                        b.setVisibility(0);
                        y.setBackgroundColor(getResources().getColor(R.color.app_text_white));                    
                    }
                } else {
                    view = convertView;
                }

    Индусы

    vinnizp, 25 Ноября 2014

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

    +74

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    public static void main(String[] args) throws Exception {
        ...
        try {
            Signature.getInstance("NONEwithRSA", "SUN");
            throw new Exception("call succeeded");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        System.out.println("OK");
    }

    http://jdk.openjdk-rt.googlecode.com/hg/test/java/security/Signature/NONEwithRSA.java

    Naturlih, 13 Ноября 2014

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

    +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
    // TODO: This is not the smartest way to implement the config
    public int getFileFragmentationLevel() {
      return config.getFileFragmentationLevel();
    }
    
    public void setFileFragmentationLevel(int fileFragmentationLevel) {
      config.setFileFragmentationLevel(fileFragmentationLevel);
    }
    
    public int getStackTraceOutputMethod() {
      return config.getStackTraceOutputMethod();
    }
    
    public void setStackTraceOutputMethod(int stackTraceOutputMethod) {
      config.setStackTraceOutputMethod(stackTraceOutputMethod);
    }
    
    public String getOutputDirectory() {
      return config.getOutputDirectory();
    }
    
    public void setOutputDirectory(String outputDirectory) {
      config.setOutputDirectory(outputDirectory);
    }
    
    // и так для всех филдов (геттеров/сеттеров) объекта config

    https://github.com/cbeust/testng/blob/master/src/main/java/org/testng/reporters/XMLReporter.java
    Ну хоть признаёт.

    Actine, 05 Октября 2014

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

    +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
    url = new URL("http://[FF01:0:0:0:0:0:0:0101]");
    String originalHostName = url.getHost();
    System.out.println(originalHostName);
    if (originalHostName.startsWith("[") && originalHostName.endsWith("]")) {
     i1 = originalHostName.indexOf("[");
     originalHostName = originalHostName.substring(i1 + 1);
     i2 = originalHostName.lastIndexOf("]");
     originalHostName = originalHostName.substring(0, i2);
     if (IPV6REGEX.matcher(originalHostName).matches()) {
      System.out.println(url + " is a ipv6 address");
      String hostName = InetAddress.getByName(originalHostName).getHostAddress().toLowerCase();
      if (hostName.contains(":")) {
       hostName = "[" + hostName + "]";
      }
     }
    }

    Взято отсюда: http://www.pretechsol.com/2013/05/ipv6-java-regular-expression-example.html#.VBtooLn69B0

    0rt, 19 Сентября 2014

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

    +74

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    if ( !( new File( dataFolder + "/Screenshoots" ).exists()
    	    && new File( dataFolder + "/Screenshoots" ).isDirectory() ) )
    		new File( dataFolder + "/Screenshoots" ).mkdir();
    	    
    if ( !( new File( dataFolder + "/Screenshoots/" + step.test.hashCode() ).exists()
    	    && new File( dataFolder + "/Screenshoots/" + step.test.hashCode() ).isDirectory() ) )
    		new File( dataFolder + "/Screenshoots/" + step.test.hashCode() ).mkdir();

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

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

    +74

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    7. 7
    public static void sleep(long millis, int nanos)  throws InterruptedException {
            // ...
            if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
                millis++;
            }
            sleep(millis);
        }

    Системе пофиг сколько конкретно ты указал наносекунд . Всё равно никак не проверишь:)
    Java Oracle, Thread::sleep(long,long)

    SSSandman, 08 Августа 2014

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

    +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
    public final class TimeBasedRollingPolicy extends RollingPolicyBase 
    ...
    private int suffixLength = 0;
    ...
    
    public void  activateOptions() {
    ....
        if (lastFileName.endsWith(".gz")) {
          suffixLength = 3;
        } else if (lastFileName.endsWith(".zip")) {
          suffixLength = 4;
        }
    }
    
    public RolloverDescription  rollover(final String currentActiveFile) {
    ...
        if (suffixLength == 3) {
          compressAction =
            new GZCompressAction(
              new File(lastBaseName), new File(lastFileName), true);
        }
    
        if (suffixLength == 4) {
          compressAction =
            new ZipCompressAction(
              new File(lastBaseName), new File(lastFileName), true);
        }
    
    ...
    }
    
    }

    Log4j

    Alex512, 11 Июля 2014

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