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
Hidden Under a Hat
May 21, 2003

Ensign Expendable posted:

I have never heard of instanceof being a bad idea. You could do something like

code:
Instrument tabComponent = (Instrument)instrumentSettingsTabbedPane.getComponent(x);
instrumentSettings[x] = tabComponent.getSettings();
provided Instrument1 and Instrument2 are subclasses of Instrument that defines getSettings(). This will also call the Instrument1 and Instrument2 getSettings() methods automatically, depending on which Instrument the tabComponent is.

I would prefer to do this, but since my instrument classes are extending JPanel already I can't give them another superclass. I know that I could have the superclass itself extend JPanel and then by inheritance the subclasses would also become JPanels, but I'm pretty new to Java and I'm designing the JPanel in Netbeans, so if my instrument classes don't directly extend JPanel then I'd have to do the swing layout entirely in code which I'm not prepared to do. Unless anyone knows a way to do what I'm describing in Netbeans? The closest I can think of is to design the JPanel, then copy and paste the component initialization into the instrument subclasses.

Adbot
ADBOT LOVES YOU

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
Write an interface Instrument that defines getSettings() and other stuff Instruments need.

Hidden Under a Hat
May 21, 2003

Ensign Expendable posted:

Write an interface Instrument that defines getSettings() and other stuff Instruments need.

Ok I just did that and it seems to work. I didn't think interfaces worked like that. Thanks everyone!

Luminous
May 19, 2004

Girls
Games
Gains

HFX posted:

Using it for the method you describe cries that you should implement an interface that Instrument classes subclass to provide that method. It is considered bad form when you are using it to basically serve as the old dreaded C 200 line if..else if.. statement. Basically, used too liberally it can point to issues with design.

Now that I've said that, it is important to remember that instanceof is the only way to handle certain situations (especially when dealing with code older then Java 5). People who automatically dismiss it as bad, are the same people who think dynamic_cast in C++ is terrible.

You're right that its not always inappropriate, but I'd much rather people default to thinking it bad than not. The cases where it is used inappropriately (i.e., they created a poor design and aren't willing to fix it) seem to be far more widespread than appropriate uses.

Luminous fucked around with this message at 17:56 on Aug 31, 2011

iam
Aug 5, 2011
Anyone any tips on the easiest/best method for utilising properties files to store system messages?

I want to move all my "Error parsing comms" etc messages to a properties file, so that the system/API can just import com.x.pz.messages and then use the constants held within (that have been populated from the properties file).

Ideally I'd like the properties file to look like:

code:
COMMS_ERROR = "Error parsing comms"
VALIDATION_ERROR = "Error validating packet"
And then just be able to use the property names as the constant names, without having to manually do something like:

code:
final String COMMS_ERROR = properties.getProperty("COMMS_ERROR");
For the dozens of system messages...

Once I've imported com.x.pz.messages I'd like to then just substitute them in as you'd expect:

code:
throw new CommsErrorException(COMMS_ERROR);
Edit: Ignore, should have spent 30 more seconds Googling :P

code:
for(String key : properties.stringPropertyNames()) {
  String value = properties.getProperty(key);
  System.out.println(key + " => " + value);
}
Edit 2: No in fact, the above snippet doesn't answer the question. HALP. I don't know if it's going to be possible unless there's an elegant method to do it, i.e. there's no way you can do final String <key> = properties.getProperty(key); - the compiler will surely just tell you to gently caress off? I suppose one solution would be to populate a HashMap using the properties file, but then that's not as clean when you have to do:

code:
throw new CommsErrorException(hm.get("COMMS_ERROR"));

iam fucked around with this message at 09:00 on Sep 1, 2011

TheresaJayne
Jul 1, 2011

iam posted:

Anyone any tips on the easiest/best method for utilising properties files to store system messages?

I want to move all my "Error parsing comms" etc messages to a properties file, so that the system/API can just import com.x.pz.messages and then use the constants held within (that have been populated from the properties file).

Ideally I'd like the properties file to look like:

code:
COMMS_ERROR = "Error parsing comms"
VALIDATION_ERROR = "Error validating packet"
And then just be able to use the property names as the constant names, without having to manually do something like:

code:
final String COMMS_ERROR = properties.getProperty("COMMS_ERROR");
For the dozens of system messages...

Once I've imported com.x.pz.messages I'd like to then just substitute them in as you'd expect:

code:
throw new CommsErrorException(COMMS_ERROR);
Edit: Ignore, should have spent 30 more seconds Googling :P

code:
for(String key : properties.stringPropertyNames()) {
  String value = properties.getProperty(key);
  System.out.println(key + " => " + value);
}
Edit 2: No in fact, the above snippet doesn't answer the question. HALP. I don't know if it's going to be possible unless there's an elegant method to do it, i.e. there's no way you can do final String <key> = properties.getProperty(key); - the compiler will surely just tell you to gently caress off? I suppose one solution would be to populate a HashMap using the properties file, but then that's not as clean when you have to do:

code:
throw new CommsErrorException(hm.get("COMMS_ERROR"));

Well at a previous place we had a wrapper called CachedTypedProperties
code here https://gist.github.com/1185736

Theresa

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
In order to solve this problem, you're going to have to do one of two things:

1. Have a line of code somewhere saying that there is a property called <whatever>, or

2. Forgo compile-time checking, and have some way to map strings to messages (and use that every time you access a message).

If you do go for (1), then you don't have to do that in every file - in fact, you could automatically generate a file that looks like so:

code:
//boilerplate...
public class ErrorStrings {
    public static final string COMMS_ERROR;
    //etc...

    static {
        Properties p = new Properties();
        p.load(/*blah*/);
        COMMS_ERROR = p.getProperty("COMMS_ERROR");
        //etc...
    }
}
And then import static that into anything that uses those constants.

Or don't do a static import, and just access stuff as ErrorStrings.COMMS_ERROR or whatever.

Galaxander
Aug 12, 2009

I'm just getting started learning Java, and when the time came to learn about applets, I hit a snag.
I'm using Eclipse, and I've got a bare-bones do-nothing applet written as a test. It compiles and runs in Eclipse, but it throws an exception when I try to use it in an .html with Firefox. Using Windows XP, if that matters.

Here is the code I'm using (just taken from some tutorial):

code:
package learning;

import java.applet.Applet;
@SuppressWarnings("serial")
public class AppletTest extends Applet
{
   public AppletTest ()
   {
      System.out.println ("Tutorial: Constructor");
   }
   public String getAppletInfo ()
   {
      return ("Written by: Coke man Balarmy");
   }
   public void init ()
   {
      System.out.println ("Tutorial: init");
   }
   public void start ()
   {
      System.out.println ("Tutorial: start");
   }
   public void stop ()
   {
      System.out.println ("Tutorial: stop");
   }
   public void destroy ()
   {
      System.out.println ("Tutorial: destroy");
   }
}
Here's the html code I'm using:
code:
<applet code=learning.AppletTest.class width=640 height=480></applet>
The html file is in the same directory as AppletTest.class.

And here's the console barf:

code:
load: class learning.AppletTest.class not found.
java.lang.ClassNotFoundException: learning.AppletTest.class
	at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
	at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
	at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
	at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
	at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
	at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
Exception: java.lang.ClassNotFoundException: learning.AppletTest.class
If I leave off the "learning." in the html, I instead get

code:
java.lang.NoClassDefFoundError: AppletTest (wrong name: learning/AppletTest)
	at java.lang.ClassLoader.defineClass1(Native Method)
	at java.lang.ClassLoader.defineClassCond(Unknown Source)
	at java.lang.ClassLoader.defineClass(Unknown Source)
	at java.security.SecureClassLoader.defineClass(Unknown Source)
	at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
	at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Unknown Source)
	at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
	at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Unknown Source)
	at java.lang.ClassLoader.loadClass(Unknown Source)
	at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Unknown Source)
	at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
	at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)
Exception: java.lang.NoClassDefFoundError: AppletTest (wrong name: learning/AppletTest)
In either case, it seems to mess up Java, and existing normal applets on the internet will cease to appear until I terminate java.exe with the Task Manager (when it restarts they work again). Using Google has found me lots of solutions that don't work. Identical symptoms to different problems, I guess.

Eclipse and Firefox/Plug-in are both using the same JRE version: 1.6.0_27

Have mercy on this stupid goon who just wants his dumb applet to work.

baquerd
Jul 2, 2007

by FactsAreUseless

King Lazer posted:


code:
<applet code=learning.AppletTest.class width=640 height=480></applet>
The html file is in the same directory as AppletTest.class.


Move the AppletTest.class file to a directory called learning in the same location as the class file is currently.

Galaxander
Aug 12, 2009

baquerd posted:

Move the AppletTest.class file to a directory called learning in the same location as the class file is currently.

originally both files were in
C:\Program Files\Java\eclipse\workspace\Learning\bin\learning

Moving the .html up into bin has worked.

Let the name baquerd ring from the mountaintops! Thanks!

wins32767
Mar 16, 2007

Is there a Java equivalent of easy_install and eggs from python? I'd really like to be able to do something like:

code:
easy_install make-config myapp.war
<edit config file>
easy_install setup-app myapp
...
<load jar/war into the servlet container>
<everything works>

baquerd
Jul 2, 2007

by FactsAreUseless

wins32767 posted:

Is there a Java equivalent of easy_install and eggs from python? I'd really like to be able to do something like:

code:
easy_install make-config myapp.war
<edit config file>
easy_install setup-app myapp
...
<load jar/war into the servlet container>
<everything works>

Apache ant is the classic choice, though there are a lot of utilities you can do this with.

tractor fanatic
Sep 9, 2005

Pillbug
Why does transfer_wrong1 have a race condition?

code:
class Account { 
    float balance; 
    synchronized void deposit(float amt) { 
        balance += amt;
    }

    synchronized void withdraw(float amt) {
        if(balance < amt)
            throw new OutOfMoneyError();
        balance -= amt;
    }

    void transfer_wrong1(Acct other, float amt) {
        other.withdraw(amt);
        // race condition: wrong sum of balances
        this.deposit(amt);
    }

    synchronized void transfer_wrong2(Acct other, float amt) {
        // can deadlock with parallel reverse-transfer
        other.withdraw(amt);
        this.deposit(amt);
    }
}

lamentable dustman
Apr 13, 2007

🏆🏆🏆

wins32767 posted:

Is there a Java equivalent of easy_install and eggs from python? I'd really like to be able to do something like:

code:
easy_install make-config myapp.war
<edit config file>
easy_install setup-app myapp
...
<load jar/war into the servlet container>
<everything works>

Sounds like you want Maven

baquerd
Jul 2, 2007

by FactsAreUseless

tractor fanatic posted:

Why does transfer_wrong1 have a race condition?

code:
class Account { 
    float balance; 
    synchronized void deposit(float amt) { 
        balance += amt;
    }

    synchronized void withdraw(float amt) {
        if(balance < amt)
            throw new OutOfMoneyError();
        balance -= amt;
    }

    void transfer_wrong1(Acct other, float amt) {
        other.withdraw(amt);
        // race condition: wrong sum of balances
        this.deposit(amt);
    }

    synchronized void transfer_wrong2(Acct other, float amt) {
        // can deadlock with parallel reverse-transfer
        other.withdraw(amt);
        this.deposit(amt);
    }
}

code:
x.transfer_wrong1(y, 50)
y.transfer_wrong1(x, 50)
transfer_wrong1(0) withdraws from account y
transfer_wrong1(1) withdraws from account x, OutOfMoneyError thrown
transfer_wrong1(0) deposits into account x

-vs-

transfer_wrong1(0) withdraws from account y
transfer_wrong1(0) deposits into account x
transfer_wrong1(1) withdraws from account y
transfer_wrong1(1) deposits into account y

There's other ways to race this but if the error is thrown that's the cleanest to see.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

tractor fanatic posted:

Why does transfer_wrong1 have a race condition?
I would assume because it isn't synchronized.
e: but I think the dude above me probably knows more than I do

also why does this seemingly money-related class use floats

Sedro
Dec 31, 2008

tractor fanatic posted:

Why does transfer_wrong1 have a race condition?

If you calculate the total balance of the accounts between the withdrawal and deposit, some money will have disappeared into the void.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I run into things like this a lot:

code:
SomeObject myObject = null;
if (someCondition) {
    myObject = new SomeObject();
}

//and then further down in this method
if (someCondition) {
    myObject.doSomething();
}
Instead of checking for someCondition again, you could do a if (myObject != null), and the code would function the same way. Is there a good reason to use one way over the other?

Ensign Expendable
Nov 11, 2008

Lager beer is proof that god loves us
Pillbug
If the code is multithreaded, the condition may have changed. Also I guess it makes it a little more readable. Even if there are no external threads changing the condition, you still know when .doSomething() runs without having to scroll up to find out why myObject is or isn't null.

Max Facetime
Apr 18, 2009

fletcher posted:

Instead of checking for someCondition again, you could do a if (myObject != null), and the code would function the same way. Is there a good reason to use one way over the other?

If the conditions to initialize your object are complex, go with comparing against null so that the complexity is contained in one place.

But really, you should avoid this situation all together, and initializing something to null before actually initializing it is a clear warning-sign that all's not well.

Maybe you could structure the code in some other way:

code:
if (someCondition) {
    SomeObject myObject = new SomeObject();
    doDescriptiveTask();
    doObviousTaskWithSomeObject(myObject);
    doSimpleTask();
    myObject.doSomething();
} else {
    doDescriptiveTask();
    doSimpleTask();
}

tractor fanatic
Sep 9, 2005

Pillbug

baquerd posted:

code:
x.transfer_wrong1(y, 50)
y.transfer_wrong1(x, 50)
transfer_wrong1(0) withdraws from account y
transfer_wrong1(1) withdraws from account x, OutOfMoneyError thrown
transfer_wrong1(0) deposits into account x

-vs-

transfer_wrong1(0) withdraws from account y
transfer_wrong1(0) deposits into account x
transfer_wrong1(1) withdraws from account y
transfer_wrong1(1) deposits into account y

There's other ways to race this but if the error is thrown that's the cleanest to see.

but if you are relying on one happening before the other you shouldn't be using concurrency anyways, right?

I mean this race condition would appear no matter what solution you try since you can't control which transfer comes first.

baquerd
Jul 2, 2007

by FactsAreUseless

tractor fanatic posted:

but if you are relying on one happening before the other you shouldn't be using concurrency anyways, right?

I mean this race condition would appear no matter what solution you try since you can't control which transfer comes first.

Properly done concurrency either does not allow the transfers to occur non-atomically or implements a non-locking control that provides for ordered transactions. The general idea is to maintain a consistently valid read state. It's OK if the transfer fails as long as the state is not at any point readable in an incorrect manner by an outside observer.

Here is a (bad, trivial, etc.) solution to the problem assuming all transactions run through a single JVM instance and this is the whole of the class definition:

code:
class Account { 
    private float balance; 

    public Account(float initBalance) {
        balance = initBalance;
    }

    private void deposit(float amt) { 
        balance += amt;
    }

    private void withdraw(float amt) {
        if(balance < amt)
            throw new OutOfMoneyError();
        balance -= amt;
    }

    static synchronized void transfer(Account incoming, Account outgoing, float amt) {
        outgoing.withdraw(amt);
        incoming.deposit(amt);
    }
}

baquerd fucked around with this message at 05:36 on Sep 2, 2011

tractor fanatic
Sep 9, 2005

Pillbug

baquerd posted:


Ah, I didn't think of using a static solution to solve this with locks. Anyways, I'm an idiot because the paper I found this in explains that the problem they were worried about is what Sedro was saying about the balances not summing up properly.

I misinterpreted the "sum of balances" comment.

rjmccall
Sep 7, 2007

no worries friend
Fun Shoe
If the only operations are transfer, withdraw, and deposit, then the original implementation is almost sufficiently atomic because of the specific constraints of the problem. The only issue is a self-transfer, where an interleaved withdrawal could fail in a way that can't happen in any serialization.

But adding almost any other operation is likely to change that. Certainly a "current total in all accounts" would. And it's probably not worth carefully analyzing the set of operations to find an optimal synchronization strategy.

Using a universal lock solves the deadlock problem, as does always grabbing multiple locks in a globally-determined order (e.g. in order of increasing account number).

gotly
Oct 28, 2007
Economy-Sized
Sorry if this is really basic, it's been about 3-4 years since I've done any real Java and I don't know how to Google this because that's exactly what it's about : this.

When is it appropriate and when is it inappropriate to reference a variable/function/anything as this.exampleThing instead of just exampleThing? No need to re-invent the wheel, if someone could point me at the correct search term I'd really appreciate it. So far, I've just found "it's a style thing" which is kind of insane. Why put "this" in front of every god drat thing if it's not needed?


Edit:

stackoverflow posted:

You only need to use this - and most people only use it - when there's an overlapping local variable with the same name. (Setter methods, for example.)

Of course, another good reason to use this is that it causes intellisense to pop up in IDEs :)

Really? Really?

gotly fucked around with this message at 04:00 on Sep 3, 2011

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Yeah, the only time I've ever seen it is when a parameter and an instance variable have the same name, or an instance variable and a local variable. (edit: I guess a parameter is just a local variable, isn't it?)

code:
public class MyClass {
    int number;

    public MyClass(int number) {
        this.number = number;
    }
}
I'm sure with a bit of work you could always make sure the names are different. What's the consensus on which one is best?

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

carry on then posted:

Yeah, the only time I've ever seen it is when a parameter and an instance variable have the same name, or an instance variable and a local variable.
for a copy method, assert copy.equals(this); is pretty useful

gotly
Oct 28, 2007
Economy-Sized

carry on then posted:

Yeah, the only time I've ever seen it is when a parameter and an instance variable have the same name, or an instance variable and a local variable. (edit: I guess a parameter is just a local variable, isn't it?)

code:
public class MyClass {
    int number; //BUTTS

    public MyClass(int number) { //CHEWBACCA
        this.number = number;
    }
}
I'm sure with a bit of work you could always make sure the names are different. What's the consensus on which one is best?


Just to make sure I have it 100% - in this case, MyClass will actually change BUTTS and leave CHEWBACCA alone?

Thom Yorke raps
Nov 2, 2004


gotly posted:

Just to make sure I have it 100% - in this case, MyClass will actually change BUTTS and leave CHEWBACCA alone?

It assigns the value of CHEWBACCA to BUTTS.

baquerd
Jul 2, 2007

by FactsAreUseless

gotly posted:

Just to make sure I have it 100% - in this case, MyClass will actually change BUTTS and leave CHEWBACCA alone?

Yes, as Ranma says. Here's some "fun" code showing another way to use "this":

code:
class Cheek {
	protected int numField;
	
	public Cheek() {
		numField = (int)(Math.random()*100);
	}
	
	public void wipe() {
		numField = 0;
	}
}

class Butts extends Cheek {
	public Butts() {
		super();
	}
	
	public Butts(Butts otherButt) {
		this();
		otherButt.wipe();
	}
	
	public void printButt() {
		System.out.println(numField);
	}
}

public class Test {
	public static void main(String[] args) {
		Butts b1 = new Butts();
		Butts b2 = new Butts(b1);
		
		b1.printButt();
		b2.printButt();
	}
}

baquerd fucked around with this message at 05:24 on Sep 3, 2011

Sedro
Dec 31, 2008
I mostly use this (and base, super, etc) when I want to filter autocompletion. Naming conventions like _fieldName solve the naming conficts (safer to avoid them entirely).

There are some cases where it makes stylistic sense:
code:
bool equals(Address other)
{
    return this.street == other.street
        && this.zip == other.zip;
}

gotly
Oct 28, 2007
Economy-Sized
Thanks guys, cleared it up a lot. I program in something drastically different during the day so it's always nice to see what seasoned Java guys consider best practice. Also, if I could write production code like baquerd I'd die a happy man.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Sedro posted:

Naming conventions like _fieldName solve the naming conficts (safer to avoid them entirely).
those conventions are poo poo and make code look terrible, why people don't just use this and avoid polluting their variables I will never understand

also never ever write a method named equals that takes in a specific kind of object and returns a boolean

Sedro
Dec 31, 2008
Do whatever you want with private fields as far as I'm concerned. I would like to hear your reasoning against the typed equals method though.

brosmike
Jun 26, 2009

Sedro posted:

I would like to hear your reasoning against the typed equals method though.

There are tons and tons of non-obvious pitfalls around writing a correct equals method. Here's what looks like a perfectly normal implementation of some equal butts if you don't think too hard about it, but it's very wrong - there are several different issues with this code:

code:
class Butt {
    private int poops; 

    public Butt(int poops) {
        this.poops = poops;
    }
    public boolean equals(Butt other) {
        return this.poops == other.poops;
    }
}

class ButtProblems {
    public static void main(String[] args) {
        Butt a = new Butt(1);
        Butt b = new Butt(1);
        
        a.equals(b); // True - okay so far
        b.equals(a); // Also true

        Object reallyA = a;

        reallyA.equals(b); // Still true - great! <- oops this is wrong, this one breaks
        b.equals(reallyA); // Nope. poo poo.
        reallyA.equals(reallyA); // Double poo poo <- oops this one is actually true (but probably not for the reason you want)
    }
}
This site looks to have a decent writeup of some of the potential issues with equals methods.

vvvvvvvvvvvv drinking heavily and not testing poo poo is the best way to post

brosmike fucked around with this message at 11:38 on Sep 3, 2011

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Sedro posted:

I would like to hear your reasoning against the typed equals method though.
I'll just quote

Joshua Bloch, Effective Java posted:

It is acceptable to provide such a “strongly typed” equals method in addition to the normal one as long as the two methods return the same result, but there is no compelling reason to do so. It may provide minor performance gains under certain circumstances, but it isn’t worth the added complexity (Item 55).
And implementing it without also overriding equals(Object) means broken code, see above post.
e: Except in the above article, replace the entirety of Pitfall #3 with "Don't mutate objects being used as keys in a Map (or present in a Set)."

Malloc Voidstar fucked around with this message at 10:32 on Sep 3, 2011

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

brosmike posted:

code:
        reallyA.equals(b); // Still true - great!
        b.equals(reallyA); // Nope. poo poo.
        reallyA.equals(reallyA); // Double poo poo

I get false, false, true.

Overload resolution is done based on the static type of the expression - since Object doesn't have an equals(Butt) method, equals(Object) gets picked.

The fact that you're not actually overriding the equals method is begging for trouble, but it's not quite as bad as you're presenting.

Sedro
Dec 31, 2008
I would never write a typed equals without overriding object.equals and object.getHashCode. When I see a typed equals I immediately know that the type implements logical equality without looking at comments/source.

Paolomania
Apr 26, 2006

Sedro posted:

I mostly use this (and base, super, etc) when I want to filter autocompletion. Naming conventions like _fieldName solve the naming conficts (safer to avoid them entirely).

I think there is plenty of semantic clarity to 'this.field', and it is an explicit meaning that is enforced by the language itself. I always prefer using language constructs over implicit conventions that may be arbitrary, conflicting, forgotten by the time you have to maintain it, or not communicated to the next programmer (internal or external) who has to look at the code and may have different assumptions about what makes for an intuitive name.

Adbot
ADBOT LOVES YOU

Mustach
Mar 2, 2003

In this long line, there's been some real strange genes. You've got 'em all, with some extras thrown in.

Aleksei Vasiliev posted:

those conventions are poo poo and make code look terrible, why people don't just use this and avoid polluting their variables I will never understand
Seriously. Same goes for the horrifying convention of prefixing member variables with m_.

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