Comentários divertidos das classes do core Java

Olá pessoal,

Eu acabei de montar um conjunto de comentários mais divertidos que eu tenho visto nos código fontes do Java. Esses são os fontes das classes que compõem o Java e as ferramentas:

DISCLAIMER: tem que saber um pouco de inglês pra poder apreciar, eu poderia tentar traduzir os comentários, mas não ia ficar bom.

:arrow: Engraçado

java.math.BigDecimal:

/* Appease the serialization gods */
private static final long serialVersionUID = 6108874887143696463L;

java.util.ArrayDeque:

/**
 * Appease the serialization gods.
 */
private static final long serialVersionUID = 2340985798034038923L;

com.sun.corba.se.impl.naming.cosnaming.NamingContextImpl:

    if (impl.Resolve(n[0],bth) != null)
    // "Resistence is futile." [Borg pickup line]
    throw new AlreadyBound();

java.awt.Dialog:

    // add all blockers' blockers to blockers :)
    for (int i = 0; i < blockers.size(); i++) {

Animator (Demo classes):

    /**
     * Stop the insanity, um, applet.
     */
    public synchronized void stop() {
        engine = null;
        animation.stopPlaying();
        if (userPause) {
            userPause = false;
            notify();
        }
    }

javax.swing.text.rtf.RTFGenerator:

String approximationForUnicode(char ch)
{
    /* TODO: Find reasonable approximations for all Unicode characters
       in all RTF code pages... heh, heh... */
    return "?";
}

com.sun.corba.se.impl.oa.poa.POAImpl:

/**
 * POAImpl is the implementation of the Portable Object Adapter. It
 * contains an implementation of the POA interfaces specified in
 * COBRA 2.3.1 chapter 11 (formal/99-10-07).
...
 */

:arrow: "Não me importo mais"

javax.swing.Timer:

// This of course implies you can get dropped events, but such is life.

sun.plugin2.ipc.windows.WindowsIPCFactory:

// Might as well keep this around

sun.media.sound.MixerSourceLine:

// ivg: Well, it does hang in some cases.

sun.security.x509.AVA:

    if (!in.markSupported()) {
        // oh well
        return true;
    } else {

:arrow: Informativo

sun.tools.java.ClassDefinition:

 // Why are they called Miranda methods?  Well the sentence "If the
 // class is not able to provide a method, then one will be provided
 // by the compiler" is very similar to the sentence "If you cannot
 // afford an attorney, one will be provided by the court," -- one
 // of the so-called "Miranda" rights in the United States.

:arrow: Frustrado

javax.swing.JTabbedPane

 // REMIND(aim): this is really silly;

com.sun.xml.internal.bind.v2.util.DataSourceSource:

    } catch (IOException e) {
        // argh
        throw new RuntimeException(e);
    }

com.sun.org.apache.xml.internal.serialize.HTMLdtd:

public static boolean isURI( String tagName, String attrName )
{
    // Stupid checks.
    return ( attrName.equalsIgnoreCase( "href" ) || attrName.equalsIgnoreCase( "src" ) );
}

javax.swing.text.rtf.AbstractFilter:

    // stupid signed bytes
    if (b < 0)
        b += 256;

com.sun.org.apache.xalan.internal.xsltc.trax.TransformerHandlerImpl:

    catch (TransformerException e) {
        // What the hell are we supposed to do with this???
        throw new IllegalArgumentException(e.getMessage());
    }

sun.misc.FloatingDecimal:

    if ( diff != 0L ) {
        // damn, damn, damn. q is too big.

sun.xml.internal.stream.writers.XMLDOMWriterImpl:

    public void writeEndDocument() throws XMLStreamException {
        //What do you want me to do eh! :)

com.sun.org.apache.xml.internal.res.XMLMessages:

 // Do this to keep format from crying.

:arrow: Bom humor

sun.awt.X11.XWM:

/*
 * Helper function for isEnlightenment().
 * Enlightenment uses STRING property for its comms window id.  Gaaa!
 * The property is ENLIGHTENMENT_COMMS, STRING/8 and the string format
 * is "WINID %8x".  Gee, I haven't been using scanf for *ages*... :-)
 */

:arrow: Agressivo

com.sun.org.apache.xalan.internal.xslt.Process:

  /** It is _much_ easier to debug under VJ++ if I can set a single breakpoint
   * before this blows itself out of the water...
   * (I keep checking this in, it keeps vanishing. Grr!)
   * */
  static void doExit(String msg)
  {
    throw new RuntimeException(msg);
  }

com.sun.org.apache.xalan.internal.xsltc.dom.BitArray:

/**
 * This method returns the Nth bit that is set in the bit array. The
 * current position is cached in the following 4 variables and will
 * help speed up a sequence of next() call in an index iterator. This
 * method is a mess, but it is fast and it works, so don't fuck with it.
 */

:arrow: Brincalhão

sun.awt.motif.MWindowPeer:

    // XXX: nasty WM, foul play.  spank WM author.
    public void handleDestroy() {

DirectoryScanner (Example classes):

    // As it stands, we simply call task.execute() in the current
    // thread - brave and fearless readers may want to attempt the
    // modification ;-)

:arrow: Dramatico

java.util.logging.LogManager:

if (deathImminent) {
    // Aaargh...
    // The VM is shutting down and our exit hook has been called.
    // Avoid allocating global handlers.
    return;
}

:arrow: Louco

javax.swing.text.rtf.MockAttributeSet:

/* This AttributeSet is made entirely out of tofu and Ritz Crackers
   and yet has a remarkably attribute-set-like interface! */
class MockAttributeSet
    implements AttributeSet, MutableAttributeSet

(O site thedailywtf.com já tinha um artigo sobre isso)
com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl:

/**
 * As Gregor Samsa awoke one morning from uneasy dreams he found himself
 * transformed in his bed into a gigantic insect. He was lying on his hard,
 * as it were armour plated, back, and if he lifted his head a little he
 * could see his big, brown belly divided into stiff, arched segments, on
 * top of which the bed quilt could hardly keep in position and was about
 * to slide off completely. His numerous legs, which were pitifully thin
 * compared to the rest of his bulk, waved helplessly before his eyes.
 * "What has happened to me?", he thought. It was no dream....
 */
protected final static String DEFAULT_TRANSLET_NAME = "GregorSamsa";

:arrow: Alegria

com.sun.org.apache.xml.internal.serializer.utils.Messages:

 fmsg = java.text.MessageFormat.format(msg, args);
 // if we get past the line above we have create the message ... hurray!

:arrow: Sarcastico

com.sun.org.apache.xpath.internal.axes.WalkerFactory:

// If we have an attribute or namespace axis that went up, then
// it won't find the attribute in the inverse, since the select-to-match
// axes are not invertable (an element is a parent of an attribute, but
// and attribute is not a child of an element).
// If we don't do the magic below, then "@*/ancestor-or-self::*" gets
// inverted for match to "self::*/descendant-or-self::@*/parent::node()",
// which obviously won't work.
// So we will rewrite this as:
// "self::*/descendant-or-self::*/attribute::*/parent::node()"
// Child has to be rewritten a little differently:
// select: "@*/parent::*"
// inverted match: "self::*/child::@*/parent::node()"
// rewrite: "self::*/attribute::*/parent::node()"
// Axes that go down in the select, do not have to have special treatment
// in the rewrite. The following inverted match will still not select
// anything.
// select: "@*/child::*"
// inverted match: "self::*/parent::@*/parent::node()"
// Lovely business, this.

:arrow: Enjoado

com.sun.tools.internal.xjc.reader.xmlschema.SimpleTypeBuilder:

    // TODO: this is so dumb
    m.put("string",         CBuiltinLeafInfo.STRING);
    m.put("anyURI",         CBuiltinLeafInfo.STRING);
    m.put("boolean",        CBuiltinLeafInfo.BOOLEAN);

com.sun.tools.example.debug.bdi.JDIEventSource:

//### Gross foul hackery!
private void dispatchEventSet(final AbstractEventSet es) {

javax.swing.tree.FixedHeightLayoutCache:

    // YECK!
    return getRow() + 1 + getTotalChildCount() -
                 (childCount - index);

com.sun.org.apache.xpath.internal.axes.LocPathIterator:

    // Yech, shouldn't have to do this.  -sb
    if(null == m_prefixResolver)
        m_prefixResolver = xctxt.getNamespaceContext();

...
      clone.m_predCount = m_predicateIndex;
      // The line above used to be:
      // clone.m_predCount = predCount - 1;
      // ...which looks like a dumb bug to me. -sb

com.sun.media.sound.MixerClip:

// i don't think we should allow this in this release: too many ways to screw up!
/*
  //        // if we have a sample voice, update it
  //        if (id != 0) {
  //            // can throw IllegalArgumentException
  //            // $$: 04.19.99: this should only happen if the loop size is too small
  //            nSetLoopPoints(id, (int)start, (int)end);
  //        }
*/

/*
...
if (Printer.err) Printer.err("Could not re-open clip in MixerClip.java.setLoopPoints!");
// we are screwed... re-open failed!
// sorry....
implClose();
...
*/

com.sun.deploy.util.VersionID:

// FIXME: this is a horrendously inefficient representation;
// should use an array of ints or Integers rather than re-parsing
// them every time

com.sun.org.apache.xml.internal.dtm.ref.IncrementalSAXSource_Filter:

    // Horrendous kluge to run filter to completion. See below.
    if(fNoMoreEvents)
      return;

Notepad (Demo Classes):

/**
 * To shutdown when run as an application.  This is a
 * fairly lame implementation.   A more self-respecting
 * implementation would at least check to see if a save
 * was needed.
 */
protected static final class AppCloser extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
        System.exit(0);
    }
}

:arrow: Outros

sun.jkernel.DigestOutputStream:

} catch (NoSuchAlgorithmException e) {
    // Impossible to get here, but stranger things have happened...
    throw new RuntimeException("DigestOutputStream() unknown algorithm");
}
// superstition from a test failure this.out = out;

com.sun.org.apache.xalan.internal.xsltc.dom.CachedDocument:

// Brutal handling of all exceptions
catch (Exception e) {
    return(System.currentTimeMillis());
}

com.sun.java.util.jar.pack.PackageWriter:

// Crash and burn with a complaint if there are funny
// bytecodes in this class file.
String complaint = code.getMethod()
    +" contains an unrecognized bytecode "+i
    +"; please use the pass-file option on this class.";
Utils.log.warning(complaint);
throw new IOException(complaint);

java.util.jar.Pack200:

/**
...
 * Examples:
 *     Map p = packer.properties();
 *     p.put(PASS_FILE_PFX+0, "mutants/Rogue.class");
 *     p.put(PASS_FILE_PFX+1, "mutants/Wolverine.class");
 *     p.put(PASS_FILE_PFX+2, "mutants/Storm.class");
 *     # Pass all files in an entire directory hierarchy:
 *     p.put(PASS_FILE_PFX+3, "police/");
 */

com.sun.tools.jdi.ObjectReferenceImpl:

/* The above code is left over from previous versions.
 * We haven't had time to divine the intent.  jjh, 7/31/2003
 */

com.sun.media.sound.RealTimeSequencer:

} catch (MidiUnavailableException mue) {
// uhum, strange situation. Need to cast to InvalidMidiDataException
throw new InvalidMidiDataException(mue.getMessage());
}

com.sun.org.apache.xml.internal.dtm.ref.dom2dtm.DOM2DTM:

// (If it's an EntityReference node, we're probably scrod. For now
// I'm just hoping nobody is ever quite that foolish... %REVIEW%)

com.sun.tools.doclets.formats.html.AbstractTreeWriter:

/**
 * Generate each level of the class tree. For each sub-class or
 * sub-interface indents the next level information.
 * Recurses itself to generate subclasses info.
 * To iterate is human, to recurse is divine - L. Peter Deutsch.
 *
 * @param parent the superclass or superinterface of the list.
 * @param list list of the sub-classes at this level.
 * @param isEnum true if we are generating a tree for enums.
 */

sun.awt.shell.Win32ShellFolder2:

// Ouch, we have no hard drives. Return something "valid" anyway.
return new File("C:\");

com.sun.org.apache.bcel.internal.ExceptionConstants:

  /** The mother of all exceptions
   */
  public static final Class THROWABLE = Throwable.class;

com.sun.xml.internal.messaging.saaj.util.ByteOutputStream:

/**
 * Evil buffer reallocation method.
 * Don't use it unless you absolutely have to.
 *
 * @deprecated
 *      because this is evil!
 */
public byte toByteArray()[] {
    byte[] newbuf = new byte[count];
    System.arraycopy(buf, 0, newbuf, 0, count);
    return newbuf;
}

com.sun.org.apache.xpath.internal.compiler.Compiler:

  int what = getWhatToShow(startOpPos);
  // bit-o-hackery, but this code is due for the morgue anyway...
  if(0x00000500 == what)
    addMagicSelf = false;

sun.jvm.hotspot.runtime.sparc.SPARCFrame:

// Also not sure exactly how alignment works...maybe should read these offsets from the target VM
// (When you have a hammer, everything looks like a nail)
long offset = VM.getVM().alignUp(4, VM.getVM().getAddressSize());   // uc_flags

sun.security.tools.KeyTool:

// do not drown user with the help lines.
if (debug) {
    throw new RuntimeException("NO BIG ERROR, SORRY");
} else {
    System.exit(1);
}

[]s,
Sami

HAha… gostei.

Impossible to get here, but stranger things have happened…

[quote]com.sun.org.apache.xalan.internal.xsltc.trax.TransformerHandlerImpl:

catch (TransformerException e) { // What the hell are we supposed to do with this??? throw new IllegalArgumentException(e.getMessage()); } [/quote]
:lol: :lol: :lol: :lol:

Você tá brincando comigo que você fez tudo isso aí…
VAIIIIIIIIII TRABALHARRRRR.
euuaeuhaeuheaae

No mais: Parabéns, ficou legal. :wink:

Valeu pessoal.

Fábio: Realmente deu um trabalhão montar, formatar e categorizar tudo isso, mas eu estou sem emprego no momento, esperando o querido governo Brasileiro liberar meu visto de trabalho e por isso estou com bastante tempo livre. Por outro lado, para ganhar um dinheirinho eu estou analisando a segurança do Java e é por esse motivo que eu encontrei uma boa parte desses comentários.

[]s,
Sami

PS.
Meus preferidos são aqueles de deuses de serialização, a coisa do borg (Star Trek) e a referencia ao livro do Kafka (o negócio do Gregor Samsa).

Eu curti muito isso aqui:

/** 
* Evil buffer reallocation method. 
* Don't use it unless you absolutely have to. 
* 
* @deprecated 
*      because this is evil! 
*/  

Deviam colocar algo assim pro DefaultTableModel também.

Se não me engano a referencia que voce disse do Borg é do The Hitchhiker’s Guide to The Galaxy. os Vorgs que falam “resistence is futile”.

Heheh, eu conheço pessoas bem mais dedicadas a Star Trek do que eu que iam ficar indignadas com você, atribuindo a frase a alguma outra origem. Existem referencias ao frase em muitos lugares, mas originalmente é dos Borg do Star Trek. :slight_smile:

BTW, o inglês correto é “resistance”, mas eu deixei de proposito do jeito errado que tava escrito no código fonte.


// (When you have a hammer, everything looks like a nail)  

O cara que escreveu isso é um gênio.

The Hitchhiker’s Guide to the Galaxy book
Publication date 12 October 1979

“Resistance is futile”
Its first use in Star Trek came in the 1990…

Ahh… sei lá… sempre que ouvi essa frase liguei ela ao livro e não a Star Trek.

Mas como o cara escreveu Borg depois acredito que seja Star Trek.

Mas nao posso deixar de negar que a frase saiu bem antes nos livros de Douglas Adams.

Ok, depois de pesquisar um pouco, estou pronto pra ceder um pouco. :slight_smile:

“Resistance is futile” continua sendo dos Borg do Stark Trek.

“Resistance is useless” que com toda probabilidade foi o que inspirou a frase em cima, foi realmente usado por Adams antes, e na verdade até antes do Adams em 1964.

http://everything2.com/title/Resistance+is+Futile

(preciso parar de ler os fontes do Java e finalmente achar o tempo pra ler o Hitchhiker’s Guide to the Galaxy)

Putz… verdade… é “Resistance is useless”… eu realmente me confundi… eu disse que foi em 1979 por que foi quando o livro foi lançado. Mas a radio novela original já passava antes disso.

É e ainda tem outra referencia antes dessa… =/

E vale a pena ler esse livro sim.
E os outros 4 da série também.

.The Restaurant at the End of the Universe
.Life, the Universe and Everything
.So Long, and Thanks for All the Fish
.Mostly Harmless