Needing help with my first software engineering project (Hospital vital simulator)

208 Replies
JavaBot
JavaBot2y ago
This post has been reserved for your question.
Hey @springbean! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
JavaBot
JavaBot2y ago
Please format your code & make it more readable. For the java programming language, it should look like this:
```java public class Main { public static void main(String[] args){ System.out.println("Hello World!"); } ```
• These are backticks, not quotes.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
JavaBot
JavaBot2y ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
JavaBot
JavaBot2y ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
JavaBot
JavaBot2y ago
// DataReader reader
// DataReader reader
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
Cyro²
Cyro²2y ago
I am happy to break it down: 1. git checkout -b my-master master - Preserve the changes you pushed to master in a new branch called my-master 2. git branch -D master With my-master checked out, delete your local master because it is about to be replaced by the upstream master 3. git remote add upstream https://github.com/tpepels/signal_project.git Add a new remote called upstream to your local repo that refers to the prof's repo. 4. git checkout -t upstream/master - Checkout the clean master branch from upstream
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
JavaBot
JavaBot2y ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
omg I was late to the party I wanna pitch in whats happening
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
hmm they made classes? I think you sent a github repo imma check it out
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
also I was thinking although ive never tried it myself there should be subsystems for projects like these, making smaller subsytems and creating jars for them to use and then combining them all together sort of like references APIs its a pretty big project fs fs
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
yeah so its like the final stretch I getcha Im thinking of forking and putting up pull requests for changes I make, that fine or do they expect this to be a one person project?
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
ok ok sounds good then adding on to this, you can make a complete utility class for this using generics to make it so that you can essentially use it for any type shouldnt most of the classes like Person just be POJOs
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
icwym yeah I suppose making POJOs for them using a library wouldnt be effective ok looking into the code rn brb
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
I though DataStorage would be storing the Patients you create into a table somewhere in a db but it looks like its just storing into a HashMap right?
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
what about the patient class is confusing
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
yep following the constructor
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
you have to use the addRecord
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
yep
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
No description
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
yeah naturally that would do
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
wouldnt IOExceptions be unchecked? I feel as if they occur when running the program so you cant use throws right? It would make sense to try catch if you expect them to occur
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
sounds good sounds good not really Patient.PatientRecords more like creating a patient object that will have a punch of patient records and you iterate through it and in order to do that you provide a start time and an end time. the start time and end time is going to filter out all records that dont fit within that specific range and provide you a list of PatientRecord
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
my first guess is to use streams ill implement something hold up I wont lie I think a little JUnit testing for single classes might be up for consideration
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
like creating some tests to see that the individual parts are working as intended in the program alot more work tbf
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
oh ok that should be the easiest part unless ofc we are testing for all cases
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
ah
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
return patientRecords.stream()
.filter(record -> ValueRange.of(startTime, endTime).isValidValue(record.getTimeStamp()))
.collect(Collectors.toList());
return patientRecords.stream()
.filter(record -> ValueRange.of(startTime, endTime).isValidValue(record.getTimeStamp()))
.collect(Collectors.toList());
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
streams are hardly covered in Java in general but they are really easy to read I think it just looks shit above because its so big but basically its filtering the List where the range is between the startTime and the endTime for the timestamp of each record in patientRecords collecting them and then converting it to a list to return
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
well for streams is basically just simplifying processing of collections (like list, arraylist, etc) and seqs of data. I come from C# and in C# we use something like LINQ its very expressive and nice to have as it allows you to filter out data to get what you want Streams is basically filtering out the data, based on a query and some limits and then returning whatever fits them
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
theres a whole guide on the most common methods used lemme send them
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
probably because it doesnt exist
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
hmm
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
try this then
return patientRecords.stream()
.filter(record -> record.getTimeStamp() >= startTime && record.getTimeStamp <= endTime)
.collect(Collectors.toList());
return patientRecords.stream()
.filter(record -> record.getTimeStamp() >= startTime && record.getTimeStamp <= endTime)
.collect(Collectors.toList());
does it work?
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
Eugen Paraschiv
Stackify
A Guide to Java Streams in Java 8 - Stackify
Java streams were a much anticipated Java feature. Learn how to use the supported operations to write cleaner and more concise code.
verbose
verbose2y ago
this should help although I dont know why the above stream isnt working for you
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
damn I just came back from the doctors anyway what I miss well yeah its an API that esentially helps with filtering data or processing it in a certain way that along side a couple other things. Streams are mostly a functional paradigm concept so they us functional interfaces alongside other things I can say for sure that streams make it 10x easier then using a for loop or any loop
JavaBot
JavaBot2y ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
Cyro²
Cyro²2y ago
@Override
public DataStorage readData(DataStorage dataStorage, String filePath) throws IOException {
DataStorage dS = new DataStorage();
if(filePath == null || filePath.isEmpty()){
throw new IllegalArgumentException("File path needs to be established");
}
try(Stream<String> stream = Files.lines(Paths.get(filePath))){
stream.forEach(line ->{DataStorage.addPatientData(line)});
}
return dS;
}
public DataStorage readData(DataStorage dataStorage, String filePath) throws IOException {
DataStorage dS = new DataStorage();
if(filePath == null || filePath.isEmpty()){
throw new IllegalArgumentException("File path needs to be established");
}
try(Stream<String> stream = Files.lines(Paths.get(filePath))){
stream.forEach(line ->{DataStorage.addPatientData(line)});
}
return dS;
}
i've started experimenting with streams
This message has been formatted automatically. You can disable this using /preferences.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
ok looking into this code it takes in 2 params being dataStorage and filePath but you dont actually use the first param anywhere within the code. You create a new DataStorage object and then do your usual guard clausing to check for nulls and what not when it can be done first and foremost this is most likely an import issue, you might have either forgot to import (if you dont have it setup) or there might be another class that is exactly named this
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
guard clausing is a technique that you used when you were checking wether the string is empty or null think of it like a preliminary check for each of the parameters BEFORE the function uses them or needs them to do some task
verbose
verbose2y ago
Replace Nested Conditional with Guard Clauses
Problem: You have a group of nested conditionals and it’s hard to determine the normal flow of code execution. Solution: Isolate all special checks and edge cases into separate clauses and place them before the main checks. Ideally, you should have a “flat” list of conditionals, one after the other.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
yes you are already doing it but its best practice to start with it first and foremost without creating any objects or manipulating any data yes which makes is kinda useless to create a new DataStorage object and use that when you can use the parameter provided there are some ways I can think of but it might take me some time to write it out lemme get to it
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
yeah that for the most part is fine there is nothing wrong with that but I believe the code for your stream could be simplified
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
came up with something like this
@Override
public DataStorage readData(DataStorage dataStorage, String filePath) throws IOException {
if(filePath == null || filePath.isEmpty()){
throw new IllegalArgumentException("File Path Cannot Be Null or Empty!");
}

if (dataStorage == null || !(dataStorage instanceof DataStorage)) {
throw new IllegalArgumentException("Data Storage Cannot Be Null or Not an Instance of DataStorage!");
}

Files.lines(Paths.get(filePath)).forEach(line -> {
String[] values = line.split(",");

dataStorage.addPatientData(
Integer.parseInt(values[0]),
Double.parseDouble(values[1]),
values[2],
Long.parseLong(values[3])
);
});

return dataStorage;
}
@Override
public DataStorage readData(DataStorage dataStorage, String filePath) throws IOException {
if(filePath == null || filePath.isEmpty()){
throw new IllegalArgumentException("File Path Cannot Be Null or Empty!");
}

if (dataStorage == null || !(dataStorage instanceof DataStorage)) {
throw new IllegalArgumentException("Data Storage Cannot Be Null or Not an Instance of DataStorage!");
}

Files.lines(Paths.get(filePath)).forEach(line -> {
String[] values = line.split(",");

dataStorage.addPatientData(
Integer.parseInt(values[0]),
Double.parseDouble(values[1]),
values[2],
Long.parseLong(values[3])
);
});

return dataStorage;
}
for this its not necessary to have instanceof and can be removed yeah sure whats the issue with the alert generator?
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
its definitely not the way to setup a OOP oriented project I can understand that
Cyro²
Cyro²2y ago
package com.alerts; import com.data_management.DataStorage; import com.data_management.Patient; / ```java * The {@code AlertGenerator} class is responsible for monitoring patient data * and generating alerts when certain predefined conditions are met. This class * relies on a {@link DataStorage} instance to access patient data and evaluate * it against specific health criteria. */ public class AlertGenerator { private DataStorage dataStorage; / * Constructs an {@code AlertGenerator} with a specified {@code DataStorage}. * The {@code DataStorage} is used to retrieve patient data that this class * will monitor and evaluate. * * @param dataStorage the data storage system that provides access to patient * data */ public AlertGenerator(DataStorage dataStorage) { this.dataStorage = dataStorage; } / * Evaluates the specified patient's data to determine if any alert conditions * are met. If a condition is met, an alert is triggered via the * {@link #triggerAlert} * method. This method should define the specific conditions under which an * alert * will be triggered. * * @param patient the patient data to evaluate for alert conditions */ public void evaluateData(Patient patient) { // Implementation goes here } / * Triggers an alert for the monitoring system. This method can be extended to * notify medical staff, log the alert, or perform other actions. The method * currently assumes that the alert information is fully formed when passed as * an argument. * * @param alert the alert object containing details about the alert condition */ private void triggerAlert(Alert alert) { // Implementation might involve logging the alert or notifying staff } } ```
This message has been formatted automatically. You can disable this using /preferences.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
ok those are requirements that can be put into their own functions
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
I feel as if there are better ways to do this but the moving window would work the best for this situation. However you could also go ahead and use the Observer pattern with a few modifications where you would subscribe to an object holding the data you mentioned prior and if there are any changes it will notify all subscribers.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
yeah sure so for the Observer pattern you would need a manager, a concrete publisher class which will publish at an interval (say every 5 seconds there could be a thread.sleep()) and subscribers which will be checking for requirements being the following: heart rate drops or spikes blood saturation below a certain threshold etc
verbose
verbose2y ago
this guide is the best from refactoring guru: https://refactoring.guru/design-patterns/observer/java/example
Observer in Java / Design Patterns
Observer pattern in Java. Full code example in Java with detailed comments and explanation. Observer is a behavioral design pattern that allows some objects to notify other objects about changes in their state.
verbose
verbose2y ago
the manager is responsible for notifying every subscriber
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
ok sounds good lemme know how it goes basically one object subscribes to the change of state of another object in this case it would be the AlertGenerator subscribed to any changes in data within the DataStorage? you would need a manager instance most likely a single instance so using a Singleton would work
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
from there it will orchestrate the subscriptions and manage them basically
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
yeah just another class for managing everything I was thinking it would be better to have a hashmap or some data structure that stores thresholds
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
yeah the name is arbitrary it doesnt really matter the name but thats the way to go about it
verbose
verbose2y ago
it would look something like this:
No description
verbose
verbose2y ago
with some modifications based on your needs this reference gives more details on the implementation: https://github.com/ZanXusV/java-design-patterns/blob/master/observer-pattern/observer-design-pattern.md
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
yeah basically thats the intention, the naming for it is kinda odd it should be ConcreteManager but it works nw nw
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
I feel like this is the peak of a sigmoid curve for the difficulty of this project I do love a challenge but its most likely going to get easier from here
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
I wish I could help out a bit more practically other than yapping but yeah its a good learning exercise fs fs
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
ask away
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
but?
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
well my current understanding was looking at it this way with what we have right now, I was thinking it would be better to make PatientRecord an actual record since its easier to work with, and provide some internal methods to datastorage and alertgenerator the EventManager (Manager in this case) would be responsible for handling instances of DataStorage (which usually for something to publish there should be a topic it publishes data to) and instances for AlertGenerator (which usually for something to subscribe it would need a topic to subscribe to) the manager class for now could be responsible for sending it back and forth and then if there are any changes of data then it would notify its subscribers for now this is a good rough layout before polishing everything
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
PatientRecord is a class with but if made into a record it would reduce the boilerplate, its not a necessity but it will make it easier
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
making those changes will save you the hassle of writing too much boilerplate but this is a distraction from the implementation that needs to be done right now
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
yeah and depending on how many instances you require it would make it more streamlined and easier to manage
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
its only dependent on the implementation, but I believe this design pattern is pretty sound proof
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
sounds good lemme know how it goes
JavaBot
JavaBot2y ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
honestly you might wanna give a bit of a synopsys of what's up at the moment since if anyone else would spring up to try and help I doubt they would wanna read over 900 messages
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
what is causing you headaches with the observer pattern?
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
yeah sure wsp I feel like working with your teachers template is giving all the more headaches
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
what are the erros are they syntax wise or is there a stack trace to refer from? we can work from there wouldnt blame you, do you have to follow your teachers template?
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
oh these errors are just from your Subject interface you havent implemented some methods
nikcho-kouhai
nikcho-kouhai2y ago
just implement the methods from interface Subject you can generate them by clicking alt+enter I believe
verbose
verbose2y ago
yeah that would work
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
try rebuilding your project
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
ok so for the args its just a @param so you can remove that
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
yeah the error for args is nothing have you overriden all of these methods?
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
hmm it might not mean much but you can try rebuilding it
nikcho-kouhai
nikcho-kouhai2y ago
I only see DataProcessor.Observer you have overloaded functions which take 2 different types of Observer they are from different packages which is hella confusing by the way not to mention that the DataStorage on the first method of the interface is called Observer this interface is incredibly messy
verbose
verbose2y ago
another thing to note your github repo isnt up to date with the latest changes youve made, after this probably push so its easier to view the full code
nikcho-kouhai
nikcho-kouhai2y ago
yeah I was also gonna say that
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
just take it slow
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
first of all why do you need two different types of Observers?
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
I am not sure if I understand what you are trying to do Okay, can you send me the code for your observer and tell me what that Observer is supposed to be doing
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
Cyro²
Cyro²2y ago
package com.data_management; import java.util.List;
public interface Observer {
void update(List<Patient> patients);
void markPatientProcessed(Patient patient);
}
public interface Observer {
void update(List<Patient> patients);
void markPatientProcessed(Patient patient);
}
This message has been formatted automatically. You can disable this using /preferences.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
I believe you may be misunderstanding what the purpose of the Observer is supposed to be okay, which classes implement the Observer interface?
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
can you send me the code for one of these classes? For example the heart monitor
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
Okay here's a thing though there is no point to be doing that in the Observer itself Actually which is the class that notifies the Observers? From what I can see it's the DataStorage class how about this: Make all the necessary checks for all the patient information such as heart beat, blood pressure and such if there is an abnormality that needs to be handled update the observers with that particular Patient object instead of passing the list with all the Patient objects you can also add logic to indicate exactly what is wrong with this Patient it can be some sort of int that holds flags as bits or if you want to make it simpler you can make it a class that just wraps a bunch of booleans like isHeartRateHigh or isBloodPressureHigh (there are a multitude of ways to implement this, this is just the simplest one I can think of) this way you also don't need 20 different classes that implement the Observer interface you just need one that checks those booleans in its update method and takes action depending on what's flagged and what's not
verbose
verbose2y ago
you could also considering going with Enums to represent different types of issues like HIGH_HEART_RATE or BLOOD_PRESSURE_LOW, etc.
nikcho-kouhai
nikcho-kouhai2y ago
You can but I wrote it out because like that it's hard to indicate multiple things at once that's why I suggested an int flag variable instead because you can't really send enums like HIGH_HEART_RATE | BLOOD_PRESSURE_LOW of course you can make a workaround for it. I just feel like it's not worth the hassle as there are easier alternatives in this case
verbose
verbose2y ago
yeah there's definitely better alternatives what I was suggesting was something I would have to make rn but I have an example here
public enum ExceptionType {
INV_FILE_PATH("INV_FP", "Invalid File Path."),
INV_FILE_TYPE("INV_FT", "Invalid File Type."),
INV_FILE_FORMAT("INV_FF", "Invalid File Format."),
INV_FILE_CONTENT("INV_FC", "Invalid File Content."),
INV_FILE_NAME("INV_FN", "Invalid File Name."),

INV_SESSION_TIMEOUT("INV_SESH_T", "Invalid Session Timeout."),
INV_CONNECTION_TIMEOUT("INV_CONN_T", "Invalid Connection Timeout."),
INV_POOL_SIZE("INV_POOL", "Invalid Pool Size."),
INV_DETECTION_THRESHOLD("INV_DETE_T", "Invalid Detection Threshold.");

private final String shortHand;
private final String desc;

ExceptionType(final String shortHand, final String desc) {
this.shortHand = shortHand;
this.desc = desc;
}

public static Optional<ExceptionType> getExceptionByShortHand(final String shortHand)
throws ExceptionTypeNotFoundException {
return Optional.ofNullable(Arrays.stream(ExceptionType.values())
.filter(exception -> exception.shortHand.equalsIgnoreCase(shortHand))
.findFirst()
.orElseThrow(() -> new ExceptionTypeNotFoundException("No Such Exception Found."))); // Throwing an Exception for Nullable?
}

//region Getters
public String getShortHand() {
return shortHand;
}

public String getDesc() {
return desc;
}
//endregion

@Override
public String toString() {
return "%s, %s".formatted(this.shortHand, this.desc);
}
}
public enum ExceptionType {
INV_FILE_PATH("INV_FP", "Invalid File Path."),
INV_FILE_TYPE("INV_FT", "Invalid File Type."),
INV_FILE_FORMAT("INV_FF", "Invalid File Format."),
INV_FILE_CONTENT("INV_FC", "Invalid File Content."),
INV_FILE_NAME("INV_FN", "Invalid File Name."),

INV_SESSION_TIMEOUT("INV_SESH_T", "Invalid Session Timeout."),
INV_CONNECTION_TIMEOUT("INV_CONN_T", "Invalid Connection Timeout."),
INV_POOL_SIZE("INV_POOL", "Invalid Pool Size."),
INV_DETECTION_THRESHOLD("INV_DETE_T", "Invalid Detection Threshold.");

private final String shortHand;
private final String desc;

ExceptionType(final String shortHand, final String desc) {
this.shortHand = shortHand;
this.desc = desc;
}

public static Optional<ExceptionType> getExceptionByShortHand(final String shortHand)
throws ExceptionTypeNotFoundException {
return Optional.ofNullable(Arrays.stream(ExceptionType.values())
.filter(exception -> exception.shortHand.equalsIgnoreCase(shortHand))
.findFirst()
.orElseThrow(() -> new ExceptionTypeNotFoundException("No Such Exception Found."))); // Throwing an Exception for Nullable?
}

//region Getters
public String getShortHand() {
return shortHand;
}

public String getDesc() {
return desc;
}
//endregion

@Override
public String toString() {
return "%s, %s".formatted(this.shortHand, this.desc);
}
}
taking this code you can probably provide ranges for the enum lets say something like BLOOD_PRESSURE(min, max) which can be ints if they fall below the min or go higher than the max then you can just use these instead
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
verbose
verbose2y ago
but this approach is much more time consuming
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
yeah, that's why I just didn't suggest it I'll make a simple example
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
Okay so here is a minimalistic example of how this might work you don't need to follow it like some guide book, it's just something I quickly wrote up. Here is your Observer interface:
public interface Observer {
class PatientState{
boolean highDiastolic;
boolean highSistolic;
boolean highHeartRate;
boolean isOk;
}
void update(Patient patient,PatientState state);
}
public interface Observer {
class PatientState{
boolean highDiastolic;
boolean highSistolic;
boolean highHeartRate;
boolean isOk;
}
void update(Patient patient,PatientState state);
}
Here is the implementation for the Observer interface:
public class ObserverImpl implements Observer{
@Override
public void update(Patient patient, PatientState state) {
if(state.highHeartRate){
//do something if the heart rate is high
}
if(state.highSistolic){
//do something if sistolic blood pressure is high
}
if(state.highDiastolic){
//do something if diastolic blood pressure is high
}
}
}
public class ObserverImpl implements Observer{
@Override
public void update(Patient patient, PatientState state) {
if(state.highHeartRate){
//do something if the heart rate is high
}
if(state.highSistolic){
//do something if sistolic blood pressure is high
}
if(state.highDiastolic){
//do something if diastolic blood pressure is high
}
}
}
Here is the Patient class:
public class Patient {
public int systolicBloodPressure;
public int diastolicBloodPressure;
public int heartRate;
}
public class Patient {
public int systolicBloodPressure;
public int diastolicBloodPressure;
public int heartRate;
}
and here is the DataStorage class:
import java.util.ArrayList;
import java.util.List;

public class DataStorage {
List<Patient> patients = new ArrayList<>();
List<Observer> observers = new ArrayList<>();
/*Logic here for adding patients to the list or whatever else is needed...*/

public void addObserver(Observer obs){
observers.add(obs);
}
public void removeObserver(Observer obs){
observers.remove(obs);
}
public void checkAbnormalities(){
for (Patient p :patients) {
Observer.PatientState curState = checkPatient(p);
if(!curState.isOk){
fireAbnormalEvent(p,curState);
}
}
}
private void fireAbnormalEvent(Patient p, Observer.PatientState state){
for(Observer obs:observers){
obs.update(p,state);
}
}
private Observer.PatientState checkPatient(Patient p){
Observer.PatientState state = new Observer.PatientState();
if(p.diastolicBloodPressure >140){
state.highDiastolic=true;
}
if(p.systolicBloodPressure>140){
state.highSistolic=true;
}
if(p.heartRate>80){
state.highHeartRate=true;
}
state.isOk= !state.highSistolic && !state.highDiastolic && !state.highHeartRate;
return state;
}

}
import java.util.ArrayList;
import java.util.List;

public class DataStorage {
List<Patient> patients = new ArrayList<>();
List<Observer> observers = new ArrayList<>();
/*Logic here for adding patients to the list or whatever else is needed...*/

public void addObserver(Observer obs){
observers.add(obs);
}
public void removeObserver(Observer obs){
observers.remove(obs);
}
public void checkAbnormalities(){
for (Patient p :patients) {
Observer.PatientState curState = checkPatient(p);
if(!curState.isOk){
fireAbnormalEvent(p,curState);
}
}
}
private void fireAbnormalEvent(Patient p, Observer.PatientState state){
for(Observer obs:observers){
obs.update(p,state);
}
}
private Observer.PatientState checkPatient(Patient p){
Observer.PatientState state = new Observer.PatientState();
if(p.diastolicBloodPressure >140){
state.highDiastolic=true;
}
if(p.systolicBloodPressure>140){
state.highSistolic=true;
}
if(p.heartRate>80){
state.highHeartRate=true;
}
state.isOk= !state.highSistolic && !state.highDiastolic && !state.highHeartRate;
return state;
}

}
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
you can copy them over somewhere so they can be formatted and not squished
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
yeah also the PatientData class seems obsolete
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
just store all the Patient data as fields in the Patient class
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
It's not that you can't do it like that but in my opinion it's way overcomplicating things
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
by the way I would just like to mention that I think that the observer pattern here is pointless as well
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
because it's unlikely you would need more than one object to do the handling of a Patient with abnormalities let me modify the code a little bit to explain what I mean
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
okay so here is the new stuff instead of an Observer interface we have this:
public interface AbnormalityHandler {
class PatientState{
boolean highDiastolic;
boolean highSistolic;
boolean highHeartRate;
boolean isOk;
}
void handlePatientWithAbnormalities(Patient p,PatientState state);
}
public interface AbnormalityHandler {
class PatientState{
boolean highDiastolic;
boolean highSistolic;
boolean highHeartRate;
boolean isOk;
}
void handlePatientWithAbnormalities(Patient p,PatientState state);
}
the implementation is this:
public class AbnormalityHandlerImpl implements AbnormalityHandler{

@Override
public void handlePatientWithAbnormalities(Patient p, PatientState state) {
if(state.highHeartRate){
//do something if the heart rate is high
}
if(state.highSistolic){
//do something if sistolic blood pressure is high
}
if(state.highDiastolic){
//do something if diastolic blood pressure is high
}
}
}
public class AbnormalityHandlerImpl implements AbnormalityHandler{

@Override
public void handlePatientWithAbnormalities(Patient p, PatientState state) {
if(state.highHeartRate){
//do something if the heart rate is high
}
if(state.highSistolic){
//do something if sistolic blood pressure is high
}
if(state.highDiastolic){
//do something if diastolic blood pressure is high
}
}
}
and this is the modified DataStorage class:
import java.util.ArrayList;
import java.util.List;

public class DataStorage {
List<Patient> patients = new ArrayList<>();
AbnormalityHandler handler;
DataStorage(AbnormalityHandler handler){
this.handler=handler;
}

/*Logic here for adding patients to the list or whatever else is needed...*/


public void checkAbnormalities(){
for (Patient p :patients) {
AbnormalityHandler.PatientState curState = checkPatient(p);
handler.handlePatientWithAbnormalities(p,curState);
}
}

private AbnormalityHandler.PatientState checkPatient(Patient p){
AbnormalityHandler.PatientState state = new AbnormalityHandler.PatientState();
if(p.diastolicBloodPressure >140){
state.highDiastolic=true;
}
if(p.systolicBloodPressure>140){
state.highSistolic=true;
}
if(p.heartRate>80){
state.highHeartRate=true;
}
state.isOk= !state.highSistolic && !state.highDiastolic && !state.highHeartRate;
return state;
}

}
import java.util.ArrayList;
import java.util.List;

public class DataStorage {
List<Patient> patients = new ArrayList<>();
AbnormalityHandler handler;
DataStorage(AbnormalityHandler handler){
this.handler=handler;
}

/*Logic here for adding patients to the list or whatever else is needed...*/


public void checkAbnormalities(){
for (Patient p :patients) {
AbnormalityHandler.PatientState curState = checkPatient(p);
handler.handlePatientWithAbnormalities(p,curState);
}
}

private AbnormalityHandler.PatientState checkPatient(Patient p){
AbnormalityHandler.PatientState state = new AbnormalityHandler.PatientState();
if(p.diastolicBloodPressure >140){
state.highDiastolic=true;
}
if(p.systolicBloodPressure>140){
state.highSistolic=true;
}
if(p.heartRate>80){
state.highHeartRate=true;
}
state.isOk= !state.highSistolic && !state.highDiastolic && !state.highHeartRate;
return state;
}

}
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
well I'd say that for your particular situation this is the best approach
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
you can move the patient state checking logic to the AbnormalityHandler interface as well if you would like ah in the checkAbnormalities method there should be a check for whether the patient is ok before firing the event
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
of course you can do that logic check in the actual AbnormalityHandler as well
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
it's just checking the isOk boolean
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
yeah. I'd say that in your situation this is probably the best approach good luck!
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
alright, feel free to ask again if something else comes up.
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
I am not sure exactly what you mean by that can you show me an example? Perhaps just your Patient class will be enough I will probably be going to bed soon though so I'd say the earliest I'll respond after a bit is tomorrow
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
still here so maybe we can get this sorted out before I go to bed
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
nikcho-kouhai
nikcho-kouhai2y ago
can you not just make a getter?
Unknown User
Unknown UserOP2y ago
Message Not Public
Sign In & Join Server To View
JavaBot
JavaBot2y ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?