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
pigdog
Apr 23, 2004

by Smythe

Volmarias posted:

Bear in mind that TDD is not for everyone. Code first, tests later is also perfectly valid.

Doing tests first would force you to think about what you are actually trying to accomplish, make it harder to use bad shortcuts such as static singletons that make code hard to test and reuse, would help you come up with good component design right off the bat, would have you limit your scope to what is actually needed, would let you start with a simple/bad solution and refine it to a neat/great one, would give you confidence that you haven't missed/forgotten any functionality... among other things. Tests are great to have while you're developing your code, hence tests first. Not only is writing tests after the fact more tedious and sometimes more difficult, but you'd miss out on the benefits of (usually better) choices they nudge you towards.

That said, there's very little to learn about JUnit.

include org.junit.Test;
public class Butts {
@Test
public void fartTest() {
assertFalse("poop".equals("fart"));
}
}

It's hardly more complicated to start with than Hello World in Java would be. I write all kinds of experimental code as test cases, it's just so easy.

pigdog fucked around with this message at 13:53 on Mar 12, 2016

Adbot
ADBOT LOVES YOU

Loezi
Dec 18, 2012

Never buy the cheap stuff

pigdog posted:

Doing tests first would force you to think about what you are actually trying to accomplish...

I partially disagree with this. I personally feel that TDD is a good thing in what I'd call the middle of the spectrum: On one extreme end of the spectrum, writing POJOs with nothing but getters and setters using TDD is a really bad way of spending your time. Instead of just spamming IntelliJ's code generation tools, I end up spending a ton of time writing tests, the usefulness of which is at best dubious. If the tests are needed, writing them afterwards is usually just a bunch of copy-pasting "assert initial value; set new value; assert new value" and can be done really fast. Swapping between writing tests and the POJO in that case just creates a cognitive load for no real benefit.

And in the other extreme, when you are doing exploratory programming for a complex subsystem, doing TDD just slows you down and you end up writing tons of tests that you just scrap when the approach you thought would be good ends up being poo poo.

Like with all things, there's a time when TDD is good and a time when it's bad. I personally find myself working more in the extremes (where it's more of a hindrance) than in the middle part.

Furthermore, I think that writing tests in the end can also functions as a sort of a self-inflicted code review, especially if you do it the next day after otherwise finishing the functionality: you get to read your code with a clear mind, do some refactoring, etc. And I feel that doing something "boring" for a day is actually really good for you after doing complex things for a day or two.

speng31b
May 8, 2010

Let's not get dogmatic about TDD one way or another. Anyone who's done this for a little while has probably known consistent producers of quality code who religiously follow red-green-refactor, and those who don't at all, and everywhere in between. I've haven't consistently found the strictness of someone's TDD process to be a harbinger of the eventual quality of their work. TDD is great when it helps you to better understand the requirements upfront so you get a better design going into a task. If it's not doing that for you, writing tests later in the process is just fine.

It's probably most important to understand that there isn't a line in the sand choice between "don't write tests" and "do TDD". You can and should strive for good test coverage even if the TDD process isn't followed.

baquerd
Jul 2, 2007

by FactsAreUseless

speng31b posted:

Let's not get dogmatic about TDD one way or another. Anyone who's done this for a little while has probably known consistent producers of quality code who religiously follow red-green-refactor, and those who don't at all, and everywhere in between. I've haven't consistently found the strictness of someone's TDD process to be a harbinger of the eventual quality of their work. TDD is great when it helps you to better understand the requirements upfront so you get a better design going into a task. If it's not doing that for you, writing tests later in the process is just fine.

It's probably most important to understand that there isn't a line in the sand choice between "don't write tests" and "do TDD". You can and should strive for good test coverage even if the TDD process isn't followed.

I agree 100%. TDD is a tool, and like any tool, simply using it doesn't create great results. Knowing when to use the tool is crucial.

pigdog
Apr 23, 2004

by Smythe

Loezi posted:

I partially disagree with this. I personally feel that TDD is a good thing in what I'd call the middle of the spectrum: On one extreme end of the spectrum, writing POJOs with nothing but getters and setters using TDD is a really bad way of spending your time.
Yeah, no need to be writing tests for simple setters and getters (or for standard library functions and such).

quote:

And in the other extreme, when you are doing exploratory programming for a complex subsystem, doing TDD just slows you down and you end up writing tons of tests that you just scrap when the approach you thought would be good ends up being poo poo.
There can be scenarios there. I mean if I'm about to program a subsystem, then I'd definitely start with what I want it to do, and could well start with tests, often against an interface of what the submodule would eventually implement to provide that functionality.

If it's about experimenting to see how a foreign library or a component works, then you wouldn't necessarily need tests -- at that point you're not describing what the system ought to do, but just still mucking around learning what it could do. That may be a case where it's too early for tests, and perhaps why one would end up with tests to scrap. Afterall you ought to write tests to test your code, not the code in that library (unless it's an integration or system test).

smackfu
Jun 7, 2004

People writing tests for getters and setters are usually trying to get 100% test coverage in my experience.

The Laplace Demon
Jul 23, 2009

"Oh dear! Oh dear! Heisenberg is a douche!"

smackfu posted:

People writing tests for getters and setters are usually trying to get 100% test coverage in my experience.

In my experience, if a getter or setter isn't covered by my tests, I'm either missing an edge case or it's dead code that should be deleted. I can't think of a good reason to add them to anything except POJOs (Lombok's @Data is nice here) except maybe as a workaround for stubbing/mocking an injected field in tests (with an appropriate @VisibleForTesting annotation or comment). Which is all to say those people writing tests for getters and setters are wasting their time writing the accessors and tests and wasting everybody else's time when reading them.

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

How about setters (and I guess maybe getters in some situations) that perform validation and apply defaults though? Where it's a bit more nuanced than 'set private thing to thing'

speng31b
May 8, 2010

Then they need to be tested, I think that's the point. Validation is pretty much a definitive example of something you'd want tests for. When people say "getters and setters don't need to be tested", I'm assuming they're talking about complete passthrough getters and setters that you'd pretty much only see on pure POJOs/value objects. So yeah we can all agree that writing tests for code that can and should be autogenerated just to get coverage numbers up is pretty silly. Don't write tests for that, just calculate your coverage in a way that avoids penalizing you for not covering pure boilerplate.

speng31b fucked around with this message at 03:38 on Mar 13, 2016

jtxdriggers
Mar 15, 2016
One of the major points of TDD that people tend to glaze over is its value when your code may be modified by someone else in the future. Good test coverage for your code provides insurance that future changes won't break the intended behavior. Even in a non-team environment, someone who hasn't worked on a particular class in a long time may have forgotten some edge-case that was well-known at one point, but has since been forgotten. Providing that test coverage up front will give confidence in changes, regardless of who is making them.

As for getter/setter testing, any additional behavior beyond setting a private variable should be tested, but I tend to keep my models in a separate package and ignore their coverage completely. If you find a model method unused once it has accomplished its intended behavior, then you should reevaluate whether that field of the model is really necessary.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

jtxdriggers posted:

One of the major points of TDD that people tend to glaze over is its value when your code may be modified by someone else in the future. Good test coverage for your code provides insurance that future changes won't break the intended behavior. Even in a non-team environment, someone who hasn't worked on a particular class in a long time may have forgotten some edge-case that was well-known at one point, but has since been forgotten. Providing that test coverage up front will give confidence in changes, regardless of who is making them.

This applies to writing tests during or after, too, though? It's hardly unique to TDD.

jtxdriggers
Mar 15, 2016

carry on then posted:

This applies to writing tests during or after, too, though? It's hardly unique to TDD.

True, however TDD would ensure the tests are there initially. But you are correct, I've worked with several people who "fill in" test coverage after the code has been written, but before pull requests are made.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...
Aka "competent developers." This is how the non-TDD world works when it comes to testing (or is supposed to work anyway)

baquerd
Jul 2, 2007

by FactsAreUseless

jtxdriggers posted:

Good test coverage for your code provides insurance that future changes won't break the intended behavior. Even in a non-team environment, someone who hasn't worked on a particular class in a long time may have forgotten some edge-case that was well-known at one point, but has since been forgotten. Providing that test coverage up front will give confidence in changes, regardless of who is making them.

Or more likely, that the tests need to be re-written or modified to work with the new changes. For me, TDD is considered harmful when not used by people who know what good, non-brittle tests look like or don't take the time to re-factor and condense their test code like they would primary business logic.

I find that unit tests written by TDD'ers are often over-used and can act as dead weight on a codebase, actually discouraging refactoring because of the overhead of fixing all of the unit tests. I can't count the number of times when I make a small change and the unit tests all go red because they were written by well-meaning but misguided TDD'ers who are writing tests that are more a re-statement of the actual code than real tests, and have 5 slightly different but not meaningfully distinct variations of the same basic test case.

Unit tests don't typically give me confidence, but behavioral tests definitely give me confidence in re-factoring.

jtxdriggers
Mar 15, 2016

baquerd posted:

I can't count the number of times when I make a small change and the unit tests all go red because they were written by well-meaning but misguided TDD'ers who are writing tests that are more a re-statement of the actual code than real tests, and have 5 slightly different but not meaningfully distinct variations of the same basic test case.

This sounds like pure lack of experience. "Misguided" is a great way to describe it. New, inexperienced hires are often encouraged or forced to TDD with very little explanation of what that actually means, with nothing to go off of other than a low quality YouTube clip from a conference the CTO went to. Some of them will read up on the topic or follow examples by the more senior devs, while others will just kind of wing it until they meet the coverage threshold, obviously making refactoring more difficult for everyone down the road.

It is certainly a valuable tool when used correctly. It meshes very well with dependency injection (mocking external dependencies), and testing the intended behavior of the interface, not the implementation itself. However, I've seen a ton of people make methods protected instead of private for the sake of accessing them via a unit test, which is generally a red flag in code reviews.

pigdog
Apr 23, 2004

by Smythe

jtxdriggers posted:

It is certainly a valuable tool when used correctly. It meshes very well with dependency injection (mocking external dependencies), and testing the intended behavior of the interface, not the implementation itself. However, I've seen a ton of people make methods protected instead of private for the sake of accessing them via a unit test, which is generally a red flag in code reviews.
Of course, you're not supposed to test private methods, they are part of the implementation which the rest of the world needn't worry about. If someone feels there is a genuine need to test the private method, then chances are it's actually better off as a public method in a separate class.

jtxdriggers
Mar 15, 2016

pigdog posted:

Of course, you're not supposed to test private methods, they are part of the implementation which the rest of the world needn't worry about. If someone feels there is a genuine need to test the private method, then chances are it's actually better off as a public method in a separate class.

Exactly, and in order to test internal methods at all, you need to expose the implementation, not the interface.

Good test setup:

code:
private SomeService someService;

@Before
public void setup() {
    someService = new SomeServiceImpl();
}
Bad test setup:

code:
private SomeServiceImpl someService; // Red flag

@Before
public void setup() {
    someService = new SomeServiceImpl();
}
Generally the conversation goes something like this:

Why does your test declare the class instead of the interface?
"So I could test a method that the class contains but the interface doesn't expose."
So then why isn't that method in another testable interface that can be injected as a dependency?
"Because it seemed like it wasn't important enough to justify its own interface and implementation."
Well if it's important enough to test here, then it's important enough to refactor out.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

jtxdriggers posted:

Exactly, and in order to test internal methods at all, you need to expose the implementation, not the interface.

Good test setup:

code:
private SomeService someService;

@Before
public void setup() {
    someService = new SomeServiceImpl();
}
Bad test setup:

code:
private SomeServiceImpl someService; // Red flag

@Before
public void setup() {
    someService = new SomeServiceImpl();
}
Generally the conversation goes something like this:

Why does your test declare the class instead of the interface?
"So I could test a method that the class contains but the interface doesn't expose."
So then why isn't that method in another testable interface that can be injected as a dependency?
"Because it seemed like it wasn't important enough to justify its own interface and implementation."
Well if it's important enough to test here, then it's important enough to refactor out.

I disagree a little, some internal methods exist because they are helpers that mutate the internal state of the object and complex enough to warrant unit tests. It doesn't make sense to expose them in a public interface or think that their implementations can be interchanged using DI. I think using the package-private scope in Java is a reasonable way to expose those methods to your tests while not exposing them as part of the public interface.

pigdog
Apr 23, 2004

by Smythe

Janitor Prime posted:

I disagree a little, some internal methods exist because they are helpers that mutate the internal state of the object and complex enough to warrant unit tests. It doesn't make sense to expose them in a public interface or think that their implementations can be interchanged using DI. I think using the package-private scope in Java is a reasonable way to expose those methods to your tests while not exposing them as part of the public interface.
Well, when they're private, then the rest of your code doesn't know or care anything about them. The rest of the world only knows your component by the public methods (or fields), which is where the test boundary should also be. Otherwise you'd just end up with brittle tests that break when you change the internals of your component, rather than the behavior at its public interface that matters.

For what it's worth, it is sometimes a good idea for interfaces and protocols to include functionality whose purpose is to only help at testing.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
I'm just gonna leave this here

http://jasonpolites.github.io/tao-of-testing/ch3-1.1.html

;)

Boz0r
Sep 7, 2006
The Rocketship in action.
I've been assigned to a Java EE project that noone really knows in-depth. How do I find out if we're using Struts 1 or 2?

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Boz0r posted:

I've been assigned to a Java EE project that noone really knows in-depth. How do I find out if we're using Struts 1 or 2?

You check the version in the pom.xml lol j/k you're probably stuck in some ant hell if it's Java EE.

Hopefully it's a jar somewhere with the version number in the name and they didn't uncompress it into your project. Also you can simply check the imports, Struts 2 use a different package org.apache.struts2 vs org.apache.struts

Enderzero
Jun 19, 2001

The snowflake button makes it
cold cold cold
Set temperature makes it
hold hold hold
Does anyone know good resources for quickly picking up Java as an experienced developer, especially SE 7? I'm looking for an equivalent to Crockford's Javascript: The Good Parts but for Java - I don't need a 500 page tome, I need something that succinctly explains details without a ton of really basic explanations for people who barely have a grasp on programming. Why is this the only language I've encountered that can't even seem to put together a good cheat sheet on like 2 pages? Why do so many summaries focus not on how to use language features to accomplish different patterns or common interesting syntax examples but go on forever about library usage? I would also be happy to look at slide presentations that do a good job of quickly but somewhat precisely explaining the language and/or SE 7 differences.

Zaphod42
Sep 13, 2012

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

Enderzero posted:

Does anyone know good resources for quickly picking up Java as an experienced developer, especially SE 7? I'm looking for an equivalent to Crockford's java script: The Good Parts but for Java - I don't need a 500 page tome, I need something that succinctly explains details without a ton of really basic explanations for people who barely have a grasp on programming. Why is this the only language I've encountered that can't even seem to put together a good cheat sheet on like 2 pages? Why do so many summaries focus not on how to use language features to accomplish different patterns or common interesting syntax examples but go on forever about library usage? I would also be happy to look at slide presentations that do a good job of quickly but somewhat precisely explaining the language and/or SE 7 differences.

Check it:

Fergus Mac Roich posted:

Oracle's Java tutorials are an excellent place to start.

casual poster posted:

Once you get into learning about creating objects (maybe week 2 or 3) get a book called Head First Java, it's very informative and uses illustrations to explain OOP concepts (it's good to get a second look at something) and has been a life saver for me (be sure to use the index in the back to find certain things!). Also brush up on your google and find some cool websites to hang out on. dreamincode is good, and so is java code geeks. When you get further in and have questions, start googling for the answer and remember to use the Oracle documents (they weren't very novice-friendly at the start, but you'll slowly begin to understand what they're talking about).
But first, get started on the mooc site. It will give you a solid understanding.

speng31b posted:

Sorry but the Oracle tutorials aren't the equivalent of "The C++ Programming Language", the book you're looking for is Effective Java (http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683) - end of story. The books others mentioned are probably fine books, but not the more indepth look at the language mechanics for someone who knows the language but not the details of how to use it most effectively.

That said, if you don't already know the material in the Oracle tutorials offhand, you should probably at least skim those before bothering with Effective Java, or have them available to reference when you read it.

Also if you're already familiar with C#: http://www.25hoursaday.com/csharpvsjava.html

We should probably put these together in the OP or something because it comes up a lot.

Enderzero
Jun 19, 2001

The snowflake button makes it
cold cold cold
Set temperature makes it
hold hold hold

Zaphod42 posted:

Check it:

Also if you're already familiar with C#: http://www.25hoursaday.com/csharpvsjava.html

We should probably put these together in the OP or something because it comes up a lot.

Thanks for the reply! The tutorial kind of sucks though - way too much basic info, not enough edge case information, and they don't even have versioned tutorials - only Java 8 is included which is not incredibly useful as my company is on 7. Obviously a lot still applies but I don't look forward to trying to figure out the differences and what I won't be able to use quickly. There seems to be a yawning gap between the tutorial and something like Effective Java.

jtxdriggers
Mar 15, 2016

Enderzero posted:

Thanks for the reply! The tutorial kind of sucks though - way too much basic info, not enough edge case information, and they don't even have versioned tutorials - only Java 8 is included which is not incredibly useful as my company is on 7. Obviously a lot still applies but I don't look forward to trying to figure out the differences and what I won't be able to use quickly. There seems to be a yawning gap between the tutorial and something like Effective Java.

Scanning through that tutorial, I didn't see anything that was specific to Java 8. I could have missed something, but generally Java 8 gives lambda notation, streams, optionals, and default interface methods. There are more additions but those are the biggies.

Java is pretty easy to pick up, especially if you already have a good grasp on object-orientation and strong types. I would recommend looking into visibility (public/protected/private/default) and generics (ArrayList<SomeObject>), especially if you're coming from something like JS. One of the biggest gripes about Java (especially prior to Java 8) is null-checking.

I generally encourage people to dive in rather than reading through a book, but that's just because I learn better that way. Some people learn more from a book, I suppose. In any case, I'm happy to answer specific questions here if you find any of those edge-cases.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.

Enderzero posted:

Does anyone know good resources for quickly picking up Java as an experienced developer, especially SE 7? I'm looking for an equivalent to Crockford's java script: The Good Parts but for Java - I don't need a 500 page tome, I need something that succinctly explains details without a ton of really basic explanations for people who barely have a grasp on programming. Why is this the only language I've encountered that can't even seem to put together a good cheat sheet on like 2 pages? Why do so many summaries focus not on how to use language features to accomplish different patterns or common interesting syntax examples but go on forever about library usage? I would also be happy to look at slide presentations that do a good job of quickly but somewhat precisely explaining the language and/or SE 7 differences.

Java Concurrency in Practice is a best-practices book cleverly disguised as a concurrency-specific resource. You'll walk away knowing how to implement common patterns as mostly-immutable structures, which is A Good Thing. It is big and beefy, rather than a cheat-sheet, but it doesn't talk down to you. I'd say that Google's Guava, Apache Commons, and JodaTime are the libraries that everyone is using and you should too.

Janitor Prime
Jan 22, 2004

PC LOAD LETTER

What da fuck does that mean

Fun Shoe

Gravity Pike posted:

I'd say that Google's Guava, Apache Commons, and JodaTime are the libraries that everyone is using and you should too.

I'm glad that Java 8 made a large part of those libraries redundant and we can start removing them from our dependency graphs.

Janitor Prime fucked around with this message at 15:16 on Mar 24, 2016

speng31b
May 8, 2010

Gravity Pike posted:

Java Concurrency in Practice is a best-practices book cleverly disguised as a concurrency-specific resource. You'll walk away knowing how to implement common patterns as mostly-immutable structures, which is A Good Thing. It is big and beefy, rather than a cheat-sheet, but it doesn't talk down to you. I'd say that Google's Guava, Apache Commons, and JodaTime are the libraries that everyone is using and you should too.

Whenever anyone asks about Java books the tl;dr should pretty much always be, in this order, Oracle Tutorials -> Effective Java -> Java Concurrency in Practice. It's been that way for a long time and I don't see it changing anytime soon.

Boz0r
Sep 7, 2006
The Rocketship in action.
The project I've been assigned to is based on Struts, and in an attempt to switch to GWT, some new pages have been made in that. A guy complained that browser history in GWT was impossible to get working if it was used together with any other mvc framework. Is that true? I don't know a lot about either.

1337JiveTurkey
Feb 17, 2005

Boz0r posted:

The project I've been assigned to is based on Struts, and in an attempt to switch to GWT, some new pages have been made in that. A guy complained that browser history in GWT was impossible to get working if it was used together with any other mvc framework. Is that true? I don't know a lot about either.

I know GWT pretty decently for a backend developer but not much about Struts, so take with a pile of salt.

GWT's intended to be embedded within a single host page with no transitions to other pages. The host can be in whatever framework you want or just static HTML. In order to provide history with this, it breaks the page into a series of tasks which are identified with URL fragments and a special history tracking iframe on the page. None of these ever reload the page, just call a client-side handler with the new task URL fragment. That can make asynchronous calls to the server for any missing data like a normal page load and then at some point set the task widget to the new task. Everything else retains the same state as before and doesn't need to reload anything which can make it much more responsive.

The trick here is that you can navigate to a task/fragment directly, like by going back from a link to a new page or following a link in an email. Instead of setting the page to the default task, it'll set it to the task that the user was in when they navigated away with the same fragment. However everything else will have its default state because it's being loaded from scratch. If you're doing only some of your pages in GWT that's bound to be a problem as you jump to an old page which loses the state, then back to a GWT page and so forth.

If that's what's going on you probably want to include any necessary state in some other form like HTML5 local storage so it can be grabbed from there. Another possible idea (remember backend guy here) is moving everything that ends up on the edges of the page like navigation, help links, etc. into GWT and then make the other pages iframes within the GWT application. History will be interesting then but apparently it interleaves Frame widget history with page history which might be what you're looking for or it might be the original problem.

Captain Cappy
Aug 7, 2008

Not a question, but I had to use JNDI recently as an LDAP client and it was kind of frustrating how vague (eg. <?>) the interface is. I just cannot get used to the whole "Let's return Object and let the class user figure out what it is" paradigm that seems to be everywhere in Java. It just seems like void * shenanigans from C and counter to the idea of strongly typed languages. I probably just don't understand how it is supposed to work but I preferred the Apache version, which seemed more strongly typed and straightforward. Is JNDI actually good and I just need to spend more time understanding it?

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

It sounds like a bunch of the code was written pre-Java 5, before generics. Couldn't tell you about JNDI as it relates to LDAP, all I know is it's used in Java EE servers to refer to resources.

casual poster
Jun 29, 2009

So casual.
So this code keeps timing-out, I'm guessing that it's not reading a file but can't figure out why. It doesn't throw any exceptions though and I'm not really sure what they're inputting on their side. Also, I know there is another way to read files (bufferreader or something like that, I've tried googling my question before but all the examples are with buffer reader) but we haven't "learned" how to use that yet in this course which is why I am stuck using the regular scanner. Any help?? I've tried many iterations.

code:
package file;
import java.io.File;
import java.util.Scanner;

public class Analysis {
    private File file;
    private Scanner reader;
    public Analysis(File file){
        this.file = file;
    }
    public int lines() {
        this.reader = new Scanner(this.file);
        int i=0;
        while (this.reader.hasNextLine()){
            i++;
        }
        return i;
    }
    
}

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

https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

If your program isn't finishing and you have a loop, that's a good place to look. What's your loop condition? How do you get to a situation where the loop ends? What does hasNextLine() actually do?

casual poster
Jun 29, 2009

So casual.
Alright let me throw out my reasoning and you tell me what concept I should look up?
So a While loop works for as long as the condition is true. the hasNextLine method will return a true statement if there is a next line in the file to be read. I throw the hasnextline as the condition for the while loop because (and I think this is where I might go wrong) it will go from one line to the next, returning true for each line then knowing to go to the next line for the next loop. Every time the while loop completes the counter (i) should increase by one.

I've tried putting a while loop where the condition is a boolean I set to true, then throwing in a if/else statement (with hasnextline as the condition for that) which will change the boolean once there are no more lines. There's something fundamental I am missing and I am not sure what.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

casual poster posted:

Alright let me throw out my reasoning and you tell me what concept I should look up?
So a While loop works for as long as the condition is true. the hasNextLine method will return a true statement if there is a next line in the file to be read. I throw the hasnextline as the condition for the while loop because (and I think this is where I might go wrong) it will go from one line to the next, returning true for each line then knowing to go to the next line for the next loop. Every time the while loop completes the counter (i) should increase by one.

I've tried putting a while loop where the condition is a boolean I set to true, then throwing in a if/else statement (with hasnextline as the condition for that) which will change the boolean once there are no more lines. There's something fundamental I am missing and I am not sure what.

What you're missing is this, in the documentation for hasNextLine():

quote:

Returns true if there is another line in the input of this scanner. This method may block while waiting for input. The scanner does not advance past any input.

So if hasNextLine doesn't advance past any input, ask yourself how might you move through the file? Scanner has the capability, go find the method that'll work best for what you're trying to accomplish.

carry on then fucked around with this message at 00:43 on Apr 4, 2016

casual poster
Jun 29, 2009

So casual.
Dang. Thanks you two. I added "this.reader.nextLine()" in the while loop and it works fine. For some reason I thought I could only call that when setting it to a variable. Thanks.

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

Yeah, hasNextLine() is a way of checking if there's something ready to be read. It would make sense that it wouldn't actually consume it, and if you look at what the method returns, it's a boolean - it has no way of giving you the next line if there was one, you know? So if it did consume the next line, you'd check if there is one, and the method would basically go 'yep... there was'. So that's another way of getting an idea of what probably happens, even if the docs don't really explain something.

That's also a subtle hint about finding the method you want ;) There tend to be naming conventions for the methods in an API, like all the 'check if there's a *thing* next' methods are called hasNext*(). Have a scan down the method summary on the doc page and you'll probably spot some methods that look right, then you can find the one that gives you what you want

e- too late!

And yeah, you can always ignore the output from a method - sometimes there's no point calling one if you're not going to use what it returns, but this is an example of a method with side effects

baka kaba fucked around with this message at 01:01 on Apr 4, 2016

Adbot
ADBOT LOVES YOU

Cryolite
Oct 2, 2006
sodium aluminum fluoride
Is it a good idea to put configuration files in the same directory as my jar files so I can change them without needing to rebuild the jar?

I don't have much experience with Java and mostly come from a .NET background. In .NET my logging .xml files and other configuration files sat alongside my executables and I could change them to tweak settings or change logging levels without needing to rebuild the executable. These configuration files weren't embedded resources.

In Java it seems the path of least resistance is to put these kinds of files into a resources directory so they're packaged in the jar. Is there an easy way to supply/change API keys to my app or change logging config without redeploying the jar? It seems like having these kinds of config files sitting in the same directory as jar files isn't a common practice in the Java world.

How do I best do configuration? Is there a common pattern so that I can keep files like logback.xml, twitterkeys.conf, etc. in the same directory as my jar instead of locked away inside the jar?

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