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
carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

PierreTheMime posted:

I have a Swingworker to go fetch records and hunt through them to search for a given pattern. This works great, but on larger groups of records I wanted to add a JProgressBar to give the user an idea of how much longer it would be. I'm having trouble understanding how to properly implement the Process() method, though. I looked up some examples and attempted to use it as-is, but where theirs worked mine only publishes after the entire search is completed, so it will sit at 0% and then jump to 100%. The kicker being I can do a stdout of the increment values and that works in real-time just fine.

Essentially what I have is this:
code:
	@Override
	protected void process(List<Integer> jobNums) {
		int i = jobNums.get(jobNums.size()-1);
		jpb.setValue(i);
	}
	
	@Override
	protected DefaultListModel<String> doInBackground() throws Exception {

		int i = 1;
		(do work)
		jpb.setMaximum(jobsListing.size());
		Iterator<xxxxx> jobItems = jobsListing.iterator();
		while (jobItems.hasNext()) {
			publish(i);
			(do more work)
			i++;
		}
	
		return yyyy;
	}
Tell me what dumb thing I'm doing, thread. :(

I may be chasing down the wrong thing, but how are you setting up your progress bar? Are the values of i starting at 0 and going to 100? Or are they some other range?

Adbot
ADBOT LOVES YOU

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

carry on then posted:

I may be chasing down the wrong thing, but how are you setting up your progress bar? Are the values of i starting at 0 and going to 100? Or are they some other range?

For the time being it's just sitting in my main GUI layout, counting up from 0 to however many records it's searching through (jpb.setMaximum(jobsListing.size())). The thread publishes the final value (the maximum size of the records found) to the JProgressBar just fine, but all values in between are being ignored for some reason.

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE

carry on then posted:

Absolutely not in my experience.

Well, "modifying a stream as it's copied from source to destination" is exactly the wheelhouse of `sed`. Maybe your coworkers just suck at their jobs?

I guess reinventing the wheel in a programming language that is wildly inappropriate for the task is nothing new though.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

KildarX posted:

Welp last question of the year;

So as prep for the final we have to create a parralel array of type String and Int sort them and then do other things with it, get the highest, lowest, etc. So I pretty much have an idea on how to do the rest of it, but I'm stuck at how to get the arrays out of a sort method

code:
	private static [insert value here] sortprint(int[] grades, String[] names)
        [insert code to sort the grades[] and then place the names[] in the correct index] 
        return something;
	
I have code to sort both arrays so that the grades[] get sorted and the names[] align correctly so that if I input an array such that

code:
 int[] grades = [20,10,05];
 String[] names = [c,b,a];
goes through sort;
output int[] grades = [ 05,10,20]
output String[] names = [ a, b, c]

I just can't figure out how to return the arrays. I certainly can't return both a String[] and an int[] from the same method right? I thought about combining them into an Object[][]; but that work around is apparently dumb according to the internet. Another weird way I thought about it is to have a array copy method, so I have two sets of arrays. I throw one into the sort method to return array set1's int[] and throw the other set through the same sort except this sort method will return Strings[], but four arrays and two methods seems a little much to have been the answer. Ideas?

Two approaches.

Create an object that holds the two arrays, pass that in, and use it for the return type.

Or return void, accept two arrays, and modify them in place as they are.

Volguus posted:

And then you will have student A with grade 2.5 even though the grade he got was 9.5. Great job. Would have loved to have you create the grading programs for the schools I've been to, since my name starts with an Z, I would have been top of the class all the time :).

Only if you implement it wrong? This is totally off dude. You can do it in-place if you want to. You just have to operate on both arrays at the same time. Its really not hard.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

PierreTheMime posted:

I have a Swingworker to go fetch records and hunt through them to search for a given pattern. This works great, but on larger groups of records I wanted to add a JProgressBar to give the user an idea of how much longer it would be. I'm having trouble understanding how to properly implement the Process() method, though. I looked up some examples and attempted to use it as-is, but where theirs worked mine only publishes after the entire search is completed, so it will sit at 0% and then jump to 100%. The kicker being I can do a stdout of the increment values and that works in real-time just fine.

Essentially what I have is this:
code:
	@Override
	protected void process(List<Integer> jobNums) {
		int i = jobNums.get(jobNums.size()-1);
		jpb.setValue(i);
	}
	
	@Override
	protected DefaultListModel<String> doInBackground() throws Exception {

		int i = 1;
		(do work)
		jpb.setMaximum(jobsListing.size());
		Iterator<xxxxx> jobItems = jobsListing.iterator();
		while (jobItems.hasNext()) {
			publish(i);
			(do more work)
			i++;
		}
	
		return yyyy;
	}
Tell me what dumb thing I'm doing, thread. :(

I haven't worked with SwingWorker but looking at the javadoc do you need to call setProgress() ?

publish() calls are queued up, so if you call publish() 5 times you may only get a single call to process() which contains all 5 results. You can't depend upon publish() to do your progress updates. You need setProgress().

Defenestrategy
Oct 24, 2010

Thanks everyone. I was sleep deprived doing that, and the reason I wasn't getting it to sort was because I didn't order a printarray thing I made so it would out put both arrays nicely, put both arrays out nicely again,and then sort. and leave me confused that it wasn't sorting. So... don't code when your under a ton of stress and lack of sleep?

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Paul MaudDib posted:

Well, "modifying a stream as it's copied from source to destination" is exactly the wheelhouse of `sed`. Maybe your coworkers just suck at their jobs?

I guess reinventing the wheel in a programming language that is wildly inappropriate for the task is nothing new though.

Please point me to the location where sed resides by default on a standard Windows Server installation

Please point me to the data set where sed resides on a standard zOS installation

Please point me to how I should be using sed in a platform independent way that does not include shipping a third party binary with the product, which requires legal approval.

Not everyone writing Java is doing so for one-off tasks on their local system.

spiritual bypass
Feb 19, 2008

Grimey Drawer
Anyone in here ever tried Apache ISIS? Looks like a really convenient way to get a working application out the door, but the huge amount of code generation sounds potentially risky.

pigdog
Apr 23, 2004

by Smythe

carry on then posted:

Please point me to the location where sed resides by default on a standard Windows Server installation
https://msdn.microsoft.com/en-us/commandline/wsl/install_guide :v:

quote:

Please point me to the data set where sed resides on a standard zOS installation
$ which sed

I mean I'm really surprised if it doesn't come standard with any Unix-like operating system and/or built into shell.

Not that I use it personally, perl -pe usually does the trick for me :)

baquerd
Jul 2, 2007

by FactsAreUseless

rt4 posted:

Anyone in here ever tried Apache ISIS? Looks like a really convenient way to get a working application out the door, but the huge amount of code generation sounds potentially risky.

Usually they use a Blackhawk on ISIS, not the Apache.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

Zaphod42 posted:

I haven't worked with SwingWorker but looking at the javadoc do you need to call setProgress() ?

publish() calls are queued up, so if you call publish() 5 times you may only get a single call to process() which contains all 5 results. You can't depend upon publish() to do your progress updates. You need setProgress().

I modified it to essentially match the example straight out of the Javadoc and I'm not having updates.

Basically here's what I have (just the snippets that are related/updated)...

GUI class:
code:

private JProgressBar jpb = new JProgressBar(0,100);

FindJobsByScript searchJobs = new FindJobsByScript(aeconnection, teams.getSelectedItem().toString(), findJobs.getText(), teams);
searchJobs.addPropertyChangeListener(
	new PropertyChangeListener() {
		 public  void propertyChange(PropertyChangeEvent evt) {
			if ("progress".equals(evt.getPropertyName())) {
				jpb.setValue((Integer)evt.getNewValue());
			}
		}
	});
searchJobs.execute();

FindJobsByScript class:
code:

@Override
protected DefaultListModel<String> doInBackground() throws Exception {

	int i = 1;
	(do work)
	Iterator<xxxxx> jobItems = jobsListing.iterator();
	while (jobItems.hasNext()) {
		System.out.println((100*i)/jobsListing.size());
		setProgress((100*i)/jobsListing.size());
		(do more work)
		i++;
	}
	
	return yyyy;
}

I'm getting the proper output with a test stdout, but it's still just updating at the completion.

PierreTheMime fucked around with this message at 18:06 on Nov 10, 2016

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

I don't think you should be doing that setMaximum call on the progress bar from within doInBackground, that runs on a worker thread and you might get concurrency issues?

e- why are you setting it to the size of jobsListing anyway? Aren't you covering your progress value to 0-100 by hand? If you have a lot of jobs that might make your progress look very small

baka kaba fucked around with this message at 18:05 on Nov 10, 2016

Volguus
Mar 3, 2009
As far as I can see there is nothing wrong with the SwingWorker. It really should work. Something else must be the culprit. However, I did notice that you have "jpb.setMaximum(jobsListing.size());" in the doInBackground method. Don't. That method gets executed in a different thread than the UI thread, and it should not update Swing components. You are telling the progress bar that it goes from 0 to 100 when you create it. Just calculate the progress properly and you don't need to change the max size.

But , other than that, which shouldn't really have an effect on how it work, I can't see anything wrong with the code.

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

baka kaba posted:

I don't think you should be doing that setMaximum call on the progress bar from within doInBackground, that runs on a worker thread and you might get concurrency issues?

Sorry that was already removed. I accidentally copied it from my old post, but it's gone. Edited.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

PierreTheMime posted:

Sorry that was already removed. I accidentally copied it from my old post, but it's gone. Edited.

Is it gone or are you doing it somewhere else? I edited because I noticed you're also converting your progress range to 0-100, you need to pick one

Honestly I think you need to post your whole task class, the threading stuff means certain things have to go in certain methods or you'll get inconsistent behaviour, so it could be something sneaky like that

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord

baka kaba posted:

Is it gone or are you doing it somewhere else? I edited because I noticed you're also converting your progress range to 0-100, you need to pick one

Honestly I think you need to post your whole task class, the threading stuff means certain things have to go in certain methods or you'll get inconsistent behaviour, so it could be something sneaky like that
I'll double check but I'm pretty sure I removed it. I had it originally because it was just going to increment from 0 to the max number of jobs, but I changed it to percentages to avoid confusing people.

I'll post it when I get back.

Edit:
How's the Swingworker class in its entirety:
code:
import java.util.Iterator;

import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.SwingWorker;

import com.uc4.api.FolderListItem;
import com.uc4.api.UC4ObjectName;
import com.uc4.api.objects.IFolder;
import com.uc4.api.objects.Job;
import com.uc4.communication.Connection;
import com.uc4.communication.requests.FolderList;
import com.uc4.communication.requests.FolderTree;
import com.uc4.communication.requests.OpenObject;

public class FindJobsByScript extends SwingWorker<DefaultListModel<String>,Integer> {
	
	private Connection aeconnection;
	private String team = "";
	private String searchParameter = "";
	private JComboBox<String> teams;
	private DefaultListModel<String> foundJobs = new DefaultListModel<String>();
	
	public FindJobsByScript(Connection aeconnection, String team, String searchParameter, JComboBox<String> teams) {
		this.aeconnection = aeconnection;
		this.team = team;
		this.searchParameter = searchParameter;
		this.teams = teams;
	}
	
	@Override
	protected DefaultListModel<String> doInBackground() throws Exception {

		int i = 1;
		
		teams.setEnabled(false);
		FolderTree tree = new FolderTree();
		this.aeconnection.sendRequestAndWait(tree);
		IFolder jobsFolder = tree.getFolder("/" + team.trim() + "/JOBS/");
		FolderList jobsListing = new FolderList(jobsFolder);
		aeconnection.sendRequestAndWait(jobsListing);
		Iterator<FolderListItem> jobItems = jobsListing.iterator();
		while (jobItems.hasNext()) {
			System.out.println((100*i)/jobsListing.size());
			setProgress((100*i)/jobsListing.size());
			FolderListItem item = jobItems.next();
			if (item.getObjectType().equals("JOBS")) {
				UC4ObjectName jobName = new UC4ObjectName(item.getName());
				OpenObject openJob = new OpenObject(jobName);
				aeconnection.sendRequestAndWait(openJob);
				Job jobItem = (Job) openJob.getUC4Object();
				if (jobItem.getProcess().toUpperCase().contains(searchParameter.toUpperCase())) {
					foundJobs.addElement(jobItem.getName());
				}
			}
			i++;
		}
	
		return foundJobs;
	}
	
	@Override
	protected void done() {
		teams.setEnabled(true);
	}
}

PierreTheMime fucked around with this message at 19:17 on Nov 10, 2016

geeves
Sep 16, 2004

baquerd posted:

Usually they use a Blackhawk on ISIS, not the Apache.

Thank you. I couldn't think of a good pun for this.

venutolo
Jun 4, 2003

Dinosaur Gum
e: Ignore. Want to re-formulate my question.

venutolo fucked around with this message at 21:43 on Nov 14, 2016

PierreTheMime
Dec 9, 2004

Hero of hormagaunts everywhere!
Buglord
Coming from zero experience, what would be a good web service interface for basic Java interaction on a website? I set up a generic Tomcat install and tried out a dynamic web service build right out of Eclipse, but I'm mostly just playing around to understand the concepts. What's a decent approach for a "RESTful" interface?

I basically just need a site that can query a database based on limited user input and return formatted text. My code works fine as a stand-alone, but I'm being told implementing it as an internal website is the way they want it presented.

geeves
Sep 16, 2004

PierreTheMime posted:

Coming from zero experience, what would be a good web service interface for basic Java interaction on a website? I set up a generic Tomcat install and tried out a dynamic web service build right out of Eclipse, but I'm mostly just playing around to understand the concepts. What's a decent approach for a "RESTful" interface?

I basically just need a site that can query a database based on limited user input and return formatted text. My code works fine as a stand-alone, but I'm being told implementing it as an internal website is the way they want it presented.

Some may say Spring, but I think Jersey is a hell of a lot easier to setup and get running - especially if you're using Maven. Jersey's documentation uses Grizzly container (I've never used it), but it's fully compatible with Tomcat and requires some modifications to your web.xml like setting your root API "directory". I use Jersey for my personal products and we run our REST interface with it at my job.

You should be able to get up and running without too much complication if you follow this: https://jersey.java.net/documentation/latest/getting-started.html

Then for the front end, you can use whatever JS framework (or just straight JS) to read the resultant JSON. You can also send back XML, Text, HTML as well from your Resources / Controllers.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

geeves posted:

Some may say Spring, but I think Jersey is a hell of a lot easier to setup and get running - especially if you're using Maven. Jersey's documentation uses Grizzly container (I've never used it), but it's fully compatible with Tomcat and requires some modifications to your web.xml like setting your root API "directory". I use Jersey for my personal products and we run our REST interface with it at my job.

You should be able to get up and running without too much complication if you follow this: https://jersey.java.net/documentation/latest/getting-started.html

Then for the front end, you can use whatever JS framework (or just straight JS) to read the resultant JSON. You can also send back XML, Text, HTML as well from your Resources / Controllers.

Echoing all this.

You don't do the web with java, you do the web with HTML/JS and then you AJAX call to REST when you need to perform operations.

And Jersey is my favorite implementation of a REST server on Java as well. Spring is good but its a huuuuge framework, so its more messy to get started. Jersey is also the reference implementation of JAX-RS, so you can use pretty much the same code with other JAX-RS implementations with little to no modifications, if you end up having some issue with Jersey. Its also well supported.

I haven't used it with Grizzly, I had it running in JBoss.

If you wanna use Java to actually generate the pages then you're looking for something like Thymeleaf, but you're going to end up using Javascript for any interactive elements regardless.

more like dICK
Feb 15, 2010

This is inevitable.
Go ahead and start with dropwizard, which packages Jersey with a bunch of other libraries (json, logging, metrics, an http server) that you'll end up using anyways.

Volguus
Mar 3, 2009

Zaphod42 posted:

.... Spring is good but its a huuuuge framework, so its more messy to get started. ....

That was true 10 years ago. 5 years ago even it ceased to be correct. 2 years ago Spring Boot came into existence, which made what was trivial before even easier:

code:
@SpringBootApplication
public class Application {
 
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
The pom.xml is easy too, thanks to the dependencies that get pulled in automatically. It is not shorter with the other frameworks either. Here's one article that i saw today on reddit about making a CRUD app with Spring boot: https://stormpath.com/blog/crud-application-react-spring-boot-user-authentication


But, like other have said, there are a lot of frameworks to choose from. Today you have (besides Spring boot) dropwizard, Spark (http://sparkjava.com/) and even JHipster which claims that it will generate crap for you : https://jhipster.github.io/

Give them a try or ... just pick one and make your mind up.

denzelcurrypower
Jan 28, 2011
Got a very simple homework assignment, but I can't for the life of me figure out why an exception keeps getting thrown.
It's a Java EE project, I'm accessing the DB through a data source / connection pool. I'm just trying to add a row to the order table,
but when it comes to executing the query, an SQL exception is thrown.

code:
public void addOrder (Order order) {
        PreparedStatement addOrder;
        try {
            String sql = "INSERT INTO 'order' ('OrderID', 'CustomerID', 'Size', 'Toppings') VALUES (NULL, ?, ?, ?)"; 
            addOrder = connection.prepareStatement(sql);
            int customerID = order.getCustomer().getCustomerID(); 
            int pizzaSize = Integer.parseInt(order.getSize()); 
            //String toppings = order.getToppingsString(); 
            String toppings = "pineapple, bacon"; 
            addOrder.setInt(1, customerID + 1);
            addOrder.setInt(2, pizzaSize); 
            addOrder.setString(3, toppings); 
            addOrder.executeUpdate(); 
            addOrder.close(); 
        } catch (SQLException ex) {
            Logger.getLogger(DBConnection.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
        }
    }
When it reaches addOrder.executeUpdate(), the exception is thrown:

code:

Severe:   You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax
 to use near ''order' ('OrderID', 'CustomerID', 'Size', 'Toppings') VALUES (NULL, 123457, 9, '' at line 1
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near ''order' ('OrderID', 'CustomerID', 'Size', 'Toppings') VALUES (NULL, 123457, 9, '' at line 1

For some reason it seems that the toppings string is not being passed into the prepared statement correctly.Any ideas what I'm doing wrong?
It's a MySQL database if that matters.

denzelcurrypower fucked around with this message at 06:32 on Nov 15, 2016

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

I think that's just the error message cutting off at the toppings value - you probably want to look at where the error starts, which is the 'order' part. Is your query syntax correct? Does it look like other examples?

denzelcurrypower
Jan 28, 2011

baka kaba posted:

I think that's just the error message cutting off at the toppings value - you probably want to look at where the error starts, which is the 'order' part. Is your query syntax correct? Does it look like other examples?

Yeah... if I paste this into MySQL

code:
INSERT INTO `order` (`OrderID`, `CustomerID`, `Size`, `Toppings`) VALUES (NULL, 123456, 9, 'cheese and pepperoni')
then it works fine. The only thing I've changed is put in values. Even if I hardcode these same values, it gives error when trying to call the method in Java.




denzelcurrypower fucked around with this message at 07:05 on Nov 15, 2016

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
I'm curious as to why you used backticks when running it directly when it has single quotes in the java string. Did you re-type it by hand instead of copy-pasting?

denzelcurrypower
Jan 28, 2011
For some reason it sometimes pastes with that strange version of single quote character but I tried replacing with regular single quote ' and the same errors seem to persist regardless.

I've been copy pasting between NetBeans and php my admin so I guess at some point the text encoding is being changed. Don't think it's related to the error though since I've tried replacing any of the strange characters.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem

Ornithology posted:

For some reason it sometimes pastes with that strange version of single quote character but I tried replacing with regular single quote ' and the same errors seem to persist regardless.

I've been copy pasting between NetBeans and php my admin so I guess at some point the text encoding is being changed. Don't think it's related to the error though since I've tried replacing any of the strange characters.

The difference between single quotes and backticks is the root cause of your problem. Ignoring it entirely and looking for some other issue is not going to be fruitful.

FateFree
Nov 14, 2003

Pretty sure you cant have a table called 'order' in Mysql. Its a keyword (such as order by blah).

Edit - I'm seeing conflicting results about this - I know I personally had to change an order table to orders a few weeks ago because of a similar issue though. Try changing it to orders and see if it works?

Edit 2 - Also why are you separating your PreparedStatement variable away from its assignment? Put em together inside the try, save a line!

FateFree fucked around with this message at 14:11 on Nov 15, 2016

ExcessBLarg!
Sep 1, 2001
You can have a table named `order`, but you have to escape the name using backticks (hence, `order`) since ORDER is a SQL keyword.

geeves
Sep 16, 2004

ExcessBLarg! posted:

You can have a table named `order`, but you have to escape the name using backticks (hence, `order`) since ORDER is a SQL keyword.

Or, you know, just not cause a massive headache by using a reserved word as a table name. :v:

Data Graham
Dec 28, 2009

📈📊🍪😋



Sometimes fate just has it in for you. "release" is a keyword now, but it wasn't back when I first designed the system :doh:

geeves
Sep 16, 2004

Data Graham posted:

Sometimes fate just has it in for you. "release" is a keyword now, but it wasn't back when I first designed the system :doh:

Radium account spotted.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

geeves posted:

Or, you know, just not cause a massive headache by using a reserved word as a table name. :v:

Yeah the problem comes from using the keyword, forcing the single quotes, causing syntax errors. Wish you could do escaped literal strings with @ like in C#, would probably make this easy.

But I'd change your database schema if at all possible.

FateFree posted:

Edit 2 - Also why are you separating your PreparedStatement variable away from its assignment? Put em together inside the try, save a line!

Saving a line doesn't matter. Who cares. Lines != Instructions. Compilers are smart.

Volguus
Mar 3, 2009

Zaphod42 posted:

Saving a line doesn't matter. Who cares. Lines != Instructions. Compilers are smart.

You don't write code for compilers. You write code for people. Initializing a variable when you declare it prevents a very ugly class of potential bugs. Not now, but probably later when another person will modify the code. If you don't need variable X outside a scope, don't declare it outside the scope.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Volguus posted:

You don't write code for compilers. You write code for people. Initializing a variable when you declare it prevents a very ugly class of potential bugs. Not now, but probably later when another person will modify the code. If you don't need variable X outside a scope, don't declare it outside the scope.

That's my point exactly, you write code for people. Its a very minor thing to nitpick and putting it above the try as a statement of intent isn't really a cardinal sin. You could move it but it really isn't worth correcting someone over.

FateFree
Nov 14, 2003

Zaphod42 posted:

That's my point exactly, you write code for people. Its a very minor thing to nitpick and putting it above the try as a statement of intent isn't really a cardinal sin. You could move it but it really isn't worth correcting someone over.

Its not minor at all, writing code is built upon small decisions like these. Why would you separate something into two lines that can (should) be explained in one? If a person gets in this habit every day of their job, they waste thousands of lines of code, and worse, you waste time and brainpower piecing together something that should be together. It would be like reading a book where someone split sentences in half and finished them down the line. This is the exact sort of thing that separates good coders from bad coders, trying to make things as easy and simple as possible at every opportunity is important and should be taught to people when you have a chance to.

geeves
Sep 16, 2004

FateFree posted:

Its not minor at all, writing code is built upon small decisions like these. Why would you separate something into two lines that can (should) be explained in one? If a person gets in this habit every day of their job, they waste thousands of lines of code, and worse, you waste time and brainpower piecing together something that should be together. It would be like reading a book where someone split sentences in half and finished them down the line. This is the exact sort of thing that separates good coders from bad coders, trying to make things as easy and simple as possible at every opportunity is important and should be taught to people when you have a chance to.

For me it's out of habit, because we write a lot of complex SQL via StringBuilder, etc. that might have some if / else clauses when adding parameters to the question you're ultimately asking. Suddenly throwing SQL directly into a preparedStatement("SELECT...."); is structurally jarring and I have not seen any company for which I've worked do except in rare or random instances. Even if I'm doing simply "SELECT * FROM foo;" it's its own string since I expect to modify the question at some point in the future.

Many programmers I work with Java wasn't their first language and that language may have been one where they would pre-sanitize the string before passing it on to the language's driver.

Also Java's own documentation follows this model as well. https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

geeves fucked around with this message at 21:54 on Nov 16, 2016

Adbot
ADBOT LOVES YOU

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

FateFree posted:

Its not minor at all, writing code is built upon small decisions like these. Why would you separate something into two lines that can (should) be explained in one? If a person gets in this habit every day of their job, they waste thousands of lines of code, and worse, you waste time and brainpower piecing together something that should be together. It would be like reading a book where someone split sentences in half and finished them down the line. This is the exact sort of thing that separates good coders from bad coders, trying to make things as easy and simple as possible at every opportunity is important and should be taught to people when you have a chance to.

Why do you have to continue to talk down to me dismissively like I've never heard of improving code readability? Everything I've posted in this thread suggests I know exactly what you're talking about. Where we disagree is over how big a deal this is to readability; not whether readability matters period. Very arrogant attitude.

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