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
Volguus
Mar 3, 2009
Not hard at all. In the worst case scenario you would have to write your own ant task or maven plugin (if whatever exists is not suitable). And that is quite easy and well documented. To make an LDAP call with Java is not a big deal at all (same goes for a http call), though if your LDAP server requires authentication to do anything, that authentication must come from somewhere: another properties file. And you just went full circle :).

Public/private key mechanism is another option, but then, the private key must reside somewhere as well. Depending how strict your requirements are, it can get quite hairy. I had once a security guy review my web application, and they complained that the username/password to the database were stored on the server (datasource file). And they suggested that i split them in several parts, all encrypted, and recreate both at runtime. After reviewing the work that had to be done to implement that, and the fact that the server was a company internal server, i thank them for their input and went on my merry way. There are cases when this is a valid option, and there are cases when it's not worth it.

Adbot
ADBOT LOVES YOU

Sang-
Nov 2, 2007
ANTLR 4.0 has just been released! http://www.antlr.org/wiki/pages/viewpage.action?pageId=29130850

Most exciting part to me (and probably tef :p) is:

quote:

As I was rewriting ANTLR, I wanted to experiment with a new variation of the LL(*) parsing algorithm. As luck would have it, I came up with a cool new version called adaptive LL(*) that pushes all of the grammar analysis effort to runtime. The parser warms up like Java does with its JIT on-the-fly compiler; the code gets faster and faster the longer it runs. The benefit is that the adaptive algorithm is much stronger than the static LL(*) grammar analysis algorithm in v3. Honey Badger takes any grammar that you give it; it just doesn't give a drat. (v4 accepts even left recursive grammars, except for indirectly left recursive grammars where x calls y which calls x).

Hot Yellow KoolAid
Aug 17, 2012
I'm having a problem with an intro java GUI assignment. I'm supposed to implement a mock radar display (similar to marine sonar) with a sweeping arm that spins every second. (The display shows other things, but I think I have those objects figured out). My attempts to implement the sweeping arm have been based off taking the java code for an analog clock's second hand and making it move 60X faster.

This is where I'm stuck. I'm using Graphics2D for GUI, and this is the code I have so far:
http://pastebin.com/xdU0aZMk

...and here is where I got the code for the analog clock:
http://javacodespot.blogspot.com/2010/05/java-analog-clock.html

Is implementing the swing-arm this way a lost cause? Some of the other analog clock/mock radar applications out there work by extending the Applet class instead of the Frame class (like I do), and I was wondering if that would be a better option.

Also, I need to implement grid lines in this somehow. Is there any way to draw lines using Graphics2D? I'm pretty sure I could solve this problem just by drawing some really slim rectangles.

ynef
Jun 12, 2002

Hot Yellow KoolAid posted:

I'm having a problem with an intro java GUI assignment. I'm supposed to implement a mock radar display (similar to marine sonar) with a sweeping arm that spins every second. (The display shows other things, but I think I have those objects figured out). My attempts to implement the sweeping arm have been based off taking the java code for an analog clock's second hand and making it move 60X faster.

This is where I'm stuck. I'm using Graphics2D for GUI, and this is the code I have so far:
http://pastebin.com/xdU0aZMk

...and here is where I got the code for the analog clock:
http://javacodespot.blogspot.com/2010/05/java-analog-clock.html

Is implementing the swing-arm this way a lost cause? Some of the other analog clock/mock radar applications out there work by extending the Applet class instead of the Frame class (like I do), and I was wondering if that would be a better option.
Have you covered threads yet? I think the idea is to schedule a thread that fires a couple of times per second, draws the radar arm in a new position (if you have a counter for the angle, increase it and then take the value modulo 360 to figure out where it should point this time), and then puts airplane dots at the correct positions.

Are the planes supposed to move as well?

Post a link to the actual assignment, please.

Hot Yellow KoolAid posted:

Also, I need to implement grid lines in this somehow. Is there any way to draw lines using Graphics2D? I'm pretty sure I could solve this problem just by drawing some really slim rectangles.
You have code in the file you pasted that draws lines, dude.

omeg
Sep 3, 2012

I have an App that uses Eclipse rich client as a GUI base. I'm writing a plugin for it and all is well, but now I want to support a new App version. I created a new target platform and added the app's jar dir (new version) as before in Eclipse, but now I'm getting an error that some type cannot be resolved. It's apparently indirectly referenced by some class file. The error only appears if I target the new App version. I see that some App jars do reference that missing type/namespace but I don't see it actually defined anywhere. What the hell is going on here? I even did a broad file search on the whole App directory and didn't find anything related.

Max Facetime
Apr 18, 2009

This might be a case where a method has moved from a subclass to its superclass between versions. Or maybe vice versa. Every method your code calls gets a constant pool entry. This entry points to some class or interface which has the correct method. This is all pretty hairy so I'm not certain of the details, but I think it's possible that it might reference a package-private superclass if the public/protected subclass doesn't have an override of the method. If such superclass gets removed in the next version then binary-compatibility is broken.

As a practical suggestion you could try looking at the generated bytecode and constant pool entries with javap if you know which of your classes is having problems. You could also try changing the code to use interface or base class types, if possible.

omeg
Sep 3, 2012

I found the class definition, it's a pretty basic class that doesn't seem to be different in the previous version. Added the jar manually and it seems to work.

Insane Totoro
Dec 5, 2005

Take cover!!!
That Totoro has an AR-15!
I have a homework question that I have been working on and I am trying to logically think out the last part. Basically I already constructed an array of objects by making a constructor. Alright so now I want to print out the attributes of the objects to the user. Let's say that each object has two attributes, cost and volume. So I would want to say:

"The cost is: $$$$"
"The volume is: XXXXX"

So basically I was thinking how would I write one "primary" method to do the formatting and iterating through the array of objects... and then have "smaller" methods do the actual printing.

But I have one question the textbook seems to omit. How do you pass a reference to a single object to a method?

armorer
Aug 6, 2012

I like metal.
Are you asking how to specify a single element in an array? (Use brackets and an index after the array variable.) Or something else?

Insane Totoro
Dec 5, 2005

Take cover!!!
That Totoro has an AR-15!
Hmmm, well I am specifying a certain element in an array.

But how would I make a void method PRINT a certain attribute of that object in that array. The object has an attribute of bananaCost:

public static void printCost(int[] A){

//something in here that prints the bananaCost attribute's value

}

armorer
Aug 6, 2012

I like metal.
The built in mechanism to print to stdout is:
code:
 System.out.print("Hello world");
or if you want a newline at the end:
code:
 System.out.println("Hello world");

pigdog
Apr 23, 2004

by Smythe
It's hard to understand the context, though it appears you're doing something wrong. Can you post the code so far and/or the text of the assignment? Are you trying to print each object's cost and volume, or the sum of the ones contained in the array?

Insane Totoro
Dec 5, 2005

Take cover!!!
That Totoro has an AR-15!
Well here's an example of what I want to do. The constructor is in another class

code:

import java.util.Scanner;

public class myProject{

    public static void main(String[] args) {
        
          Scanner input = new Scanner(System.in);
          
          System.out.println("Enter the total number of tenants: "); 
          int numTenants = input.nextInt();
          
          Tenant[] tenantMatrix = new Tenant[numTenants];
          
          for(int i = 1; i <= numTenants; i++){
              
              String firstName;
              String lastName;
              String aptNumber;
              int yearlyRent;
              
              System.out.println("Enter the first name of tenant " + i + " : "); 
              firstName = input.next();
              
              System.out.println("Enter the last name of tenant " + i + " : "); 
              lastName = input.next(); 
              
              System.out.println("Enter the apartment number of tenant " + i + " : "); 
              aptNumber = input.next();
                      
              System.out.println("Enter the yearly rent of tenant " + i + " : "); 
              yearlyRent = input.nextInt();
              
              tenantMatrix[i-1] = new Tenant(firstName, lastName, aptNumber, yearlyRent);
          
              
          }
          
        for(int j = 1; j <= numTenants; j++){
            
            //print each attribute here

            //"The person's full name is........" 
            //"The person's apartment number is........"
            //"The person's monthly rent is....."
            //I have methods that will calculate their monthly rent, etc.








          )            
            
            
        }

       
        
        
    }
}

Insane Totoro fucked around with this message at 18:51 on Jan 28, 2013

Insane Totoro
Dec 5, 2005

Take cover!!!
That Totoro has an AR-15!
Basically I have constructed several methods (objects). I want to pass the object or a particular attribute of one of those objects into a method. How do I do that?

armorer
Aug 6, 2012

I like metal.
Based on the code you have above calling something like
code:
myMethod(tenantMatrix[i]);
will pass a particular Tenant object into your method. You will need to make sure your methods take a single parameter of type Tenant for this to work.
code:
public void myMethod(Tenant tenant) {
 //do stuff
}

Insane Totoro
Dec 5, 2005

Take cover!!!
That Totoro has an AR-15!
Ohhhhhh I think I get what you are trying to say there.

Basically "Tenant" creates a new variable type in itself?

I am trying to understand this conceptually as well, not just "finishing homework."





So this is what I am conceptually trying to do. However the firstName and lastName variables are obviously in a different class right now. How would I pull them in? I thought I already passed that object to this method? Am I missing some "rule" here conceptually?


code:
public void printFullName(Tenant tenant){
           String fullName = firstName + lastName;
           System.out.println(fullName);
               
        }

Insane Totoro fucked around with this message at 19:36 on Jan 28, 2013

armorer
Aug 6, 2012

I like metal.
Well, there are a lot of ways of going about this. You have a class myProject (which ought to start with a capital letter according to the class naming conventions, so let's say MyProject). I assume that you have another class Tenant, since that is what you are manipulating. You could put methods on Tenant which print various attributes of that tenant:

code:
public void printFirstName() {
    System.out.print(this.firstName);
    //System.out.print(firstName); //would also work just fine.  You can omit "this." if you want
}
People tend to frown on this kind of thing though because the Tenant doesn't really need to print stuff. Since you have MyProject, you can instead define a method on that, which prints the name of a Tenant that is handed to it as a parameter. In this case you are saying something like "MyProject has the ability to print the first name of a Tenant, if you provide it with the Tenant."

code:
public void printFirstName(Tenant tenant) {
    System.out.print(tenant.firstName);
}
Honestly this is all extremely basic object oriented design stuff, so if you have some course material which covers defining classes and methods you may want to read through it again.

Insane Totoro
Dec 5, 2005

Take cover!!!
That Totoro has an AR-15!
I am re-reading the textbook on how to call an attribute of an object. I actually don't see anywhere in this text where it says I would use anything of the sort like "tenant.firstName"

Now that certainly MAKES SENSE to me when presented to me but the text doesn't really make that clear or that this is even possible. I have gone over this with a friend of mine and it seems to me that he is also equally confused on similar things like this that I am.

Without going too TL;DR I am pretty sure that our textbook is just wholly inadequate. Can anyone possibly recommend a proper textbook that covers most of Java fundamentals? I am all ears to trying to do this more myself.


Edit: This was not meant to sound whiny. I am genuinely frustrated after having reread my lecture notes and textbook multiple times.

Insane Totoro fucked around with this message at 19:44 on Jan 28, 2013

armorer
Aug 6, 2012

I like metal.
Using something like "tenant.firstName" inside a method in MyProject will work as long as the firstName attribute on Tenant was declared as public (or protected if MyProject is in the same package as Tenant). If it was declared private, or if MyProject is not in the same package, you will need to make a method like

code:
public String getFirstName() {
    return firstName;
}
in your Tenant class in order to expose firstName. If you have that method defined, then you would write tenant.getFirstName() in MyProject. Your book probably cover this sort of thing under a discussion about "access modifiers". Common programming practice in Java is to define all attributes as private, and provide "getters and setters".

Turkeybone
Dec 9, 2006

:chef: :eng99:
When you say new Tenant(first, last, number, rent), you are instantiating a new object type that you created, yes. All objects are subclasses of the OG, type Object. One such method that is inherited from Object is toString(). Since you are basically spitting out the fields of this object, you might want to look into overriding toString(). Basically you write the method public String toString() that does all the printing etc that you want to do.

If your fields are public then for any Tenant t you can say t.firstName t.lastName

If you wanted to count the number of tenants created, you could create a static variable like public static int tenantCount, and then increment it in the constructor. So then if you wanted to call the current number of tenants, rather than t.tenantCount you would say Tenant.tenantCount, because it's a static variable.

Also, just another random point, if you're not specifically going to use i, you might as well just write your for loop as iterating over the elements in an array. So if you want to print the details for each tenant in the tenantMatrix, you can do

code:
for (Tenant t: tenantMatrix){

t.methodThatDoesYourStuff

}
or something to that effect.

Just thoughts from one novice, please correct me where appropriate.

Insane Totoro
Dec 5, 2005

Take cover!!!
That Totoro has an AR-15!

armorer posted:

in your Tenant class in order to expose firstName. If you have that method defined, then you would write tenant.getFirstName() in MyProject. Your book probably cover this sort of thing under a discussion about "access modifiers". Common programming practice in Java is to define all attributes as private, and provide "getters and setters".

I was actually just thinking about that. Why wouldn't you just want to make them public? What's the "bad" in that? Or does this apply largely to more complex programming? I feel like I don't have a firm grasp on "getters and setters" and my textbook (Liang, 8th ed) is somehow obtuse to me. Is it something like... you don't want other things in your program modifying certain bits of code, so you make it private? And then the getters and setters are basically creating a "reference" (like just copying the value, not actually letting the other code touch the value) and then that variable is accessible, although the original variable isn't modifiable outside of it being entered into an object? I feel like I am not explaining this well. I guess I also haven't run into a situation where that is a good thing to make it private?

Turkeybone posted:

Just thoughts from one novice, please correct me where appropriate.

Oh it is perfectly fine. I am a novice too. This is all new to me conceptually (I was originally a history major, ten years ago).

I have another novice question as well. Bear with me, please.

So my professor says to me that I am to basically copy his code so that I can read a .txt file into a program and basically divide that .txt file into single words so that each word can be placed inside an array. Each word in the .txt file is on a single line. Example:

Apple
Banana
Coconut
Durian
Endive

So I would want to put each one of those words into an array.

The code that he gave me is thus: (my comments in //)

Java code:
private void readList(String filename){ // the professor says the method MUST be called "private void readList"???
        PrintWriter fout = null;
        BufferedReader fin = null; // the variable for reading in the text
        try { // try catch block
            fin = new BufferedReader(new FileReader("Fruit.txt")); //the file that needs to go in your top level folder
            String line = null; // this line creates a string
            while ((line = fin.readLine()) != null) { //keep reading in each line until it is "null" (end of file)
                fout.println(line); //so this prints out the text.... but how do I get it into an array?
            }
            fin.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            fout.close();
        }
    }
}

Well I thought I might just be able to iterate through the .txt file and create an array based on the length of that .txt file. However the .txt file does not always have a consistent number of words. How can I declare an array if I don't know how long the array needs to be? And given the way I must name the method, it seems I cannot even return an array from the method. This seems very confusing to me and I am at a loss as to what I should be doing. I suppose I could write my own method that lets me return something but that seems to violate the "terms" of the assignment.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.
Is anybody else here using the early-access Java 8 builds and finding that the compiler is really fragile? It seems to crash on code for no clear reason with an AssertionError. Sometimes I can fix it (no idea how), sometimes I have to switch builds. Builds 72-75, building with IntelliJ IDEA.

edit: Using the standard builds, not the "lambdas everywhere!" builds

Malloc Voidstar fucked around with this message at 02:54 on Feb 3, 2013

SneakyPriest
Oct 31, 2011

Insane Totoro posted:

Well I thought I might just be able to iterate through the .txt file and create an array based on the length of that .txt file. However the .txt file does not always have a consistent number of words. How can I declare an array if I don't know how long the array needs to be? And given the way I must name the method, it seems I cannot even return an array from the method. This seems very confusing to me and I am at a loss as to what I should be doing. I suppose I could write my own method that lets me return something but that seems to violate the "terms" of the assignment.

Depending on whether this also violates the terms of the assignment or not, consider using an ArrayList. It's essentially an array that grows as you add to it; since you don't know the size of the array in advance it seems like it would be a good fit.

About not being able to return an array from the method: if you declare/initialize the array outside of the method, you can modify it. That is, if you do something like:

code:
class YourAssignmentClass
{
	public ArrayList<String> text;
	public static void main(String args[])
	{
		text = new ArrayList<String>();
	}
}
Then within the method you can add Strings as you read them, and they won't be lost when you leave the scope of the method.

Max Facetime
Apr 18, 2009

Aleksei Vasiliev posted:

Is anybody else here using the early-access Java 8 builds and finding that the compiler is really fragile? It seems to crash on code for no clear reason with an AssertionError. Sometimes I can fix it (no idea how), sometimes I have to switch builds. Builds 72-75, building with IntelliJ IDEA.

Not me, but I've been playing with Checker Framework now that there's a new version and it has a working Eclipse plugin. It makes heavy use of the expanded annotation system in Java 8 and the latest version has this gem in its changelog:

pre:
Adapt to underlying jsr308-langtools changes.
  Most visible change is syntax for fully-qualified types, from
  @A java.lang.Object to java.lang.@A Object.
:monocle:

Features might still be in some flux!

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe

Insane Totoro posted:

I was actually just thinking about that. Why wouldn't you just want to make them public? What's the "bad" in that? Or does this apply largely to more complex programming? I feel like I don't have a firm grasp on "getters and setters" and my textbook (Liang, 8th ed) is somehow obtuse to me. Is it something like... you don't want other things in your program modifying certain bits of code, so you make it private? And then the getters and setters are basically creating a "reference" (like just copying the value, not actually letting the other code touch the value) and then that variable is accessible, although the original variable isn't modifiable outside of it being entered into an object? I feel like I am not explaining this well. I guess I also haven't run into a situation where that is a good thing to make it private?

Making local variables public is generally considered bad coding practice (with a few exceptions) because you want to make absolutely sure that nothing outside the class itself can modify its data without explicitly wanting to (i.e. via a set method.)

Getters and setters don't have to be complicated or hard to understand (although it does become somewhat complicated if working with objects rather than primitives.) For primitives these are examples of a get and a set:

Java code:
int value = 0;

//Getter
public int getValue() {		//Int is return type because value is an int.
	return this.value;	//You simply return the int, value, which is requested by the method
}

//Setter
public void setValue(int value) {	//void return type because method just modifies local variable.
	this.value = value;		//Set local variable value to passed value.
}
When it comes to objects this becomes slightly more complicated because with objects you get a reference to the object (rather than a copy) in your getter. This means that if the getter is called to assign the object to a variable name, every time you make changes to that object, you make changes to the local object in the class you got it from. This can be circumvented by using the Object method clone().

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
If you want to sound like somebody with fancy certifications and expertise the technical terms for "getters" and "setters" are "accessors" and "mutators", respectively. :eng101:

While these may seem like unnecessary boilerplate, especially in the case where a member could be simply declared final, they serve an additional purpose beyond just controlling access to members. In many situations you might find it necessary to introduce additional side-effects when a field is read or modified- for example, clearing caches or notifying observers. If you expose an API with public fields you're stuck. If you expose an API with accessors and mutators you can introduce this behavior without changing any contracts. The designers of C# recognized how common this pattern was and provided Attributes to add syntactic sugar which makes it look like you have a public field but provides all the functionality of wrapping the field in methods.

edit: Oh, also you cannot naively depend on Object.clone(). Objects which do not implement Cloneable will throw an exception and the semantics of Object.clone() do not specify whether it should produce a deep-copy or shallow-copy of an object's members, so you never know what somebody's implementation will do. It's a nasty little misfeature of Java.

Internet Janitor fucked around with this message at 16:25 on Feb 3, 2013

Insane Totoro
Dec 5, 2005

Take cover!!!
That Totoro has an AR-15!
I am taking notes and digesting all your sage advice and you guys should just write a textbook! You would do better than most authors

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Yeah but all the examples would use butts and farts instead of foos and bars.

Insane Totoro
Dec 5, 2005

Take cover!!!
That Totoro has an AR-15!
Creating an array of butts would be a great sample problem

Turkeybone
Dec 9, 2006

:chef: :eng99:
Yeah, for your adding to an array, definitely look into learning about ArrayList. It lets you append and remove list elements (array items) without having to set the size beforehand.

Sedro
Dec 31, 2008

Internet Janitor posted:

The designers of C# recognized how common this pattern was and provided Attributes to add syntactic sugar which makes it look like you have a public field but provides all the functionality of wrapping the field in methods.
I think you mean properties.

Doctor w-rw-rw-
Jun 24, 2008

carry on then posted:

Yeah but all the examples would use butts and farts instead of foos and bars.

I like big-endian butts and I can not lie
You other hosts can't deny


(Java is big-endian)

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
Sedro: Oh, whoops. I guess I should actually read documentation I link to, hunh.

Doctor w-rw-rw-
Jun 24, 2008

Internet Janitor posted:

If you want to sound like somebody with fancy certifications and expertise the technical terms for "getters" and "setters" are "accessors" and "mutators", respectively. :eng101:

While these may seem like unnecessary boilerplate, especially in the case where a member could be simply declared final, they serve an additional purpose beyond just controlling access to members. In many situations you might find it necessary to introduce additional side-effects when a field is read or modified- for example, clearing caches or notifying observers. If you expose an API with public fields you're stuck. If you expose an API with accessors and mutators you can introduce this behavior without changing any contracts. The designers of C# recognized how common this pattern was and provided Attributes to add syntactic sugar which makes it look like you have a public field but provides all the functionality of wrapping the field in methods.

edit: Oh, also you cannot naively depend on Object.clone(). Objects which do not implement Cloneable will throw an exception and the semantics of Object.clone() do not specify whether it should produce a deep-copy or shallow-copy of an object's members, so you never know what somebody's implementation will do. It's a nasty little misfeature of Java.
(quoting IJ but more of a general reply)

As a matter of engineering, while you may find situations where you would like to introduce additional side-effects when a field is read or modified, IMO in few circumstances _should_ you. BTW, you can use Lombok annotations to generate getters and setters for you in Java (it's a project that you can add to yours, not a feature of Java on its own though).

If you are listening to changes in an object, triggering something after each change may be a bad idea. Let's say you mutate a huge batch of objects all at once, and each object connects to a cache, updates it with its state, and then disconnects. The overhead would be staggering. Now if you were changing multiple properties of each object, that could be multiplicatively worse. Clearly, then, you need to manage the state manager, but from outside of the object somehow to let it know. Either you let the abstraction leak through and tie the object to its state manager, or you do ugly things.

My favorite pattern is to have immutable objects with private final member variables. This means that you set the values at construction and they last forever more. I make the constructor private and add a public static class (inside the data class, so it has access to the private constructor) that is essentially a mutable version of the data class with no setters, and a .build() function that calls and returns the data class's constructor.

In general, I find immutable is easier to deal with than mutable. No worries about it changing state; in fact, it pushes that abstraction outside of itself, so that you're managing state outside the object already, and if you need to start a transaction or what-have-you, it's clear where that should be done. Things are, by default, atomic.

Of course, it probably burns a little memory, but also note that you can avoid a lot of defensive copying if your inputs are known to be immutable.

EDIT: Oh, and also the visibility of mutable values on different threads is not guaranteed to be synchronized, I believe, so a mutable object won't be updated on all threads immediately without synchronization unless you use the Atomic* (AtomicInteger, AtomicBoolean) versions of them. That is to say, if an object's property is updated twice from different threads, you might get corruption, whereas there is no such concern with immutable objects (and sharing builder objects across threads is preposterously stupid)

Doctor w-rw-rw- fucked around with this message at 17:48 on Feb 3, 2013

Internet Janitor
May 17, 2008

"That isn't the appropriate trash receptacle."
A totally valid criticism. I was just pointing out a common use case.

Doctor w-rw-rw-
Jun 24, 2008

Internet Janitor posted:

A totally valid criticism. I was just pointing out a common use case.

Yeah, I figured you already knew, it was just the line "In many situations you might find it necessary to introduce additional side-effects when a field is read or modified" that made me want to point out that encouraging side effects is in large part a path of pain and sadness, since that's not immediately obvious to many. My philosophy is generally to have a clear distinction between data and behavior.

Paolomania
Apr 26, 2006

Another reason to use accessors is to ensure change visibility across threads and other concurrency reasons. Althought 'volatile' will work in some cases, protecting member with methods allows you to apply explicit access synchronization / memory barriers.

Max Facetime
Apr 18, 2009

Internet Janitor posted:

edit: Oh, also you cannot naively depend on Object.clone(). Objects which do not implement Cloneable will throw an exception and the semantics of Object.clone() do not specify whether it should produce a deep-copy or shallow-copy of an object's members, so you never know what somebody's implementation will do. It's a nasty little misfeature of Java.

There's quite a few of those in addition to Object.clone():

Serializable and Object(Input/Output)Streams, which introduce another way of creating objects, this time without calling constructors. If you use serialization you add another public API to your classes without the ease-of-use of Javadoc. This should have been a separate library.

Object.wait()/Object.notify(), which put a lock and a monitor in every object, when this could have gone into a separate Standard Library class.

The use of SecurityManagers to implement sandboxing by blacklisting parts of the Standard Library at runtime. This should have been done by compiling and running against smaller subsets of the Standard Library API.

Lazy classloading and linking. This adds a bunch of non-determinism at runtime and in exchange allows you one micro-optimization where a singleton can be initialized on first use without needing to be synchronized. Classloading and linking should have been restricted to happen during Class.forName() and other such method calls.

Malloc Voidstar
May 7, 2007

Fuck the cowboys. Unf. Fuck em hard.

Win8 Hetro Experie posted:

Serializable and Object(Input/Output)Streams, which introduce another way of creating objects, this time without calling constructors. If you use serialization you add another public API to your classes without the ease-of-use of Javadoc. This should have been a separate library.
They actually very recently tried to remove serialization, or at least it was seriously considered and worked on. Fun to see how horrifyingly badly designed it is: "The protocol was designed with the assumption that the serialized stream would be transmitted over an unreliable connection. It is for this reason that each object and descriptor is written twice to the stream, to allow the bytes to be compared by the receiver. In severely-degraded environments, e.g., Microsoft Windows machines running the McAfee Antivirus program, the TC_OBJECT constant and associated object data may be written to the serialized stream up to eight times due to timeouts caused by real-time virus scanning."

Adbot
ADBOT LOVES YOU

Max Facetime
Apr 18, 2009

Hahaha, this is great

JEP 154: Remove Serialization posted:

Another motivation to removing serialization is that the transient keyword is slated to be re-allocated to another Java language feature planned for a future release. Details of this language feature will be outlined in a future JEP.

[...]

Risks and Assumptions

Implementation of this proposal may hinder the adoption of Java 8.

There is some chance that the Java SE 8 (JSR 337) Expert Group will object to this plan or, at the very least, revise it significantly.

If the compatibility option to re-enable serialization requires that the JDK ship with two copies of rt.jar (or two copies of the JDK modules) then it may have some impact on the size of the JDK download.

Impact
◾Compatibility: High
◾Documentation: Medium
◾TCK: High
◾Twitter: High

I knew there was no way in hell that this would ever be done so I looked at the mailing list this was posted to see the fireworks. Unfortunately the people there caught on to it being an April fools joke much quicker than I would have.

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