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
FateFree
Nov 14, 2003

Yeah at that point whats the point of the DB.. might as well use a file reader or something.

Anyhoo I think I'm going to do the hybrid approach - extract all the common stuff into a parent class and have those fields be regular database fields, and then a JSON column for the rest, like:

Inputs
page (fk)
type (varchar)
name (varchar)
value (varchar)
label (varchar)
data (varchar) (json string for variable stuff like dropdown choices, max lengths, whatever is specific to the input type)

Although now I'm wondering what the point of the regular fields are.. maybe I should just throw everything except the page & type into the json column.

FateFree fucked around with this message at 14:58 on Apr 10, 2017

Adbot
ADBOT LOVES YOU

Fergus Mac Roich
Nov 5, 2008

Soiled Meat
I'm wondering what the point of the json is. You know the types of data that you're handling in advance. Why not just model it in SQL? Even a hosed up relational DB is going to be performant compared to searching or filtering by blobs of JSON.

FateFree
Nov 14, 2003

Well I've used json columns for unpredictable parts of data in the past and its worked very well, things like preferences objects where it was just way too much overhead to create a new boolean or default choice for every little thing that came up. It made the schema much simpler. Also I'm not truly modelling form fields, its something less defined and at the mercy of my client. I know it sounds like I should be using a NoSQL db but really this is just one part of the application, everything else works great with the standard db modelling.

Also I will never do any searching or filtering on this json column - its just going to load a whole page of components by their ids and display them.

Tactical Shitpost
Jun 13, 2016
Here's something different:

Let's say you have couple of instances of an application connected to a database on which you need to do some maintenance tasks. The tasks include 1) looking at recent updates made by another application in a different data domain and syncing the changes to my domain, 2) Removal of "orphaned" (junk) records in my domain, and so on - generally stuff that should be done by one instance only.

The problem is how do i select that instance? I'd like to avoid having configuration explicitly say which instance should do it, so i'm looking at the Raft/Paxos consensus algorithms to select the "Cluster Leader" instance that will either orchestrate the tasks or do them by itself. Some protection against the leader instance being down, or something to help recover from a split brain would be super nice. Full blown actor frameworks like Akka seem a bit heavy, but they can be considered.

Anyone got any experience with that? Any libraries to recommend?

Kilson
Jan 16, 2003

I EAT LITTLE CHILDREN FOR BREAKFAST !!11!!1!!!!111!

Tactical Shitpost posted:

Here's something different:

Let's say you have couple of instances of an application connected to a database on which you need to do some maintenance tasks.

Anyone got any experience with that? Any libraries to recommend?

You can maybe setup a clustered scheduler in Quartz to do something like that.

I don't think it really has the concept of a master node, if that matters. Also, split brain will still be a problem (I would argue that's a problem no matter what you're doing, and recovery from that is out of scope of some task scheduling).

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE

FateFree posted:

Ok time for some friendly architecture discussion. I'm interested in knowing how you gents would model a list of objects that should all be displayed on a UI in a row, but each one having different properties.

For instance HTML form fields would be a perfect analogy - some things are input fields with a name and value, other inputs are dropdowns that have their own collection of items to display, a text field may have a max length etc.

So from an inheritance perspective it probably makes sense to have a parent class with common attributes like name and value and child classes for the rest, but how would you model your DB tables? Different tables for each subclass and an ugly query to pull your list of objects? (I'm using Hibernate/JPA with Spring Boot btw.) Or what about a single 'Inputs' table with a JSON column for all the variable data (like the dropdown options). That would make the db very simple and I'll never need to query any of the JSON stuff anyway. But then you might have to do some manual casting to your child classes after you retrieve everything. Any model a similar structure before?

If the subclasses are predictable, you can have table-per-subclass (which is my favored strategy with inheritance). This is easy to do with Hibernate, it'll handle it automatically

If you have no idea what will be coming in - or there are an unreasonable amount of different tables - then you go with the JSON columns. Modern DBs can index JSON so that's not entirely terrible. But you can still map a bunch of the important/shared poo poo to actual relational columns and that does help performance a lot.

The problem comes in you start talking about validation, because the next stop on that crazytrain is defining your own validation language, and then a format that lets you map validation to fields, maybe add a generic format that lets you automatically build views from these forms, and then congratulations, your inner platform is designed, you just designed a template language and a validation schema, pat yourself on the back :golfclap:

We've gone down that path with electronic message parsing and poo poo is loving bullshit. We also have the "totally abstract schema where every record is a billion key-value pairs" too. Our performance is garbage specifically because of those tables and next release I get to make the case for why the PHD who designed it (still on the team somehow) is a retard. I guess he's been off playing with MongoDB in the meantime trying to sell the bosses on that (not joking).

If there is fundamentally a lot of configuration that needs to be done - there is no substitute here, regardless of whether you specify the abstractions in terms of code or in your own made-up validation scheme.

Personally I prefer the code anyway since it can be tested/validated.

Paul MaudDib fucked around with this message at 07:54 on Apr 12, 2017

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE

Fergus Mac Roich posted:

I'm wondering what the point of the json is. You know the types of data that you're handling in advance. Why not just model it in SQL? Even a hosed up relational DB is going to be performant compared to searching or filtering by blobs of JSON.

Modern SQL databases (PG, Oracle, etc) can index JSON so it's reasonably performant.

The point of the JSON column is basically to have a "misc" field. There's really no way to predict what will go there and it's not really relevant to the schema in any sense. You're not going to validate based on it. You probably also aren't going to query on it very often. Maybe there is also big institutional inertia to you actually modifying your DB schema, because you work for an institution and/or client that is terrible.

Alternately - if you want to parse records into an abstract format that you can re-parse later if you need. Beats the gently caress out of CSV-style formats like HL7 or XML-style formats

Personally I've been trying to set up integration testing for Ye Old Terrible Ball-of-poo poo legacy application using JSON fields. For each pass through the app - record the request URL, the request params, the request attribute store, the session attribute store, and where it gets mapped to. In theory the JSON is a super convenient format that I can reconstitute for passing parameters into the servlets - and then I can compare DB changes against a clean instance to see whether poo poo Actually Happened or not. And then we can start working down to adding lower-level tests.

True story I've thrown away about 30% of the codebase now. Wasn't being used, it was just being maintained for the hell of it. No tests obviously.

smackfu
Jun 7, 2004

Anyone use any neat Spring things with Spring Boot? They have what seems like dozens of packages, are there any that you found particularly useful?

poemdexter
Feb 18, 2005

Hooray Indie Games!

College Slice

smackfu posted:

Anyone use any neat Spring things with Spring Boot? They have what seems like dozens of packages, are there any that you found particularly useful?

Yes! Spring Security is awesome for setting up auth. Spring Actuator is great for all the nice endpoints it gives you for server status tracking as well as the ability to write custom endpoints easy.

Basically all our projects here start with these lines in gradle:

code:
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'org.springframework.boot:spring-boot-starter-security'
compile 'org.springframework.boot:spring-boot-actuator'

geeves
Sep 16, 2004

FateFree posted:

Ok time for some friendly architecture discussion. I'm interested in knowing how you gents would model a list of objects that should all be displayed on a UI in a row, but each one having different properties.

For instance HTML form fields would be a perfect analogy - some things are input fields with a name and value, other inputs are dropdowns that have their own collection of items to display, a text field may have a max length etc.

So from an inheritance perspective it probably makes sense to have a parent class with common attributes like name and value and child classes for the rest, but how would you model your DB tables? Different tables for each subclass and an ugly query to pull your list of objects? (I'm using Hibernate/JPA with Spring Boot btw.) Or what about a single 'Inputs' table with a JSON column for all the variable data (like the dropdown options). That would make the db very simple and I'll never need to query any of the JSON stuff anyway. But then you might have to do some manual casting to your child classes after you retrieve everything. Any model a similar structure before?

quote:

The problem comes in you start talking about validation, because the next stop on that crazytrain is defining your own validation language, and then a format that lets you map validation to fields, maybe add a generic format that lets you automatically build views from these forms, and then congratulations, your inner platform is designed, you just designed a template language and a validation schema, pat yourself on the back

Dynamic form fields like this make up the crux of our application and I've just refactored the code from some war crime I wrote 5 years ago. We don't have to index or search our main data store, so nearly everything is text / JSON or what not. (We later index it in Solr as part of another process). But they're only as dynamic as we allow them to be. We know of each possible type that we allow.

We did have a "Type" of field table, so I used that. It is small, so I added a column with the class name, so each one is "com.foo.form.MyFormField" and it lines up with our Model of what we do collect, so there is one base class everything inherits from there.

This makes validation very easy since each Type of field maps to its own class I just factory it out and validate based on type.

So, when saving or loading, I can essentially have one point of entry (or even many) that can handle each individually.

code:
Field field = FormFactory.getField(getFormFieldType());

field.validate();
field.save();
field.load();
field.bar();
.... etc.

Volguus
Mar 3, 2009

smackfu posted:

Anyone use any neat Spring things with Spring Boot? They have what seems like dozens of packages, are there any that you found particularly useful?

Create a simple jhipster project. There are tens of spring packages used throughout, see how they work, play with the project. Quite educational (never heard of liquidbase before, is a quite neat library).

smackfu
Jun 7, 2004

I will need to try that. I've been playing with the SpringFox Swagger package which auto documents your REST apis. It's useful for seeing which end points you were lazy with, like "why is DELETE enabled on this controller???" And useful if someone says that you need to document APIs of course.

Spring Actuator is also really cool although I'm not sure how to use it in our production environment since our individual web servers are not directly addressable. So you could get stats/health for the server you happen to be connected to but not sure how useful that is.

poemdexter
Feb 18, 2005

Hooray Indie Games!

College Slice

smackfu posted:

I will need to try that. I've been playing with the SpringFox Swagger package which auto documents your REST apis. It's useful for seeing which end points you were lazy with, like "why is DELETE enabled on this controller???" And useful if someone says that you need to document APIs of course.

Spring Actuator is also really cool although I'm not sure how to use it in our production environment since our individual web servers are not directly addressable. So you could get stats/health for the server you happen to be connected to but not sure how useful that is.

For production servers that are directly addressable, automated health checks by sysadmin tools is great. Plus you can write custom endpoints for things like integration health checks (can service A reach service B) for microservice environments.

Personally, I wrote a little webapp at work that pings all servers' /health endpoint in all environments to get the version deployed. I think display it in a simple table on a page. Now people can just hit that to see what version of what is deployed where instead of bugging the hell out of me.

P.S. Devops is a rabbit hole you do not want to go down if you're a developer trying to write code. There's always more things to monitor and automate and tweak and people will lean on you hard when things randomly stop working.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

poemdexter posted:

P.S. Devops is a rabbit hole you do not want to go down if you're a developer trying to write code.

This sounds better.

smackfu
Jun 7, 2004

In my further research, I also found out that Spring Boot Admin exists so you can run that as a separate app and it sits somewhere it can talk to all your web servers and presents a common web interface. Haven't played with it yet but it sounds promising.

As far as dev ops, our problem is that we really only have devs and server-level ops (like alerts get raised if the server CPU goes too high.) App ops (like endpoint errors or slow response times) ends up falling into limbo and then they complain to the devs when users report problems. Dysfunctional!

Ariong
Jun 25, 2012

Get bashed, platonist!

I'm using scene builder for the first time, and I'm stuck at the part where you register your controller class. There's supposed to be a dropdown menu containing each class within the same folder as my FXML file, but there isn't. The only solutions to this problem I can find just say to put the FXML file in the same folder as the controller class, which it already is. No luck. I tried typing the name in manually, but that just resulted in the program spitting out an exception. How do I get Scene Builder to recognize the controller class in the same folder as the FXML file?

John F Bennett
Jan 30, 2013

I always wear my wedding ring. It's my trademark.

Does your controller class implement Initializable? Does it have a blanc constructor and did you annotate the fields and methods you need with @FXML?

Ariong
Jun 25, 2012

Get bashed, platonist!

John F Bennett posted:

Does your controller class implement Initializable? Does it have a blanc constructor and did you annotate the fields and methods you need with @FXML?

When I try to implement that, it gives a cannot find symbol error. I have imported javafx.fxml.FXML. I just gave it a blank constructor, to no effect. All the the fields and each method except for the constructor are annotated with @FXML.

John F Bennett
Jan 30, 2013

I always wear my wedding ring. It's my trademark.

I'm looking at my own project right now, did you import javafx.fxml.Initializable in your controller as well? You should then be able to implement the interface there.

What does your main class look like? The one that extends Application.

TheresaJayne
Jul 1, 2011

Ariong posted:

When I try to implement that, it gives a cannot find symbol error. I have imported javafx.fxml.FXML. I just gave it a blank constructor, to no effect. All the the fields and each method except for the constructor are annotated with @FXML.

if you define any other constructor (with parameters) the default constructor doesnt exist

Ariong
Jun 25, 2012

Get bashed, platonist!

John F Bennett posted:

I'm looking at my own project right now, did you import javafx.fxml.Initializable in your controller as well? You should then be able to implement the interface there.


That did the trick! Thanks very much.

geeves
Sep 16, 2004

Has anyone run into any problems with internationalization?

I'm running into separate, but similar issues with java.util.ResourceBundle and struts2. We support about 15 languages. When we added the most recent (Dutch and Turkish) it still defaults to English. Actually Dutch works for struts2, not for ResourceBundle. I don't see anything in the docs that show I'm doing anything incorrectly and the _tr.properties file is in the classpath. We have an app that generates our properties files for us; if the translated property file is not readable for some reason, does ResourceBundle default down to english?

(We also use angular translate and that works and can verify that the translations, or at least a subset of them, are valid).

Edit: Tracked it down to a bad \uxxxx character. Our translation service fat fingered oo instead of 00.

geeves fucked around with this message at 18:29 on Apr 19, 2017

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
I am having a hell of a hard time hiring Java developers in the Bay Area. Doesn't seem like many schools are using Java anymore either so the problem is only gonna get worse. Anybody else dealing with that?

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...
Probably because anyone worth a drat in the bay area is already very well employed.

FateFree
Nov 14, 2003

fletcher posted:

I am having a hell of a hard time hiring Java developers in the Bay Area. Doesn't seem like many schools are using Java anymore either so the problem is only gonna get worse. Anybody else dealing with that?

Ever consider hiring remote developers? I'd only apply for a remote job myself nowadays.

ToxicSlurpee
Nov 5, 2003

-=SEND HELP=-


Pillbug

FateFree posted:

Ever consider hiring remote developers? I'd only apply for a remote job myself nowadays.

To add to that developers in the Bay Area are probably very, very expensive. Are you paying enough? Well developers are expensive in general but still...consider bumping up the pay scale?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

FateFree posted:

Ever consider hiring remote developers? I'd only apply for a remote job myself nowadays.

We have a couple but in general the answer is no, that decision was made way above my pay grade.

ToxicSlurpee posted:

To add to that developers in the Bay Area are probably very, very expensive. Are you paying enough? Well developers are expensive in general but still...consider bumping up the pay scale?

Yeah we have competitive salaries that are appropriate for the Bay Area. There's just so few people that even apply for the positions though, let alone make it to a phone screen to talk compensation.

Carbon dioxide
Oct 9, 2012

fletcher posted:

I am having a hell of a hard time hiring Java developers in the Bay Area. Doesn't seem like many schools are using Java anymore either so the problem is only gonna get worse. Anybody else dealing with that?

That's nonsense. Here in Europe, afaik Java is the language most widely used in businesses (with C# in 2nd place), so schools tend to focus on Java a lot.

9-Volt Assault
Jan 27, 2007

Beter twee tetten in de hand dan tien op de vlucht.

fletcher posted:

Java. Bay Area.

Have you tried porting your application to Rust or Haskell with a mongodb backend to make it webscale instead of using legacy stuff like Java?

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

9-Volt Assault posted:

Have you tried porting your application to Rust or Haskell with a mongodb backend to make it webscale instead of using legacy stuff like Java?

*eye twitch*

John F Bennett
Jan 30, 2013

I always wear my wedding ring. It's my trademark.

Now say something about Java being the new COBOL.

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer
I hope to god there are still people wanting to hire java developers in the coming years...


Ariong posted:

I'm using scene builder for the first time, and I'm stuck at the part where you register your controller class. There's supposed to be a dropdown menu containing each class within the same folder as my FXML file, but there isn't. The only solutions to this problem I can find just say to put the FXML file in the same folder as the controller class, which it already is. No luck. I tried typing the name in manually, but that just resulted in the program spitting out an exception. How do I get Scene Builder to recognize the controller class in the same folder as the FXML file?

I just learned scene builder for a class, so feel free to PM me any questions you have.

One thing my professor taught us in the first week of class is that, while the default implementation of the start method provided by netbeans is this:
code:
@Override
public void start(Stage stage) throws Exception {
	Parent root = FXMLLoader.load(getClass().getResource("UI.fxml"));
        
        Scene scene = new Scene(root);
        
        stage.setScene(scene);
        stage.show();
}
The following is often much more useful because it gives us a reference to the controller.
code:
@Override
public void start(Stage stage) throws Exception {
	FXMLLoader loader = new FXMLLoader(getClass().getResource("UI.fxml"));
        Parent root = loader.load();
        UIController controller = loader.getController();
        
        Scene scene = new Scene(root);
        
        stage.setScene(scene);
        stage.show();
        
        controller.ready(stage); //this method call not possible in the other implementation. 
}

ToxicSlurpee
Nov 5, 2003

-=SEND HELP=-


Pillbug

fletcher posted:

Yeah we have competitive salaries that are appropriate for the Bay Area. There's just so few people that even apply for the positions though, let alone make it to a phone screen to talk compensation.

How is your reputation? What do people say about you on glassdoor? Do you mean actually competitive or "we want above average devs for average industry wages" competitive?

If people aren't even applying there's probably a reason for it.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

Snak posted:

I hope to god there are still people wanting to hire java developers in the coming years...

Enterprise Java has become the COBOL of this century. You'll definitely be able to find something in the next decade.

Volguus
Mar 3, 2009

Volmarias posted:

Enterprise Java has become the COBOL of this century. You'll definitely be able to find something in the next decade.

While Oracle does its best to push people away from Java, I don't think you'll find a platform out there with a more rich, stable, feature-full set of libraries and frameworks. Been working in .NET for the last 6 months and it's been eye opening. .NET is in the dark ages. It was born crippled and has been thrown down the stairs when it was little. With a lot of band-aids, .NET could heal and do something in the world when it grows up, but it's not there yet.

Jo
Jan 24, 2005

:allears:
Soiled Meat

fletcher posted:

We have a couple but in general the answer is no, that decision was made way above my pay grade.


Yeah we have competitive salaries that are appropriate for the Bay Area. There's just so few people that even apply for the positions though, let alone make it to a phone screen to talk compensation.

Do you have a neat product? It's generally my experience as someone in the Bay Area who _wants_ to work with Java but knows a bunch of other languages that the Java positions are relegated to maintaining old codebases or doing SUPER FUN finance/infrastructure dev.

Are you looking for a new backend dev for Awful Yearbook? :v:

arbybaconator
Dec 18, 2007

All hat and no cattle

Hey goons - I'm working on a project for class i'm taking. The project involves creating a very simple baseball game simulator. It will generate a random baseball game between two teams.

Here's what I have coded so far:
  • Two classes - BaseballGame, and Utils (contains getPlayer and batting method)
  • 9 players on each team are stored in an ArrayList
  • The generateGame method iterates through 9 innings via the playInning method
  • The playInning Method uses the playHalfInning method to handle who is at bat, what event occurs after the pitch etc via a batting method which uses probability

I think i've got everything figured out outside of handling the runners/bases/scoring aspect. I've been racking my brain around what the simplest (read: easy) way to handle the players traversing the bases.

I'm not looking for a SOLUTION to the problem - just looking for a few pointers/ideas RE: how to implement efficiently. Any ideas?

Here's my code so far (missing scoring and baserunning related stuffs, obviously, but it compiles and runs)

Baseball Game method:
code:
import java.util.*;

public class BaseBallGame {

    public static void main(String[] args) {
        generateGame();

    }

    public static void generateGame() {

        System.out.println("--------------------------------------------");
        System.out.println("Play Ball!");
        System.out.println("--------------------------------------------");

        int inning = 1;
        boolean gameTied = false;

        do {
            playInning(inning);
            inning++;
        } while ((inning <= 1) || gameTied);

    }

    public static void playInning(int inning) {
        System.out.println("--------------------------------------------");
        System.out.println("Inning " + inning + "!");
        System.out.println("--------------------------------------------");

        playHalfInning("home team");
        playHalfInning("away team");
        //System.out.println(Utils.random());

    }

    public static void playHalfInning(String team) {
        int outs = 0;
        int iterator = 0;
        int score = 0;

        String currentPlayer = "";
        System.out.println(team + " is up!");

        while (outs < 3) {
            currentPlayer = (Utils.getPlayer(team, iterator));
            System.out.println(currentPlayer + " is at bat!");

            outs = outs + Utils.batting(currentPlayer);
            System.out.println("\n" + team + " outs = " + outs + "\n" + "score: " + score);
            iterator++;
        }

    }

}
Utils Method:
code:
import java.util.ArrayList;
import java.util.Random;

public class Utils {

    public static int batting(String currentPlayer) {

        Random rand = new Random();
        int outs = 0;

        int randomInt = rand.nextInt(100);

        if (randomInt <= 70) {
            System.out.println(currentPlayer + " has struck out!");
            outs++;
        } else if (randomInt > 70 && randomInt <= 87) {
            System.out.println(currentPlayer + " has hit a single!");
            //updateField("single");

        } else if (randomInt > 87 && randomInt <= 94) {
            System.out.println(currentPlayer + " has hit a double!");
            //updateField("double");

        } else if (randomInt > 94 && randomInt <= 96) {
            System.out.println(currentPlayer + " has hit a triple!");
            //updateField("triple");
        } else if (randomInt > 96 && randomInt <= 100) {
            System.out.println(currentPlayer + " has hit a HOME RUN!!!!");
            //updateField("homerun");
            //score++;
        }
        return outs;

    }

    public static String getPlayer(String team, int playerAtBat) {

        String currentPlayer = "";

        ArrayList<String> homeTeam = new ArrayList();
        homeTeam.add("doug");
        homeTeam.add("ben");
        homeTeam.add("robert");
        homeTeam.add("andrew");
        homeTeam.add("gable");
        homeTeam.add("adam");
        homeTeam.add("brent");
        homeTeam.add("justin");
        homeTeam.add("ken");

        ArrayList<String> awayTeam = new ArrayList();
        awayTeam.add("bennet");
        awayTeam.add("james");
        awayTeam.add("shane");
        awayTeam.add("oneal");
        awayTeam.add("airon");
        awayTeam.add("ronnie");
        awayTeam.add("corey");
        awayTeam.add("dbo");
        awayTeam.add("david");

        if (team.equals("home team")) {
            currentPlayer = homeTeam.get(playerAtBat);
        } else if (team.equals("away team")) {
            currentPlayer = awayTeam.get(playerAtBat);
        }

        return currentPlayer;

    }
}

Snak
Oct 10, 2005

I myself will carry you to the Gates of Valhalla...
You will ride eternal,
shiny and chrome.
Grimey Drawer
Well, I'm just a student also, so take my advice with a grain of salt.

But here's what I would probably do.

You could model the field as a graph of location objects. This "location" class could have a "players here" attribute which would be a collection of players. You could split this into team a and team b players if you want.

Forget the outfield and the stuff between bases for now, and pretend there are just bases. So you'd have a collection that contained four instances of locations, representing home, first, second, and third base.

depending on how you want to process the actions and how complicated you want to get with it, you could set up some kind of "action queue" and either loop through players on the field and queue their actions, or loop through locations and queue actions for each player found at each location. Regardless of whether you're going to the do the action queue, you probably players, since then you don't end up having to iterate through empty locations for no reason.

So you might want to set it up so that players on the "active team" (the team that's batting) have an attribute indicating their locations, while players on the pitching team are attributes of locations.

That way, you can loop through players on the active team and do something like "what location are they at, run to the next location based on the current one"

Then you can have opposing players at that location decide if they should do something about it.


I got distracted.

Here's what I would do:

Use a queue<player> to model the bases. Initialize it with 4 dummy players who are just "empty base". When a batter hits a single, add the batting player to the queue and poll the queue. If the player polled from the queue is a real player, count a run. If it's an empty player, discard it and do nothing. When a batter hits a double, add the batter and then add a empty player and poll twice. You can write a method to do this that you just call more times. It's a little crude, but it's super straight forward. Bases are a FILO operation.

edit: In theory you could add null the queue instead of a dummy player, but that's not recommended, because it makes the behavior of poll() ambiguous as to whether the queue is empty. But you could do it.

Snak fucked around with this message at 23:22 on Apr 21, 2017

FateFree
Nov 14, 2003

I know this is just a class project but heres what jumps out at me. You should have more classes, since you are trying to model the world in an object oriented way. A Utils class is the devil, thats not a real world object. Things like Games, Players, Teams, Innings - these are objects and this is how your code should be structured. Things organized in this way are much easier to understand. This all might be too dramatic of a change for this project but try to keep that in mind for future ones, because thats the only way you'll be able to represent a complex system in a manageable way.

For example, a Team class might have a List<Player> of players, and a boolean for isHomeTeam(). A Player might have a String name and position and batting averages and whatnot. The Game class might keep track of the score and own a list of Innings. Each Inning can hold the score from either team. The game or Stadium class might keep track of the bases, which could just be an array of Players of size 4. Initially empty, players can move from one base to another as the previous one hits, just like how their real life counterparts work. A lot of your logic would involve moving player objects around this array and increasing the score every time a player reaches the last index (at which point he is removed).

Adbot
ADBOT LOVES YOU

CPColin
Sep 9, 2003

Big ol' smile.
One way or another, you need to keep track of the state of the three bases. If you care which player is on a given base (and if you had a Player class or enum), you could have:

code:
   Player firstBase;
   Player secondBase;
   Player thirdBase;
If, on the other hand, you only care whether or not a base is occupied, you could have:

code:
   boolean firstBase;
   boolean secondBase;
   boolean thirdBase;
Then, your batting() code could update the scores and bases.

At this point, you're starting to pass a lot of state around, so you'll want to start thinking about how all the state fits together. Like, what parts of the game are the same every time you run the simulator? (Does the state of the game need to track who's on each team or just who's up to bat next? Does each team care if it's the home team or does only the game care about that? Stuff like that.)

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