Competition “Laugh or cry?”. Voting
It is time to tally up results of our competition. From all published examples, I have chosen five finalists, which can be found just below. Now you can vote for two examples of a smell code. You can vote up until August, 27.
What is the Worst Code?
- COTOHA’s example (32%, 15 Votes)
- Ikar’s example (36%, 17 Votes)
- Dmytro Shteflyuk’s example (43%, 20 Votes)
- Rage’s example (6%, 3 Votes)
- Peter’s example (43%, 20 Votes)
Total Voters: 47
Our finalists:
-
COTOHA (details)
Language: C#private enum MessageBoxFields
{
CheckBox = 0,
Sender = 1,
SenderAvatar = 2,
Recipient = 3,
RecipientAvatar = 4,
Subject = 5,
FriendRequest = 6,
PendingRequest = 7,
Date = 8,
Time = 9,
Read = 10,
MessageID = 11
}
private void MessageBoxVisibleFields(List<int> ShowFields)
// сюда мы передаем список колонок, которые надо показать в датагриде
{
List<int> AllFields = new List<int>();
// заметте, что ТУТ мы не верим в неявное приведение типов
// поэтому мы юзаем Convert.ToInt32
AllFields.Add(Convert.ToInt32(MessageBoxFields.CheckBox));
AllFields.Add(Convert.ToInt32(MessageBoxFields.Sender));
AllFields.Add(Convert.ToInt32(MessageBoxFields.SenderAvatar));
AllFields.Add(Convert.ToInt32(MessageBoxFields.Recipient));
AllFields.Add(Convert.ToInt32(MessageBoxFields.RecipientAvatar));
AllFields.Add(Convert.ToInt32(MessageBoxFields.Subject));
AllFields.Add(Convert.ToInt32(MessageBoxFields.FriendRequest));
AllFields.Add(Convert.ToInt32(MessageBoxFields.PendingRequest));
AllFields.Add(Convert.ToInt32(MessageBoxFields.Date));
AllFields.Add(Convert.ToInt32(MessageBoxFields.Time));
AllFields.Add(Convert.ToInt32(MessageBoxFields.Read));
AllFields.Add(Convert.ToInt32(MessageBoxFields.MessageID));
// мы только что сформировали список всех колонок ;)
bool flag = false;
List<int> ShowF = new List<int>(); // здесь будут лежать колонки, которые мы покажем.
// да-да те, которые нам передали как параметр 8-/
List<int> HideF = new List<int>(); // а тут те, которые мы спрячем
// глубина этого алгоритма непостижима простому смертному, но я же СОТОНА!
// поэтому я вам всё как есть расскажу
// как в любой задаче по дискретной математике, бежим по матрице
for (int i = 0; i < AllFields.Count; i++) // это столбцы :)
{
for (int j = 0; j < ShowFields.Count; j++) // а тут колонки.
{
if (AllFields[i] == ShowFields[j]) // а тут у нас пересечение.
{
ShowF.Add(ShowFields[j]);
j = ShowFields.Count; // WTF!?!
flag = true; // ДА ЭТО ЖЕ BREAK!!! мама-мия!!!
}
// только за эту реализацию break я требую и оригиналы и переводы
// code complete, the beautiful code, refactoring ну и prefactoring до кучи
}
if (!flag) // ну если пересечение не случилось, то придётся поле спрятать
{
HideF.Add(AllFields[i]);
}
flag = false; // ну да. а вдруг таки случалось пересечение
}
// ну дальше просто детский лепет
// надо просто показать поля, которые надо показать
for (int i = 0; i < ShowF.Count; i++)
{
// помните мы там замечали, что мы не верим в неявное приведение типов?
// так вот мы уверовали! алилуйя!!!
MessagesGridView.Columns[ShowF[i]].Visible = true;
}
// и спрятать те, которые надо спрятать
for (int i = 0; i < HideF.Count; i++)
{
MessagesGridView.Columns[HideF[i]].Visible = false;
}
} - Ikar (details)
Language: Javatry{
temp = new ArrayList();
int i = 0;
while(true){
if((pos = ans[i].indexOf("href=")) == -1) {
i++;
}else{
str = ans[i].substring(pos + 5, ans[i].indexOf(">", pos));
if((pos = str.indexOf("\"")) != -1){
str = str.substring(pos+1, str.indexOf("\"", pos+1));
}
temp.add(str);
i++;
}
}
}catch(IndexOutOfBoundsException ex){} - Dmytro Shteflyuk (details)
Language: Javascript// <!--
function ValidateDate(cyear, cday, cmonth,error)
{
var year = $get(cyear).value;
var day = $get(cday).value;
var month = $get(cmonth).value;
var cerror = $get(error);
if (year==""&&day==""&&month=="")
{
// cerror.innerHTML="Date is invalid. Please, enter a valid date.";
return true;
}
if (year!=""&&day!=""&&month!="")
{
var num1;
var num2;
num1 = new Number(year);
num2 = new Number(day);
if (isNaN(num1)||isNaN(num2))
{
cerror.innerHTML="Date is invalid. Please, enter a valid date.";
return false;
}
if (year<1850)
{
cerror.innerHTML="Date is invalid. Please, enter a valid date.";
return false;
}
if(day<=0)
{
cerror.innerHTML="Date is invalid. Please, enter a valid date.";
return false;
}
if (month<=7)
{
if (month%2==0&& day>30 )
{
cerror.innerHTML="Date is invalid. Please, enter a valid date.";
return false;
}
if (month%2!=0&& day>31)
{
cerror.innerHTML="Date is invalid. Please, enter a valid date.";
return false;
}
}
if (month>7)
{
if (month%2==0&& day>31)
{
cerror.innerHTML="Date is invalid. Please, enter a valid date.";
return false;
}
if (month%2!=0&& day>30)
{
cerror.innerHTML="Date is invalid. Please, enter a valid date.";
return false;
}
}
if (month==2)
{
if (year%4==0 && day>29)
{
cerror.innerHTML="Date is invalid. Please, enter a valid date.";
return false;
}
if (year%4!=0 && day>28)
{
cerror.innerHTML="Date is invalid. Please, enter a valid date.";
return false;
}
}
var d = new Date();
var db =new Date(year, month, day);
if(db>=d)
{
cerror.innerHTML="Date can't be more than today. Please, enter a valid date.";
return false;
}
return true;
}
cerror.innerHTML="Date is invalid. Please, enter a valid date.";
return false;
}
//--> - Rage (details)
Language: С#protected string GetFriendListTable()
{
int CellNr = Convert.ToInt32(txtCellNr.Text);
IList<FriendList> frList = (IList<FriendList>)Session["FriendsList"];
int index = frList.Count - CellNr;
if (index == 1)
{
return string.Format(
"<table>" +
"<tr align='center'>{0}</tr>" +
"</table>",
FormTableCell(frList[CellNr + 0].FriendID, GetFirstLAstName(frList[CellNr + 0].FriendID))
);
}
if (index == 2)
{
return string.Format(
"<table>" +
"<tr align='center'>{0}{1}</tr>" +
"</table>",
FormTableCell(frList[CellNr + 0].FriendID, GetFirstLAstName(frList[CellNr + 0].FriendID)),
FormTableCell(frList[CellNr + 1].FriendID, GetFirstLAstName(frList[CellNr + 1].FriendID))
);
}
if (index == 3)
{
return string.Format(
"<table>" +
"<tr align='center'>{0}{1}{2}</tr>" +
"</table>",
FormTableCell(frList[CellNr + 0].FriendID, GetFirstLAstName(frList[CellNr + 0].FriendID)),
FormTableCell(frList[CellNr + 1].FriendID, GetFirstLAstName(frList[CellNr + 1].FriendID)),
FormTableCell(frList[CellNr + 2].FriendID, GetFirstLAstName(frList[CellNr + 2].FriendID)));
}
if (index == 4)
{
return string.Format(
"<table>" +
"<tr align='center'>{0}{1}</tr>" +
"</table>" +
"<table>" +
"<tr align='center'>{2}{3}</tr>" +
"</table>",
FormTableCell(frList[CellNr + 0].FriendID, GetFirstLAstName(frList[CellNr + 0].FriendID)),
FormTableCell(frList[CellNr + 1].FriendID, GetFirstLAstName(frList[CellNr + 1].FriendID)),
FormTableCell(frList[CellNr + 2].FriendID, GetFirstLAstName(frList[CellNr + 2].FriendID)),
FormTableCell(frList[CellNr + 3].FriendID, GetFirstLAstName(frList[CellNr + 3].FriendID)));
}
if (index == 5)
{
return string.Format(
"<table>" +
"<tr align='center'>{0}{1}{2}</tr>" +
"</table>" +
"<table>" +
"<tr align='center'>{3}{4}</tr>" +
"</table>",
FormTableCell(frList[CellNr + 0].FriendID, GetFirstLAstName(frList[CellNr + 0].FriendID)),
FormTableCell(frList[CellNr + 1].FriendID, GetFirstLAstName(frList[CellNr + 1].FriendID)),
FormTableCell(frList[CellNr + 2].FriendID, GetFirstLAstName(frList[CellNr + 2].FriendID)),
FormTableCell(frList[CellNr + 3].FriendID, GetFirstLAstName(frList[CellNr + 3].FriendID)),
FormTableCell(frList[CellNr + 4].FriendID, GetFirstLAstName(frList[CellNr + 4].FriendID)));
}
if (index == 6)
{
return string.Format(
"<table>" +
"<tr align='center'>{0}{1}{2}</tr>" +
"</table>" +
"<table>" +
"<tr align='center'>{3}{4}{5}</tr>" +
"</table>",
FormTableCell(frList[CellNr + 0].FriendID, GetFirstLAstName(frList[CellNr + 0].FriendID)),
FormTableCell(frList[CellNr + 1].FriendID, GetFirstLAstName(frList[CellNr + 1].FriendID)),
FormTableCell(frList[CellNr + 2].FriendID, GetFirstLAstName(frList[CellNr + 2].FriendID)),
FormTableCell(frList[CellNr + 3].FriendID, GetFirstLAstName(frList[CellNr + 3].FriendID)),
FormTableCell(frList[CellNr + 4].FriendID, GetFirstLAstName(frList[CellNr + 4].FriendID)),
FormTableCell(frList[CellNr + 5].FriendID, GetFirstLAstName(frList[CellNr + 5].FriendID)));
}
if (index == 7)
{
return string.Format(
"<table>" +
"<tr align='center'>{0}{1}{2}{3}{4}</tr>" +
"</table>" +
"<table>" +
"<tr align='center'>{5}{6}</tr>" +
"</table>",
FormTableCell(frList[CellNr + 0].FriendID, GetFirstLAstName(frList[CellNr + 0].FriendID)),
FormTableCell(frList[CellNr + 1].FriendID, GetFirstLAstName(frList[CellNr + 1].FriendID)),
FormTableCell(frList[CellNr + 2].FriendID, GetFirstLAstName(frList[CellNr + 2].FriendID)),
FormTableCell(frList[CellNr + 3].FriendID, GetFirstLAstName(frList[CellNr + 3].FriendID)),
FormTableCell(frList[CellNr + 4].FriendID, GetFirstLAstName(frList[CellNr + 4].FriendID)),
FormTableCell(frList[CellNr + 5].FriendID, GetFirstLAstName(frList[CellNr + 5].FriendID)),
FormTableCell(frList[CellNr + 6].FriendID, GetFirstLAstName(frList[CellNr + 6].FriendID)));
}
if (index == 8)
{
return string.Format(
"<table>" +
"<tr align='center'>{0}{1}{2}{3}</tr>" +
"</table>" +
"<table>" +
"<tr align='center'>{4}{5}{6}{7}</tr>" +
"</table>",
FormTableCell(frList[CellNr + 0].FriendID, GetFirstLAstName(frList[CellNr + 0].FriendID)),
FormTableCell(frList[CellNr + 1].FriendID, GetFirstLAstName(frList[CellNr + 1].FriendID)),
FormTableCell(frList[CellNr + 2].FriendID, GetFirstLAstName(frList[CellNr + 2].FriendID)),
FormTableCell(frList[CellNr + 3].FriendID, GetFirstLAstName(frList[CellNr + 3].FriendID)),
FormTableCell(frList[CellNr + 4].FriendID, GetFirstLAstName(frList[CellNr + 4].FriendID)),
FormTableCell(frList[CellNr + 5].FriendID, GetFirstLAstName(frList[CellNr + 5].FriendID)),
FormTableCell(frList[CellNr + 6].FriendID, GetFirstLAstName(frList[CellNr + 6].FriendID)),
FormTableCell(frList[CellNr + 7].FriendID, GetFirstLAstName(frList[CellNr + 7].FriendID)));
}
if (index == 9)
{
return string.Format(
"<table>" +
"<tr align='center'>{0}{1}{2}{3}{4}</tr>" +
"</table>" +
"<table>" +
"<tr align='center'>{5}{6}{7}{8}</tr>" +
"</table>",
FormTableCell(frList[CellNr + 0].FriendID, GetFirstLAstName(frList[CellNr + 0].FriendID)),
FormTableCell(frList[CellNr + 1].FriendID, GetFirstLAstName(frList[CellNr + 1].FriendID)),
FormTableCell(frList[CellNr + 2].FriendID, GetFirstLAstName(frList[CellNr + 2].FriendID)),
FormTableCell(frList[CellNr + 3].FriendID, GetFirstLAstName(frList[CellNr + 3].FriendID)),
FormTableCell(frList[CellNr + 4].FriendID, GetFirstLAstName(frList[CellNr + 4].FriendID)),
FormTableCell(frList[CellNr + 5].FriendID, GetFirstLAstName(frList[CellNr + 5].FriendID)),
FormTableCell(frList[CellNr + 6].FriendID, GetFirstLAstName(frList[CellNr + 6].FriendID)),
FormTableCell(frList[CellNr + 7].FriendID, GetFirstLAstName(frList[CellNr + 7].FriendID)),
FormTableCell(frList[CellNr + 8].FriendID, GetFirstLAstName(frList[CellNr + 8].FriendID)));
}
if (index == 10 || index > 10)
{
return string.Format(
"<table>" +
"<tr align='center'>{0}{1}{2}{3}{4}</tr>" +
"</table>" +
"<table>" +
"<tr align='center'>{5}{6}{7}{8}{9}</tr>" +
"</table>",
FormTableCell(frList[CellNr + 0].FriendID, GetFirstLAstName(frList[CellNr + 0].FriendID)),
FormTableCell(frList[CellNr + 1].FriendID, GetFirstLAstName(frList[CellNr + 1].FriendID)),
FormTableCell(frList[CellNr + 2].FriendID, GetFirstLAstName(frList[CellNr + 2].FriendID)),
FormTableCell(frList[CellNr + 3].FriendID, GetFirstLAstName(frList[CellNr + 3].FriendID)),
FormTableCell(frList[CellNr + 4].FriendID, GetFirstLAstName(frList[CellNr + 4].FriendID)),
FormTableCell(frList[CellNr + 5].FriendID, GetFirstLAstName(frList[CellNr + 5].FriendID)),
FormTableCell(frList[CellNr + 6].FriendID, GetFirstLAstName(frList[CellNr + 6].FriendID)),
FormTableCell(frList[CellNr + 7].FriendID, GetFirstLAstName(frList[CellNr + 7].FriendID)),
FormTableCell(frList[CellNr + 8].FriendID, GetFirstLAstName(frList[CellNr + 8].FriendID)),
FormTableCell(frList[CellNr + 9].FriendID, GetFirstLAstName(frList[CellNr + 9].FriendID)));
}
else
{
return string.Format("<table><tr align='center'><td></td></tr></table>");
}
} - Peter (details)
Language: Java
Thanks to all of you for your examples and active in the discussion.

ну моё дело я сделал
Ikar the best но книжка моя Ж)
2007-08-19 at 2.04 pm
та это бред. пусть вотящие описывают своё решение. а то глупо наблюдать как пример критика на незнание функций набирает больше очей, чем пример Икара на незнание циклов.
пидрахуи!!!!
2007-08-19 at 2.12 pm
Здравствуй, мой дорогой. И где же в моем примере незнание функций?
ЗЫ. От пидрахуя слышу
2007-08-19 at 2.15 pm
начну сам:
проголосовал за Икара и за Сотону, т.к.
1. икар показал, что даже не зная основ можно писать програмы. этот exception-based цикл можно смело включать в книгу рецептов “что делать, если компилятор не поддерживает…”.
2. у сотоны пример сочетает всего по чуть-чуть. и “отличное” знание циклов, и копи-паст, и “понимание” того, что человек творит. короче кромешный ужос.
чем не понравились остальные:
если бы не копи-паст часть (еррор-мессаджи), то я б его даже вонючим не назвал
1. критик - очень уж красивый алгоритм.
2. рейдж - копипаст. черезчур банально, хотя и лучшее из копипастов :). но и главное, что это тот же чёрт, что и в моём примере, так что он все равно без награды не останется
3. петер - это уже заумь. при чём настолько часто встречающаяся, что сказать, что это “пахнущий” код низя. это традиционная ашипка. все такое делали.
2007-08-19 at 2.23 pm
2 критик.
как это где? ну чувак просто не знает, что javascript Date позволяет за 3 строчки проверить валидность даты. например вот так (только что написал, так что может бочить):
<html>
<body>
<script>
/**
y - YYYY
m - MM
d - DD
*/
function CheckDate(y,m,d) {
m = m-1; // бо Date с нуля считает
var temp = new Date(y,m,d);
if ( (y == temp.getFullYear()) &&
(m == temp.getMonth()) &&
(d == temp.getDate())
) {
return true;
}else {
return false;
}
}
</script>
D: <input type="text" name="d" id="d"><br>
M: <input type="text" name="m" id="m"><br>
Y: <input type="text" name="y" id="y"><br>
<input type="button" value="check" id="c"
onClick="alert (y.value + '/' + m.value + '/' + d.value +
': ' + CheckDate(y.value, m.value, d.value));">
</body>
</html>
2007-08-19 at 3.13 pm
гммм по поводу кода - а что значат эти проценты ? (я так полагал что процент проголосовавших за данный вариант - но на данный момент это уже 155%)
2007-08-20 at 8.49 am
2007-08-20 at 10.01 am
ваще бага ещё та.
1. даёт проголосовать 1 раз с главной страницы, а второй раз уже из страницы этого поста. короче я тут ещё раз проголосовал
2. возможность выбора нескольких кандидатов компроментирует голосование. ерка, уж ты должен помнить голосование за капитанов. короче надо давать возможность выбирать только одного.
так что бага не в плагине, а тех, кто считает.
раз голосующий может выбрать больше чем 1 пункт, то 100% и не будет никогда… (ну кроме случая, когда _все_ выбирут только по одному участнику.
на текущий момент проголосовало 10 человек, но дало 17 голосов.
2007-08-20 at 10.41 am
COTOHA, тут как не крути, можно накрутить голоса. И я ж ничего не говорил по поводу безопасности.
2007-08-20 at 1.42 pm
брехня
голосуют тока с помощью каментов (может ваще тока зареганные) и описывают почему именно это выбрано.
и каменты типа “+1″ рубить на корню. и всё - никаких накруток.
2007-08-20 at 3.04 pm
кстати - голосование с множественным выбором - 100%-й erka-style
конформизм в действии 
2007-08-20 at 3.12 pm