Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Flobbster posted:

Not only that, but even in the case of appending a bunch of string constants and string variables together, the Java compiler is smart enough (that's a phrase you don't hear too often!) to compile that into a StringBuilder construction and sequence of append() calls. I never knew this until I had to decompile a class for something and saw that.

Actually, this (1) is mandated by the language specification and has nothing to do with the quality of the compiler, (2) applies to any value that you concatenate into a string, not just string values, and (3) works only within a single expression. Also, weren't we talking about JavaScript, not Java?

Adbot
ADBOT LOVES YOU

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"

rjmccall posted:

Actually, this (1) is mandated by the language specification and has nothing to do with the quality of the compiler, (2) applies to any value that you concatenate into a string, not just string values, and (3) works only within a single expression.

Well yeah, anything that's not a string would get toString()'d first so that's a non-issue. That's cool though, I didn't know it was part of the language spec itself -- I just assumed it was an optimization in the compiler for large expressions.

quote:

Also, weren't we talking about JavaScript, not Java?

JavaScript code that was being generated on the server (in, as it turns out though, C# and not Java). It's a code horror that generates another code horror :v:

In the interest of full disclosure, I've done the very same thing in two of my projects (generating JS code with a StringBuilder in one, generating C++ in the other). I replaced the whole thing with Velocity templates (for the JS) and StringTemplate (for the C++ -- this code needed to be generable in both Eclipse and VS.NET plugins, so I needed a library with both Java and .NET versions), and I can't believe I didn't do that from the outset.

PrBacterio
Jul 19, 2000

Flobbster posted:

JavaScript code that was being generated on the server (in, as it turns out though, C# and not Java). It's a code horror that generates another code horror :v:
To be fair, though, program-generated code is pretty much always horrible, and nobody really cares because its not really meant to ever be looked at by a human being.

dwazegek
Feb 11, 2005

WE CAN USE THIS :byodood:
Haven't posted in this thread in a while, mostly because the WTF-inducing guys have all left the company, and the entire codebase has cleaned up quite nicely.

However today I had to go through some old (unused) code and found this beauty:
code:
/// <summary>
/// Creates a unique code.
/// </summary>
/// <returns>A unique code</returns>
private string CreateActivationCode()
{
    double seed = 0.16;
    int year = DateTime.Now.Year;
    int month = DateTime.Now.Month * 12;
    int day = DateTime.Now.DayOfYear;
    int hour = DateTime.Now.Hour * 24 * 60 * 60;
    int min = DateTime.Now.Minute * 24 * 60 * 60;
    int sec = DateTime.Now.Second * 24 * 60 * 60;
    int milsec = DateTime.Now.Millisecond * 24 * 60 * 60 * 1000;

    double basevalue = Convert.ToInt32(((double)(((year * month * day) + (hour + min + sec + milsec))) * seed));
    int len = basevalue.ToString().Length;
    if (len < 10)
    {
        string bvstring = (basevalue.ToString() + "0000000000");
        basevalue = double.Parse(bvstring.Substring(0, 9));
    }
    if (len >= 10)
    {
        len++;
    }
    if (len < 10)
    {
        len = 10;
    }
    if (len > 16)
    {
        len = 10;
    }

    return string.Format("{0}-{1}", len.ToString("X"), Math.Abs(Math.Round(basevalue, 0)));
}

pseudopresence
Mar 3, 2005

I want to get online...
I need a computer!
The Something Awful Forums > Discussion > Serious Hardware / Software Crap > The Cavern of COBOL: throw new Exception("hahaha, I bet you did not understood the code");

http://www.urubatan.info/2008/11/commenting-source-code-is-only-for-the-weak/

He turns some clear straightforward code into...I don't know :psyduck:

TSDK
Nov 24, 2003

I got a wooden uploading this one
If he thinks that this:
code:
closeFileReader(readerForFile);
Is somehow more readable than:
code:
readerForFile.close();
Then perhaps he should be programming in C and not Java.

ymgve
Jan 2, 2004


:dukedog:
Offensive Clock

Fib posted:

The Something Awful Forums > Discussion > Serious Hardware / Software Crap > The Cavern of COBOL: throw new Exception("hahaha, I bet you did not understood the code");

http://www.urubatan.info/2008/11/commenting-source-code-is-only-for-the-weak/

He turns some clear straightforward code into...I don't know :psyduck:

readFileContetIntoBuffer(buffer,readerForFile);

readFileContet

Contet



edit:
code:
public String write(StringBuilder fle, StringBuffer con) {
  BufferedReader br = new BufferedReader(new FileReader(fle.toString()));

  String lin;
  while(true) {
    lin = br.readLine();
    if (lin == null)
      break;

    con.append(lin).append("\n");
  }

  return con.toString();
}
This is how I would do it, but is doing the BufferedReader thing on one line and rewriting the readLine() part good or bad?

ymgve fucked around with this message at 18:29 on Nov 20, 2008

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.
^^^ Haha, we even highlighted it the same way.

quote:

readFileContetIntoBuffer(buffer,readerForFile);

quote:

readFileContetIntoBuffer

quote:

Contet

IF I EVER MEET YOU I WILL PULL OUT YOUR EYES AND DRIVE NAILS INTO THE SOCKETS, YOU MOTHERFUCKER.

Sorry. I HATE mispelled constants.

pseudopresence
Mar 3, 2005

I want to get online...
I need a computer!
code:
BufferedReader br = new BufferedReader(new FileReader(fle.toString()));
I've not done Java in years but this looks perfectly clear to me.

code:
  String lin;
  while(true) {
    lin = br.readLine();
    if (lin == null)
      break;

    con.append(lin).append("\n");
  }
I actually prefer the C-style while((var = getNext()) != NULL) style since it's very easy to spot once you know it, and it keeps some of the logic out of the body of the loop.

ymgve
Jan 2, 2004


:dukedog:
Offensive Clock
To elaborate more on my question, which of these are good/bad?

code:
(original)

String lin;
while((lin=br.readLine())!=null){
  con.append(lin).append("\n");
}


(mine)

String lin;
while(true) {
  lin = br.readLine();
  if (lin == null)
    break;

  con.append(lin).append("\n");
}


(other style I've seen elsewhere)

String lin;
lin = br.readLine();
while(lin!=null) {
  con.append(lin).append("\n");

  lin = br.readLine();
}


(yet another)

String lin;
boolean done = false;
while(!done) {
  lin = br.readLine();
  if (lin == null) {
    done = true;
  }
  else {
    con.append(lin).append("\n");
  }
}


(dailyWTF worthy way, don't even know if this will work)

String lin;
try {
  while(true) {
    lin = br.readLine();
    con.append(lin).append("\n");
  }
}
catch (NullPointerException npe) {
}

ymgve fucked around with this message at 19:07 on Nov 20, 2008

Zombywuf
Mar 29, 2008

code:
  BufferedReader br = new BufferedReader(new FileReader(fle.toString()));
Haha, Java you card.

Also, why the hell is the filename a string builder?

TSDK
Nov 24, 2003

I got a wooden uploading this one
... and why is a function for reading called 'write' at one point?

chocojosh
Jun 9, 2007

D00D.
And why are all variable names only three letters long?

fle? file!
lin? line!

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



TSDK posted:

... and why is a function for reading called 'write' at one point?

It's obviously writing the file to the buffer you big noob ugh it's like you've never seen real code before

There's probably a write(StringBuffer con,StringBuilder fle) that writes the buffer back to the file :suicide:

ymgve posted:

To elaborate more on my question, which of these are good/bad?

I like the third and first ones (in that order), myself.

ymgve
Jan 2, 2004


:dukedog:
Offensive Clock

Munkeymon posted:

It's obviously writing the file to the buffer you big noob ugh it's like you've never seen real code before

There's probably a write(StringBuffer con,StringBuilder fle) that writes the buffer back to the file :suicide:


I like the third and first ones (in that order), myself.

I've always felt the third one is a bit iffy because you have the same call twice, so if you ever change the code around, you have two locations that you need to change. Not so hard in this simple example, though.

I feel better about the first one, but it does seem a bit "unclean" to do an assignment inside the while() evaluation.

(Then again, this comes from someone who prefers break...)

Painless
Jan 9, 2005

Turn ons: frogs, small mammals, piles of compost
Turn offs: large birds, pitchforks
See you at the beach!

TRex EaterofCars posted:

Sun's javac is probably one of the best compilers on earth.

I have no idea what you're talking about. It produces pretty much a direct translation from Java to bytecode with no optimization or anything. It's easy to be the "best" in a nearly completely trivial process.

EDIT: I just realized I skipped a page in my rush to yell at Java, oh well.

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"

TSDK posted:

... and why is a function for reading called 'write' at one point?

Clearly he's programming in lower-level terms than our puny little minds can handle, since obviously every operation on a computing machine is a "write" -- even if you're reading from a file, you have to WRITE those bits to memory or a register to use them :rolleyes:

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



ymgve posted:

I've always felt the third one is a bit iffy because you have the same call twice, so if you ever change the code around, you have two locations that you need to change. Not so hard in this simple example, though.

I feel better about the first one, but it does seem a bit "unclean" to do an assignment inside the while() evaluation.

(Then again, this comes from someone who prefers break...)

True, but how often would you expect a read call to change form in a signifigant way?

Did you recently change your username?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Munkeymon posted:

I like the third and first ones (in that order), myself.

I prefer the original one then the third.

ymgve
Jan 2, 2004


:dukedog:
Offensive Clock

Munkeymon posted:

True, but how often would you expect a read call to change form in a signifigant way?

Did you recently change your username?

Nope, same username since registration. Why?

uXs
May 3, 2005

Mark it zero!

Campbell posted:

I just got done debugging a custom javascript image rotator that was spawned in hell. There was a basic javascript error, which wasn't a big deal. What was the big deal was that the rotator was a custom control project that existed only on that ex-employee's machine.

And all the javascript was done server-side and fed line by line into a StringBuilder which looked like this:

sb.Append("function buttes() ");
sb.Append("\r");
sb.Append("{");
sb.Append("\r");
sb.Append("if (this==that) ");
sb.Append("\r");
sb.Append("{");

gently caress I JUST NEED TO CORRECT YOUR INSANE JAVASCRIPT SO THE setTimeout() IS APPLIED TO A VARIABLE AND CAN BE CLEARED. BUT FINDING THE ACTUAL TIMEOUT IS A NEEDLE IN YOUR STRINGBUILDER HAYSTACK! :argh:

(I'm going to assume this is C# here.)

In pretty much every online tutorial about registering javascript, they put the javascript code in between the C# code, and gently caress around with StringBuilders or whatever. It looks horrible and I always make functions in separate .js-files instead, and just put a single function call in the C# registerscript function call.

However, I recently discovered that if you put an @ sign in front of the string, you can include line breaks in strings, and it just works. So this:

code:
sb.Append(@"
function buttes()
 {
 if (this==that)
   {
   //do stuff
   } ");
is valid code. So you can include Javascript code right in between C# if you want, and make it a lot more readable. (Other plus is that when you become sane and move it to a separate file, you can just copy/paste it without having to remove "sb.Append" on every line.)

(Putting it in separate files is still better, because there you get syntax coloring and junk.)

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Painless posted:

I have no idea what you're talking about. It produces pretty much a direct translation from Java to bytecode with no optimization or anything. It's easy to be the "best" in a nearly completely trivial process.

EDIT: I just realized I skipped a page in my rush to yell at Java, oh well.

When javac's hands aren't tied by inter-class abstraction boundaries, it can actually do quite a lot; but of course that's a huge limitation.

Painless
Jan 9, 2005

Turn ons: frogs, small mammals, piles of compost
Turn offs: large birds, pitchforks
See you at the beach!

rjmccall posted:

When javac's hands aren't tied by inter-class abstraction boundaries, it can actually do quite a lot; but of course that's a huge limitation.

You might mean it could do. It doesn't actually do poo poo.

This
code:
int sum( int[] b )
{
  int l = 0;
  for ( int i = 0; i < b.length; ++i ) l += b[ i ];
  return l;
}
and this
code:
int sum( int[] b )
{
  int l = 0;
  int size = b.length;
  for ( int i = 0; i < size; ++i ) l += b[ i ];
  return l;
}
produce different code. If you're using an interpreter to execute this, the performance difference can be huge. There's no reason javac couldn't do the optimization itself; someone just decided that JIT is so awesome, no one's going to ever interpret Java anywhere again.

Victor
Jun 18, 2004
The real WTF is that Java doesn't provide single, simple methods to read/write all text/lines, like .NET does. Hmmmm, maybe just wanting to get a file's contents without caring about how is a common enough operation to provide a shortcut in the standard library?

P.S. Another problem with calling readLine in two places is that continue will screw you over.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe

Painless posted:

You might mean it could do. It doesn't actually do poo poo.

Bah, you're right. Apparently I haven't looked at this since they decided to deprecate -O.

tef
May 30, 2004

-> some l-system crap ->

Painless posted:

You might mean it could do. It doesn't actually do poo poo.

What if b[] is being modified in a different thread?

Painless
Jan 9, 2005

Turn ons: frogs, small mammals, piles of compost
Turn offs: large birds, pitchforks
See you at the beach!

tef posted:

What if b[] is being modified in a different thread?

Then the results are undefined, because Java's volatile is only usable as a field attribute? And also, the length of an array will never change, so this question is pointless? Perhaps I have owned you goon sire?

Victor
Jun 18, 2004

tef posted:

What if b[] is being modified in a different thread?
[list=1][*]I'm pretty sure you get a new b -- I know .NET doesn't resize arrays in-place and I doubt Java does either.[*]Assuming in-place array modification, the code isn't threadsafe anyway.[/list]

very
Jan 25, 2005

I err on the side of handsome.
Recently I found a
code:
if ( big long condition &&
     blah blah blah )
{
    return true;
}
else
{
    return false;
}
and started to wonder who checked that in.. and then I realized.. it was me. :(

But also I had to hunt down one of the senior dev's anonymous enumerations, because he thought int was a good enough data type to represent it. I should bother him about where that darn enumeration is every time I have to use his functions.

Speaking of misspelled constants, we've got one somewhere that is hilariously and obviously misspelled. I wish I could remember what it was.

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...
Today I saw something that made me cry since I'm pretty sure the guy that's writing this is getting paid more than me.

This guy spent four days writing an app in .NET which allowed you to put an x and y value in two textboxes and click "Plot" and it would plot a point at those values on another control. And his code didn't even work.

So today I gave him a story for "parsing" log files retrieved from a machine. The first iteration of this is simply "look for {FAIL!} in the log, if it's there, the test failed."

His solution looks something like this (he hasn't checked it in yet and I'm just going off memory of what I saw over the shoulder)

code:
StreamReader x = open file etc;
byte[] y = x.ReadToEnd();
int i = 0;
while (i != y.Length)
{
  i = i + 1;
  if (y == "{FAIL!}")
  {
    ....
I don't remember exactly how he was checking for the string, maybe he wasn't there yet, but I went back to my office and made head-shaped imprints in my desk.

When I left today he was "stuck" on a compiler error which said "You can't have a method with the same name as its containing type". How is this a hard error to interpret?

edit: Oh, also, at one point he wanted to make a flag "WaitForFinishTrueOrFalse", and also changed a boolean field from "WillCheckReturnValue" on an object to "IsCheckReturnValue". And then used it in a if (IsCheckReturnValue == true) statement as justification for why "is" was better.

Dessert Rose fucked around with this message at 05:32 on Nov 21, 2008

shrughes
Oct 11, 2008

(call/cc call/cc)

Ryouga Inverse posted:

So today I gave him a story for "parsing" log files retrieved from a machine. The first iteration of this is simply "look for {FAIL!} in the log, if it's there, the test failed."

A "story"?

No Safe Word
Feb 26, 2005

shrughes posted:

A "story"?

I assume he means something like a user story

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...

No Safe Word posted:

I assume he means something like a user story

Correct. It's a Scrum/Agile term.

Here's what he checked in:

code:
        public int RetrieveLog(string vmLog, string sourceLog)
        {
            VMName = vmLog;
            Source = Program.GetFilePath(sourceLog, Program.target_dir);
            byte [] logResults = null;
            int counter = 0;

            logResults = System.IO.File.ReadAllBytes(Source);
            while (counter != logResults.Length)
            {
                if (logResults[counter].ToLower() == "fail")
                {
                    returnCode = 1;  //failure return code
                    break;
                }
                counter++;
            }
        }
I think I want to kill myself.

(It doesn't work, so I think he removed it from the project file so that the project still built)

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



ymgve posted:

Nope, same username since registration. Why?

Memory corruption on my part, I guess. I mostly remember avatars, anyway.

Ryouga Inverse posted:

I think I want to kill myself.

Just kill the guy who turned that poo poo in and maybe his job could be filled by someone who doesn't leave the # out of C#.

Jethro
Jun 1, 2000

I was raised on the dairy, Bitch!

Munkeymon posted:

Just kill the guy who turned that poo poo in and maybe his job could be filled by someone who doesn't leave the # out of C#.
I think he's programing C♭ instead.

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Jethro posted:

I think he's programing C♭ instead.

I'm not musical enough to know what the hell that thing is :(

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...

Munkeymon posted:

I'm not musical enough to know what the hell that thing is :(

"flat" instead of "sharp".

Yeah, I replaced the code with about three lines of "actual" code (the rest being whitespace and return {constant} statements) ... oh, and mine worked.

Fenderbender
Oct 10, 2003

You have the right to remain silent.
code:
    $search_code = "sub apply_search_pattern {\n";
    for ( $i = 0 ; $i < $len ; ++$i ) {
        $search_code .= "  \$on[$i] ||= /\\b$query[$i]\\b/io;\n";
    }
    $search_code .= "}\n";

    eval $search_code;
:froggonk:

Mikey-San
Nov 3, 2005

I'm Edith Head!
.

Adbot
ADBOT LOVES YOU

Zakalwe
May 12, 2002

Wanted For:
  • Terrorism
  • Kidnapping
  • Poor Taste
  • Unlawful Carnal Gopher Knowledge
A colleague and I were looking through a ray-tracer that someone released as we were implementing one of our own algorithms in it in order to see if the gains we were seeing were peculair to our own code.

We came across a piece of code like this...

code:
for( int axis = 0; axis < 3; axis++){
       switch(axis){
              case 0 : do_stuff(axis); break;
              case 1 : do_stuff(axis); break;
              case 2 : do_stuff(axis); break;
       }
}

:psyduck:

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply