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
1337JiveTurkey
Feb 17, 2005

rjmccall posted:

I mean, Java's generics support is already too sophisticated by some metrics — most programmers don't understand the mathematics and just work around (misuses of) the type system with casts. And there's a lot more yet that Java generics can't express, like the co-/contra-variance of List<T> with T.

If Java could express covariance and contravariance of type parameters rather than making every method take some List<? extends T> instead, that'd fix my biggest complaint with its type system.

Reified types are a nice to have feature, but I think it comes up once every few months for me, and I write a lot of generic code. When it does come up, it's often some variation where the parent class is Bar<BP extends BaseParameter> and class Foo implements Bar<RefinedParameter> or class Foo<RP extends RefinedParameter> implements Bar<RP>. In that case it is possible to recover the type through Foo.class.getGenericInterfaces(). It's even more verbose than usual for Java (and that's saying something) but it's technically possible.

You need to find the Type which myType.equals(Bar.class), cast it (unsafely :v:) to a ParameterizedType and then getActualTypeArguments() to recover the parameter. In this case it would be the Class of RefinedParameter or WildcardType equivalent to ? extends RefinedParameter.

In practice, I've found just putting in a method Class<BP> Bar.getParameterType() which Foo implements to return RefinedParameter.class is often sufficient, if inelegant.

Adbot
ADBOT LOVES YOU

gonadic io
Feb 16, 2011

>>=
These last few pages have convinced me that my current plan of avoiding C++ in favour of Haskell or, if I'm desperate and tired, Java is probably not the greatest career move. Is there a handy guide to C++ templates? Are they comparable to Haskell's type system?

Zombywuf
Mar 29, 2008

AlsoD posted:

These last few pages have convinced me that my current plan of avoiding C++ in favour of Haskell or, if I'm desperate and tired, Java is probably not the greatest career move. Is there a handy guide to C++ templates? Are they comparable to Haskell's type system?

http://www.boostpro.com/mplbook/

It's a bit off at the deep end though, but if you have a general idea of what's going on this book will explain the detail.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

AlsoD posted:

These last few pages have convinced me that my current plan of avoiding C++ in favour of Haskell or, if I'm desperate and tired, Java is probably not the greatest career move. Is there a handy guide to C++ templates? Are they comparable to Haskell's type system?

Someone can correct me if I'm wrong, as I'm not a professional programmer, but...

It's my understanding that Java, despite it's shortcomings, is a very widespread "pro" language in use by lots of places that pay people to write software. So, if that's what you mean by "not the greatest career move", you may be wrong.

taqueso
Mar 8, 2004


:911:
:wookie: :thermidor: :wookie:
:dehumanize:

:pirate::hf::tinfoil:

Thermopyle posted:

Someone can correct me if I'm wrong, as I'm not a professional programmer, but...

It's my understanding that Java, despite it's shortcomings, is a very widespread "pro" language in use by lots of places that pay people to write software. So, if that's what you mean by "not the greatest career move", you may be wrong.

Hopefully he means "not the greatest move for happiness over the life of my career". You can make money programming in a lot of different languages. If you become proficient at languages you like to use, you will be employable using those same languages.

Johnny Cache Hit
Oct 17, 2011

Thermopyle posted:

Someone can correct me if I'm wrong, as I'm not a professional programmer, but...

It's my understanding that Java, despite it's shortcomings, is a very widespread "pro" language in use by lots of places that pay people to write software. So, if that's what you mean by "not the greatest career move", you may be wrong.

It depends on where you want to work.

Plenty of jobs would never hire a person for a Java development position unless they had 5 years of Java experience or whatever.

But there are plenty of jobs that know an engaged programmer that uses a niche language like Haskell would be able to pick up any language thrown at them, and that what's important is knowing the foundations of programming - not a specific language.

Personally, those are the jobs I look for.

baquerd
Jul 2, 2007

by FactsAreUseless

Kim Jong III posted:

what's important is knowing the foundations of programming - not a specific language.

They are both important. Having a mastery of all of a specific language's quirks, standard library API knowledge, and general practice with a language will speed development time and reduce accidental introduction of language idiosyncratic errors.

ToxicFrog
Apr 26, 2008


AlsoD posted:

These last few pages have convinced me that my current plan of avoiding C++ in favour of Haskell or, if I'm desperate and tired, Java is probably not the greatest career move. Is there a handy guide to C++ templates? Are they comparable to Haskell's type system?

If by that you mean "not the best move for your employability", Java is if anything more widespread than C++ at this point (although there's a lot of C++ jobs around still, if you find the language appealing).

If you mean "not the best move for your happiness", well, I detest both C++ and Java, so I'm not the one to talk to. :v:

The General Programming Thread, C/C++ Thread, and Java Thread can probably stuff you full of information on their respective books and job markets as well.

NotShadowStar
Sep 20, 2000

Thermopyle posted:

Someone can correct me if I'm wrong, as I'm not a professional programmer, but...

It's my understanding that Java, despite it's shortcomings, is a very widespread "pro" language in use by lots of places that pay people to write software. So, if that's what you mean by "not the greatest career move", you may be wrong.

Nope. Consider you can quite literally hire 20 Java 'developers' from Bangladesh for the price of one in the US. That's the mentality you're up against when you look for Java/PHP/C# jobs. Also all the jobs you see are the equivalent of a pipefitter, just connecting pieces together and you're never doing anything interesting. Alternately, if you're a good Ruby/Python/Clojure/Haskell/Scala/Javascript developer, that automatically excludes you from that whole enterprisey horseshit and far more interesting places take notice of you.

NotShadowStar fucked around with this message at 20:54 on Nov 29, 2011

baquerd
Jul 2, 2007

by FactsAreUseless

NotShadowStar posted:

Nope. Consider you can quite literally hire 20 Java 'developers' from Bangladesh for the price of one in the US. That's the mentality you're up against when you look for Java/PHP/C# jobs.

This seems hit or miss as more and more companies understand why you put "developers" in quotes.

shrughes
Oct 11, 2008

(call/cc call/cc)

AlsoD posted:

These last few pages have convinced me that my current plan of avoiding C++ in favour of Haskell or, if I'm desperate and tired, Java is probably not the greatest career move. Is there a handy guide to C++ templates? Are they comparable to Haskell's type system?

I work at a C++-using job, it's a lot of fun.

C++ templates are very comparable to Haskell's type system. You can have templates parameterized on types, and you can have templates parameterized on class templates, like in Haskell.

For example in Haskell you can do data List a = ....

You could talk about the kinds of type constructors: List :: * -> *. List takes a type and produces a type.

and in C++ you can do

code:
template <class A> class List { ... };
In that case List<int> is a type.

In Haskell you can do data StateT s m a = ... where StateT :: * -> (* -> *) -> * -> *.

In C++ you can do

code:
template <class S, template <class> class M, class A>
class StateT { ... };
but since C++ is not lazily evaluated, making monad transformers is not a practical thing to do. In general, parameterizing something on a class template in C++ is a sign that you've fallen off the wagon.

The typeclasses of Haskell also have C++ analogues, in the form of overloaded functions.

Practical and conscientiously written C++ code does not look at all like Haskell code.

raminasi
Jan 25, 2005

a last drink with no ice
If your concern was that Java generics sound too convoluted and weird, then C++ is definitely not going to be a safer haven for you.

MrMoo
Sep 14, 2000

I've just been picking up a couple of new APIs at work (Thomson Reuters) and it's utterly depressing. C++ code written by poor C developers that skip all the basics, code copy and pasted from many other projects and not even bothering to change introduction text or pre-processor guards. Today I'm looking at C code that is conversely written by poor C++ Windows developers showing no basic understanding of C coding and loving up everything.

Who the gently caress puts static prototypes in public headers? Unfortunately this isn't them:

http://stackoverflow.com/questions/7912863/is-there-a-way-to-have-static-prototypes-and-public-ones-in-the-same-header-file

Apparently the C++ API is cleaned up a bit, they were previously adding "using namespace" inside public headers. The private headers in each example still does it though, and the C APIs certainly don't care about polluting namespace everywhere.

What gets me is a "lean high performance" API has examples comprising 20 headers and 20 C++ files for sending demo values and performing absolutely zero processing on the content.

Comedy note that a new "ultra performance" API uses select on Windows and this is an API designed and built on Windows and then ported to Solaris and Linux taking really crufty Windows API clones for i18n, configuration files and other services.

Bozart
Oct 28, 2006

Give me the finger.

tef posted:

or it's actually a common bug that lots of people overlook. most notably - jon bentley - who went to a lot of effort to check his c code.

From way back - this didn't just get past Jon Bentley but also Russ Cox, on the second edition.

There is some kind of glass half empty / half full nature to this. You can always improve your work, which is in some ways a cheerful thing to think on. It also means your work - in a medium so tractable that it is only one step removed from thinking - will always be imperfect, and reflect upon our own shortcomings. So we can laugh about relational tables with 1000 columns and rolling your own passwords and using comments as source control and the for-switch idiom, but I think we should spend some time focusing on subtle problems that we have difficulty with, instead of simple problems that we trivially avoid.

I've spent quite awhile trying to come up with one that was understandable, but they are all so domain specific or long-winded that I cannot. I apologize.

pokeyman
Nov 26, 2006

That elephant ate my entire platoon.
Thanks for wrecking the thread you jerk.

Zombywuf
Mar 29, 2008

Sooo, here's a horror I wrote...
code:
create or replace function session_get(
    id uuid
) returns Users.user_id%TYPE as $$
begin
    return (
        select
            u.user_id
        from
            Sessions s
            inner join Users u
                on s.fk_user_id = u.user_id);
end
$$ language plpgsql;

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
If we're on to horrors we write ourselves, here's something I did:
code:
final int[] butt = new int[1];
Runnable r = new Runnable() {
    @Override void run() {
        //stuff

        butt[0] = wat;
    }
}
Java :argh:

gonadic io
Feb 16, 2011

>>=

Jabor posted:

Runnable stuff

I don't get it, why does your code need a Runnable wrapper and what is "wat"?

TasteMyHouse
Dec 21, 2006
He's assigning to a final variable. I guess final as applied to array variables in Java doesn't make the elements of the array itself final? Or did this even compile?

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

TasteMyHouse posted:

He's assigning to a final variable. I guess final as applied to array variables in Java doesn't make the elements of the array itself final? Or did this even compile?

A final variable in Java is a special trick that allows closure-like behavior.

See this page for more information.

TasteMyHouse
Dec 21, 2006

Suspicious Dish posted:

A final variable in Java is a special trick that allows closure-like behavior.

See this page for more information.

Oh, that's cool.

Out of curiosity, is there a way to declare an immutable array in java?

ToxicFrog
Apr 26, 2008


Suspicious Dish posted:

A final variable in Java is a special trick that allows closure-like behavior.

See this page for more information.

ClosuresThatWorkAroundFinalLimitation posted:

Inner classes in Java capture ("close over") the lexical scope in which they are defined. But they only capture variables that are declared "final".

This is a problem when the closure is intended to modify such a variable. (The rationale for the limitation is that it simplifies the compiler writer's job!)

To overcome this limitation declare the variable as a final reference to a mutable object, such as an array of size one.

:stonk:

Never programming in Java again was the best decision I ever made.

Bozart posted:

There is some kind of glass half empty / half full nature to this. You can always improve your work, which is in some ways a cheerful thing to think on. It also means your work - in a medium so tractable that it is only one step removed from thinking - will always be imperfect, and reflect upon our own shortcomings. So we can laugh about relational tables with 1000 columns and rolling your own passwords and using comments as source control and the for-switch idiom, but I think we should spend some time focusing on subtle problems that we have difficulty with, instead of simple problems that we trivially avoid.

While I agree with this, I think it may be better off as a separate thread - what makes the horrors here horrors is that many of them are trivially avoidable even by novice programmers. "Coding subtle problems that bedevil even experienced programmers" doesn't have quite the same ring to it.

Furthermore, as you point out, it's a lot harder to come up with examples.

That said, I'd read the poo poo out of such a thread.

NotShadowStar
Sep 20, 2000
I think the latest attempt at adding lambdas in Java 7 after the last abortion is really just a syntax macro for anonymous inner classes, so you can only access final variables outside the scope of it. Which defeats all of the point of a real lambda or closure anyway but welp java.

quote:

and Java has been worked on by some of the greatest minds in the field

Every single one of them should be called out and publicly shamed. They took the brilliant Smalltalk language and hosed it all up because they thought that they couldn't sell something to aspergers filled engineers if it didn't look tangentially like C++.

1337JiveTurkey
Feb 17, 2005

ToxicFrog posted:

:stonk:

Never programming in Java again was the best decision I ever made.

Closures over non-final variables can lead to some interesting situations:
code:
public Runnable stackSchmack() {
	int i = 1;
	return new Runnable() {
		public void run() {
			System.out.println(i++);
		}
	};
}

public static void main(String… argv) {
	Runnable r = stackSchmack();
	for (int i = 0; i < 100; i++) {
		new Thread(r).start();
	}
}

ToxicFrog
Apr 26, 2008


1337JiveTurkey posted:

Closures over non-final variables can lead to some interesting situations:

I don't see how this is a "closures over non-final variables" issue as opposed to a "modifying shared state from multiple threads without synchronization" issue.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

NotShadowStar posted:

Every single one of them should be called out and publicly shamed. They took the brilliant Smalltalk language and hosed it all up because they thought that they couldn't sell something to aspergers filled engineers if it didn't look tangentially like C++.

I should take the time to point out that there are three things that we call Java:

  1. The Java language. It's very restrictive, silly, and behind the times. Simple concepts like "for...each" were introduced way after they should have been.

  2. The Java standard library. This is a huge thing. Parts of it are good, parts of it are bad. Speaking as a Linux desktop engineer, the part I deal with the most is AWT. AWT, or at least the X11 part of it, is trash. It implements grabbing a window's bitmap contents by asking the X server for one pixel at a time (see Java_sun_awt_X11_XRobotPeer_getRGBPixelsImpl), rather than using anything modern like XShmGetImage. I can't speak for the Windows or OS X parts of AWT, or for the rest of the standard library. It's been worked on by very smart people. It's been worked on by not so smart people.

  3. The JVM. The JVM is a very, very good piece of smart engineering. Java the language doesn't really show off the raw power of the JVM that well. Other languages like Scala or Jython show off the raw JVM much better than Java, the language.

Suspicious Dish fucked around with this message at 02:13 on Dec 1, 2011

ToxicFrog
Apr 26, 2008


Suspicious Dish posted:

I should take the time to point out that there are three things that we call Java:

At least in my case, when I bitch about Java, I am specifically bitching about Java the language or Java the library. The JVM is pretty sweet and I'm a big fan of Scala.

This is not to say that it couldn't be improved (tail call elimination and no type erasure, for example), but as far as I can tell all of my complaints about the JVM boil down to it needing to maintain backwards compatibility with every brain-damaged design decision Java-the-language has been subject to over the years.

Also, AWT is just as unpleasant and terrible no matter what OS you're on.

NotShadowStar
Sep 20, 2000
The JVM wasn't a Sun thing though, that came from the complicated history of Smalltalk. Indeed the smart people concluded correctly that the C++ style syntax wasn't the way to go but braindumbs at Sun was having none of it.

trex eaterofcadrs
Jun 17, 2005
My lack of understanding is only exceeded by my lack of concern.

NotShadowStar posted:

Every single one of them should be called out and publicly shamed. They took the brilliant Smalltalk language and hosed it all up because they thought that they couldn't sell something to aspergers filled engineers if it didn't look tangentially like C++.

Well... Yeah, they were right. Sun probably couldn't have foisted java as effectively as it did if it was much different than it is.

charliesome
Oct 21, 2010
This loving stack overflow thread:

http://stackoverflow.com/questions/8339192

1337JiveTurkey
Feb 17, 2005

ToxicFrog posted:

I don't see how this is a "closures over non-final variables" issue as opposed to a "modifying shared state from multiple threads without synchronization" issue.

There's nothing to synchronize on because there's no reason you ever need to synchronize a local variable when only its thread can touch it. It's also a "the stack frame doesn't exist any more" issue and a "allowing pointers to reference the stack" issue. They're not insurmountable issues, but they add complexity to the language and reduce the scope of optimizations. Additionally, closures being by value means they behave consistently with method call semantics: No variable will be changed in a method unless it happens within the method itself. Java in this case chose consistency over "more checkboxes = better than" language design.

Beef
Jul 26, 2004

quote:

There's nothing to synchronize on because there's no reason you ever need to synchronize a local variable when only its thread can touch it.

What? You're spawning 100 instances of that same thread. Yes it is a concurrency issue.

1337JiveTurkey
Feb 17, 2005

Beef posted:

What? You're spawning 100 instances of that same thread. Yes it is a concurrency issue.

Only because it's mutable. It's a violation of underlying language invariants for the sake of not using a Callable instead of a Runnable. That's what gets us languages like PHP.

Brain Candy
May 18, 2006

turby posted:

This loving stack overflow thread:

http://stackoverflow.com/questions/8339192

Q : "How do I make a hashing function that uses at most 20 characters in a string?"
A : "Use substring!"
A : "Use LINQ!"
A : "Nested ternary operators!"

:eng99:

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
this is my own code but it's awful as gently caress so I'm posting it

I have a Java library for Terraria player files. Items in the game previously were identified solely by their names. I went the immutable route and set up a static factory as so: (some irrelevant lines removed)
code:
    /**
     * Some idiot once said that premature optimization is the root of all evil.
     * I implemented a caching hash map to cut down on instances of this object.
     * @param itemName
     *            name of the item to return
     * @return the item of the specified name, not necessarily a new instance
     */
    public static Item of(String itemName) {
        // greetz to Knuth
        if (CACHE.containsKey(itemName))
            return CACHE.get(itemName);
        Item item = new Item(itemName);
        CACHE.put(itemName, item);
        return item;
    }
Well, after the most recent update, items now have both a name and a byte identifying their condition. I changed my code to this:
code:
    public static Item of(String itemName, int prefix) {
        // greetz to Knuth
        if (CACHE.containsKey(itemName))
            return CACHE.get(itemName);
        Item item = new Item(itemName, prefix);
        CACHE.put(itemName, item);
        return item;
    }
and then spent an hour trying to figure out why, when I wrote a player with 40 different versions of the same item, that the game was only seeing 40 items of the same condition.
:suicide:

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Aleksei Vasiliev posted:

code:
Some idiot once said that premature optimization is the root of all evil.

I hope you learned your lesson.

Dessert Rose
May 17, 2004

awoken in control of a lucid deep dream...

1337JiveTurkey posted:

Only because it's mutable. It's a violation of underlying language invariants for the sake of not using a Callable instead of a Runnable. That's what gets us languages like PHP.

What underlying language invariants does this violate? You started 100 threads that all call a method on an object that mutates shared state without synchronization.

If you didn't want to have that shared state then don't close over it. Or assign it to a closure-local variable.

C# handles this just fine.

kuf
May 12, 2007
aaaaaa
code:
switch(thefile_counter){
    case 1:
        break;
    case 2:
        break;
    case 3:
        break;
    ...
    case 52:
        break;
    case 53:
        break;
    case 54:
        thefile_counter = 0;
        break;
}
Yes, there were cases four to fifty-one. I hate undergrads.

NotShadowStar
Sep 20, 2000
Uh can't you write if (thefile_counter == 54) { thefile_counter = 0; } on the assignment and give him an F because ffffffffff

NotShadowStar fucked around with this message at 03:51 on Dec 2, 2011

Adbot
ADBOT LOVES YOU

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

DotFortune posted:

code:
switch(thefile_counter){
    case 1:
        break;
    case 2:
        break;
    case 3:
        break;
    ...
    case 52:
        break;
    case 53:
        break;
    case 54:
        thefile_counter = 0;
        break;
}
Yes, there were cases four to fifty-one. I hate undergrads.

Switch statements are jump tables, so they're faster than if statements!

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