- 1
Java говно
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+4
Java говно
+1
public static Date getMinDate(List<Date> dates) {
Preconditions.checkArgument(dates != null && !dates.isEmpty(), "Dates list must be not null and not empty");
dates.sort(Comparator.naturalOrder());
return dates.get(0);
}
ну а че
+2
super(
new TkWithHeaders(
new TkVersioned(
new TkMeasured(
new TkFlash(
new TkAppFallback(
new TkAppAuth(
new TkForward(
new TkFork(
new FkHost(
"relay.jare.io",
new TkFallback(
new TkRelay(base),
req -> new Opt.Single<>(
new RsWithType(
new RsWithBody(
new RsWithStatus(req.code()),
new Sprintf(
Код вполне рабочего проекта
−1
if (userSettingsErrorType != null && userSettingsErrorType.getError() != null &&
userSettingsErrorType.getError().getMessage() != null && userSettingsErrorType.getError().getMessage().getName() != null &&
userSettingsErrorType.getError().getMessage().getName().length != 0) {
try {
getView().ifPresent(v -> v.setFieldErrorMessage(SettingsField.NAME,
userSettingsErrorType.getError().getMessage().getName()[0]));
} catch (Exception e) {
Crashlytics.logException(e);
}
}
наткнулся на сие чудо во время рефакторинга.
0
[code]
protected AbstractPopup init(Project project,
@NotNull JComponent component,
@Nullable JComponent preferredFocusedComponent,
boolean requestFocus,
boolean focusable,
boolean movable,
String dimensionServiceKey,
boolean resizable,
@Nullable String caption,
@Nullable Computable<Boolean> callback,
boolean cancelOnClickOutside,
@Nullable Set<JBPopupListener> listeners,
boolean useDimServiceForXYLocation,
ActiveComponent commandButton,
@Nullable IconButton cancelButton,
@Nullable MouseChecker cancelOnMouseOutCallback,
boolean cancelOnWindow,
@Nullable ActiveIcon titleIcon,
boolean cancelKeyEnabled,
boolean locateByContent,
boolean placeWithinScreenBounds,
@Nullable Dimension minSize,
float alpha,
@Nullable MaskProvider maskProvider,
boolean inStack,
boolean modalContext,
@Nullable Component[] focusOwners,
@Nullable String adText,
int adTextAlignment,
boolean headerAlwaysFocusable,
@NotNull List<? extends Pair<ActionListener, KeyStroke>> keyboardActions,
Component settingsButtons,
@Nullable final Processor<? super JBPopup> pinCallback,
boolean mayBeParent,
boolean showShadow,
boolean showBorder,
Color borderColor,
boolean cancelOnWindowDeactivation,
@Nullable BooleanFunction<KeyEvent> keyEventHandler) {
[/code]
// https://github.com/JetBrains/intellij-community/blob/master/platform/platform-impl/src/com/intellij/ui/popup/AbstractPopup.java
+3
/*
* Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4890726
@summary Check the correctness of KOI8_U by comparing to KOI8_R
*/
import java.util.*;
import static java.lang.Character.UnicodeBlock;
public class UkrainianIsNotRussian {
private static String decode(byte[] bytes, String encoding) throws Throwable {
String s = new String(bytes, encoding);
equal(s.length(), 1);
check(Arrays.equals(s.getBytes(encoding), bytes));
return s;
}
private static void realMain(String[] args) throws Throwable {
final byte[] bytes = new byte[1];
int differences = 0;
for (int i = 0; i < 0xff; i++) {
bytes[0] = (byte) i;
final String r = decode(bytes, "KOI8_R");
final String u = decode(bytes, "KOI8_U");
if (! r.equals(u)) {
differences++;
final char rc = r.charAt(0);
final char uc = u.charAt(0);
final UnicodeBlock rcb = UnicodeBlock.of(rc);
final UnicodeBlock ucb = UnicodeBlock.of(uc);
System.out.printf("%02x => %04x %s, %04x %s%n",
i, (int) rc, rcb, (int) uc, ucb);
check(rcb == UnicodeBlock.BOX_DRAWING &&
ucb == UnicodeBlock.CYRILLIC);
}
}
equal(differences, 8);
}
//--------------------- Infrastructure ---------------------------
static volatile int passed = 0, failed = 0;
static void pass() {passed++;}
static void fail() {failed++; Thread.dumpStack();}
static void fail(String msg) {System.out.println(msg); fail();}
static void unexpected(Throwable t) {failed++; t.printStackTrace();}
static void check(boolean cond) {if (cond) pass(); else fail();}
static void equal(Object x, Object y) {
if (x == null ? y == null : x.equals(y)) pass();
else fail(x + " not equal to " + y);}
public static void main(String[] args) throws Throwable {
try {realMain(args);} catch (Throwable t) {unexpected(t);}
System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed);
if (failed > 0) throw new AssertionError("Some tests failed");}
}
https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/test/jdk/sun/nio/cs/UkrainianIsNotRussian.java
+1
@Override
public String toString() {
return "IndexData{" +
"id='" + id + '\'' +
", regNum='" + regNum + '\'' +
", docType='" + docType + '\'' +
", customerOrg='" + customerOrg + '\'' +
", ownerOrg='" + ownerOrg + '\'' +
", responsibleOrg='" + responsibleOrg + '\'' +
", publishOrg='" + publishOrg + '\'' +
", path='" + path + '\'' +
", zipName='" + zipName + '\'' +
", xmlName='" + xmlName + '\'' +
", fileDate=" + fileDate +
", publishDate='" + publishDate + '\'' +
", info=" + info +
'}';
}
сериализация в json
+1
when {
(defaultCurrency != null) -> {
when {
(currenciesList == null) -> {
currenciesList = mutableListOf(defaultCurrency)
}
(currenciesList?.isEmpty() == true) -> {
currenciesList?.add(defaultCurrency)
}
else -> {
if (currenciesList?.contains(defaultCurrency) == false) {
defaultCurrency = currenciesList?.first()
}
}
}
}
else -> {
when {
((currenciesList == null) || (currenciesList?.isEmpty() == true)) -> {
throw IllegalArgumentException("Default currency and list of currencies from terminal configuration are empty")
}
else -> {
defaultCurrency = currenciesList?.first()
}
}
}
}
Интерн сражается со скобочками.
0
// int limit - кол-во записей на странице
// int current - текущая страница
// int pages - кол-во страниц
// int count - общее кол-во записей
if (limit > 0) {
pages = count / limit;
if (count % limit > 1) {
pages++;
}
if (current != pages) {
if (current >= 1 && current <= pages) {
current = pages / (current + 1);
} else {
current = 1;
}
}
}
Феерическая реализация постраничника от джуна
+3
// https://github.com/TigerVNC/tigervnc/blob/8c6c584377feba0e3b99eecb3ef33b28cee318cb/java/com/jcraft/jsch/Buffer.java#L65-L85
public void putInt(int val) {
tmp[0]=(byte)(val >>> 24);
tmp[1]=(byte)(val >>> 16);
tmp[2]=(byte)(val >>> 8);
tmp[3]=(byte)(val);
System.arraycopy(tmp, 0, buffer, index, 4);
index+=4;
}
public void putLong(long val) {
tmp[0]=(byte)(val >>> 56);
tmp[1]=(byte)(val >>> 48);
tmp[2]=(byte)(val >>> 40);
tmp[3]=(byte)(val >>> 32);
System.arraycopy(tmp, 0, buffer, index, 4);
tmp[0]=(byte)(val >>> 24);
tmp[1]=(byte)(val >>> 16);
tmp[2]=(byte)(val >>> 8);
tmp[3]=(byte)(val);
System.arraycopy(tmp, 0, buffer, index+4, 4);
index+=8;
}
Жабовское байтоебство (судя по всему это такой ntohl) из реализации VNC.
Вот интересно, в жабке-то unsigned типов нет нихера, но почему-то сделали unsigned двоичный сдвиг (>>>), который работает для этих встроенных signed типов как если б это были unsigned. А как насчет unsigned умножения и деления (сложение и вычитание - то один хер, без разницы, если у нас two's complement)?