How to shorten the condition code ? (JAV, Check null) - java

I use it to check for null.DataSet has a structure of both String Integer and Bigdecimal data types.
How to shorten the condition code? Is there any way? To shorten my code. Thank you.
public void ConfrimData(DataSet data) {
if (StringUtils.isEmpty(data.getA())
|| StringUtils.isEmpty(data.getB())
|| StringUtils.isEmpty(data.getC())
|| StringUtils.isEmpty(data.getD())
|| StringUtils.isEmpty(data.getE())
|| StringUtils.isEmpty(data.getF())
){
if (StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (StringUtils.isEmpty(data.getB())) {
loggerTransaction.info(Var.VALUE_B);
}
if (StringUtils.isEmpty(data.getC())) {
loggerTransaction.info(Var.VALUE_C);
}
if (StringUtils.isEmpty(data.getD())) {
loggerTransaction.info(Var.VALUE_D);
}
if (StringUtils.isEmpty(data.getE())) {
loggerTransaction.info(Var.VALUE_E);
}
if (StringUtils.isEmpty(data.getF())) {
loggerTransaction.info(Var.VALUE_F);
}
return;
}
_DataSet
private String A = null;
private Integer B = null;
private String C= null;
private String D = null;
private BigDecimal E= null;
private String F= null;

Well, you could make it slightly less repeaty using streams, but it won't make it necessarily better, let alone faster:
LinkedHashMap<Supplier, String> map = new LinkedHashMap<>();
map.put(data::getA, Var.VALUE_A);
map.put(data::getB, Var.VALUE_B);
map.put(data::getC, Var.VALUE_C);
map.put(data::getD, Var.VALUE_D);
map.put(data::getE, Var.VALUE_E);
map.put(data::getF, Var.VALUE_F);
List<String> logMessages = map.entrySet().stream()
.filter(entry -> StringUtils.isEmpty(entry.getKey().get()))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
if (!logMessages.isEmpty()) {
logMessages.forEach(loggerTransaction::info);
}
else {
// Remaining code
}

In your first if statement you check all the parameters to see if any of them are empty.
Then, in the inner if statements, you check them again. The first check is redundant. The return statement is also not necessary since it does not end the method early or returns any data.
Here is a shorter version that should give the same result:
public void confirmData(DataSet data) {
if (StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (StringUtils.isEmpty(data.getB())) {
loggerTransaction.info(Var.VALUE_B);
}
if (StringUtils.isEmpty(data.getC())) {
loggerTransaction.info(Var.VALUE_C);
}
if (StringUtils.isEmpty(data.getD())) {
loggerTransaction.info(Var.VALUE_D);
}
if (StringUtils.isEmpty(data.getE())) {
loggerTransaction.info(Var.VALUE_E);
}
if (StringUtils.isEmpty(data.getF())) {
loggerTransaction.info(Var.VALUE_F);
}
}
EDIT
Here is a slightly prettier solution with less code repetition:
public void confirmData(DataSet data) {
logIfEmpty(data.getA(), Var.VALUE_A);
logIfEmpty(data.getB(), Var.VALUE_B);
logIfEmpty(data.getC(), Var.VALUE_C);
logIfEmpty(data.getD(), Var.VALUE_D);
logIfEmpty(data.getE(), Var.VALUE_E);
logIfEmpty(data.getF(), Var.VALUE_F);
}
private void logIfEmpty(Object check, String log) {
if (StringUtils.isEmpty(check)) {
loggerTransaction.info(log);
}
}
EDIT #2
And if you have other code you want to execute if you did not find any empty values, you can do this:
public void confirmData(DataSet data) {
boolean foundEmpty;
foundEmpty = logIfEmpty(data.getA(), Var.VALUE_A);
foundEmpty = logIfEmpty(data.getB(), Var.VALUE_B) || foundEmpty;
foundEmpty = logIfEmpty(data.getC(), Var.VALUE_C) || foundEmpty;
foundEmpty = logIfEmpty(data.getD(), Var.VALUE_D) || foundEmpty;
foundEmpty = logIfEmpty(data.getE(), Var.VALUE_E) || foundEmpty;
foundEmpty = logIfEmpty(data.getF(), Var.VALUE_F) || foundEmpty;
if(foundEmpty) {
return;
}
}
private boolean logIfEmpty(String check, String log) {
if (StringUtils.isEmpty(check)) {
loggerTransaction.info(log);
return true;
}
return false;
}

Maybe assigning a flag...
public void ConfrimData(DataSet data) {
boolean flag;
if (flag = StringUtils.isEmpty(data.getA())) {
loggerTransaction.info(Var.VALUE_A);
}
if (flag = StringUtils.isEmpty(data.getB()) || flag) {
loggerTransaction.info(Var.VALUE_B);
}
if (flag = StringUtils.isEmpty(data.getC()) || flag) {
loggerTransaction.info(Var.VALUE_C);
}
if (flag = StringUtils.isEmpty(data.getD()) || flag) {
loggerTransaction.info(Var.VALUE_D);
}
if (flag = StringUtils.isEmpty(data.getE()) || flag) {
loggerTransaction.info(Var.VALUE_E);
}
if (flag = StringUtils.isEmpty(data.getF()) || flag) {
loggerTransaction.info(Var.VALUE_F);
}
if (flag) return;

Related

Swap if/else conditions/code blocks according to a bool flag

I have the following method:
private void filterMode1(Map<String, String> appToPlat, Map<String, FunctAndPlat> overMap,
List<Merged> merged, List<Merged> missing, String app, String funct) {
if (overMap.containsKey(app)) {
String plat = overMap.get(app).getPlat();
merged.add(new Merged(plat, app, func));
} else if (appToPlat.containsKey(app)) {
String plat = appToPlat.get(app);
merged.add(new Merged(plat, app, func));
} else {
missing.add(new Merged("", app, funct));
}
}
According to a boolean flag I may need to swap condition2/block2 with condition1/block1 so
cond2 is checked first; it becomes:
private void filterMode2(Map<String, String> appToPlat, Map<String, FunctAndPlat> overMap,
List<Merged> merged, List<Merged> missing, String app, String funct) {
if (appToPlat.containsKey(app)) {
String plat = appToPlat.get(app);
merged.add(new Merged(plat, app, func));
} else if (overMap.containsKey(app)) {
String plat = overwritesMap.get(app).getPlat();
merged.add(new Merged(plat, app, func));
} else {
missing.add(new Merged("", app, func));
}
}
And the result is:
if (boolFlag) {
filterMode2(..);
} else {
filterMode1(..);
}
How to get rid of the duplicate code in the two methods?
Using condition1 and condition2 variables and && (and), || (or), ! (not) it will look something like this:
if (condition1 && boolFlag || condition2 && !boolFlag) {
.........
} else if (condition1 && !boolFlag || condition2 && boolFlag) {
........
} else {
.......
}

Check if extends jTextFormattedField is empty

I have one extends jFormattedTextField and in this field, I have a method to verify if it is empty, but in jTextField it works, but in jFormattedTextField no.
As I pass the fields on my frame:
RVDFormattedTextField[] obrigatoriosFTF = new RVDFormattedTextField[1];
private void setaObrigatorios() {
obrigatoriosFTF[0] = rvfCNPJ;
}
if (RVDFormattedTextField.isEmpty(obrigatoriosFTF)) {
Mensagem.aviso("Preencha os campos obrigatórios (*).", this);
} else {
Method in jFormattedTextField:
public static boolean isEmpty(RVDFormattedTextField[] campos) {
Boolean ok = false;
for (int i = 0; i < campos.length; i++) {
if (Formatacao.removerFormatacao(campos[i].getText()).trim().isEmpty()) {
ok = true;
if (campos[i].isEditable()) {
campos[i].setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 51, 51)));
}
} else {
campos[i].setBorder(javax.swing.BorderFactory.createEtchedBorder());
}
}
return ok;
}
Does not show errors, tried to put a sout in the method and debug however nothing happens.
Method removerFormatacao
public static String removerFormatacao(String dado) {
String retorno = "";
for (int i = 0; i < dado.length(); i++) {
if (dado.charAt(i) != '.' && dado.charAt(i) != '/' && dado.charAt(i) != '-' && dado.charAt(i) != '(' && dado.charAt(i) != ')') {
retorno = retorno + dado.charAt(i);
}
}
return (retorno);
}
Method formatarCNPJ (mask)
public static void formatarCnpj(JFormattedTextField campo) {
try {
MaskFormatter m = new MaskFormatter();
m.setPlaceholderCharacter(' ');
m.setMask("##.###.###/####-##");
campo.setCaretPosition(0);
campo.setFormatterFactory(null);
campo.setFormatterFactory(new DefaultFormatterFactory(m));
campo.setValue(null);
} catch (Exception e) {
System.err.println(e);
}
}
I tried to remove these two methods, but it still didn't work.
Well, which mask is used on the JFormattedText and how is the Formatacao.removerFormatacao implementation?

javafx Caused by: java.lang.UnsupportedOperationException

when i try to add an "object" to database and then show it to TableView it shows me UnsupportedOperationException . Everything was fine until i add this code to "public void initialize()" to make textfields as "SearchBoxes":
FilteredList <Paisjet> filteredData = new FilteredList<>(data,e -> true);
paisjaSearch.textProperty().addListener((observableValue,oldValue,newValue) ->
{
filteredData.setPredicate( paisjet ->
{
if(newValue == null || newValue.isEmpty())
{
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if(paisjet.getPaisja().toLowerCase().contains(lowerCaseFilter))
{
return true;
}
return false;
});
});
kategoriaSearch.textProperty().addListener((observableValue,oldValue,newValue) ->
{
filteredData.setPredicate( paisjet ->
{
if(newValue == null || newValue.isEmpty())
{
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if(paisjet.getKategoria().toLowerCase().contains(lowerCaseFilter))
{
return true;
}
return false;
});
});
prodhuesiSearch.textProperty().addListener((observableValue,oldValue,newValue) ->
{
filteredData.setPredicate( paisjet ->
{
if(newValue == null || newValue.isEmpty())
{
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if(paisjet.getProdhuesi().toLowerCase().contains(lowerCaseFilter))
{
return true;
}
return false;
});
});
modeliSearch.textProperty().addListener((observableValue,oldValue,newValue) ->
{
filteredData.setPredicate( paisjet ->
{
if(newValue == null || newValue.isEmpty())
{
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
if(paisjet.getModeli().toLowerCase().contains(lowerCaseFilter))
{
return true;
}
return false;
});
});
SortedList <Paisjet> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(tableView.comparatorProperty());
tableView.setItems(sortedData);
OUTPUT:
Caused by: java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at java.util.AbstractList$Itr.remove(AbstractList.java:374)
at java.util.AbstractList.removeRange(AbstractList.java:571)
at java.util.AbstractList.clear(AbstractList.java:234)
at main.MainWindowController.clearTable(MainWindowController.java:315)
at main.MainWindowController.addToTableFromDatabase(MainWindowController.java:320)
at main.MainWindowController.addToDatabase(MainWindowController.java:309)
... 61 more
clearTable():
public void clearTable()
{
tableView.getItems().clear(); // line 315 at OUTPUT ERROR
}
addToTableFromDatabase():
public void addToTableFromDatabase() throws ClassNotFoundException, SQLException
{
clearTable(); //line 320 at OUTPUT ERROR
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://***.***.**.*:****/*********";
String uname="*****";
String pass="*********";
connect = (Connection) DriverManager.getConnection(url,uname,pass);
Statement statement;
String query = "SELECT * FROM paisjettable" ;
statement = connect.createStatement();
ResultSet rs = statement.executeQuery(query);
while(rs.next())
{
int id = rs.getInt("id");
String prodhuesi = rs.getString("prodhuesi");
String modeli = rs.getString("modeli");
String paisja = rs.getString("paisja");
String pjesa = rs.getString("pjesa");
String infoshtese = rs.getString("infoshtese");
double qmimi = rs.getDouble("qmimi");
double punedore = rs.getDouble("punedore");
double pagesa = rs.getDouble("pagesa");
int sasia = rs.getInt("sasia");
paisjet = new Paisjet(id,prodhuesi,modeli,paisja,pjesa,qmimi,punedore,pagesa,sasia,infoshtese);
data.add(paisjet);
tableView.setItems(data);
}
rs.close();
connect.close();
}
addToDatabase():
public void addToDatabase() throws ClassNotFoundException, SQLException
{
addToDatabaseMethod(count,prodhuesiField.getText(),modeliField.getText(),paisjaField.getText(),pjesaField.getText(),Double.parseDouble(qmimiField.getText()),Double.parseDouble(puneDoreField.getText()),Integer.parseInt(sasiaField.getText()),infoArea.getText());
count++;
prodhuesiField.clear();
modeliField.clear();
paisjaField.clear();
pjesaField.clear();
qmimiField.clear();
puneDoreField.clear();
sasiaField.clear();
infoArea.clear();
addToTableFromDatabase(); // line 309 from OUTPUT ERROR
}
You have set the table view's backing list (items) to a sorted list, which cannot be directly modified (because it is always supposed to be a sorted version of its underlying list). So table.getItems() returns the SortedList and table.getItems().clear() attempts to modify it and throws the exception.
You should modify the underlying list, which you call data in your very first code block. You haven't shown any context for the blocks of code, so it's not clear what the scope of that variable is, but you essentially need data.clear() instead of table.getItems().clear().
(Also, you do not want to call table.setItems(data) in your loop in addToTableFromDatabase, as this will remove the filtering and sorting.)

decision making in java

private Object artikanID(String string) {
try {
DAOTerjemah dao = new DAOTerjemah(ConnectionDB.getConnection()) {};
List<Kata> terjemahan1 = new ArrayList<Kata>();
List<Kata> terjemahan2 = new ArrayList<Kata>();
List<Kata> terjemahan3 = new ArrayList<Kata>();
terjemahan1 = dao.getByIndo(string);
terjemahan2 = dao.getByIndo(string.substring(0,string.length()-1));
terjemahan3 = dao.getByIndo(string.substring(0,string.length()-2));
if (terjemahan1 == null) {
return terjemahan1.get(0).getDayak();
}
else {
return terjemahan2.get(0).getDayak();
}
}catch(Exception e){
return string ;
}
}
there are 3 conditions(terjemahan1,terjemahan2 & terjemahan 3),
how to create the conditions to be executed terjemahan3 ?
With an else, but I'm not entirely sure I understand your logic.
if (terjemahan1 == null) {
return terjemahan1.get(0).getDayak();
}
else if (terjemahan2 == null) {
return terjemahan2.get(0).getDayak();
}
else {
return terjemahan3.get(0).getDayak();
}
I think you probably want the opposite though, so you only call this on variables that are not null. In this case you have to decide which one you want to call in preference if they are all not null. Also you have to decide what to do if all of them are null.
if (terjemahan1 != null) {
return terjemahan1.get(0).getDayak();
}
else if (terjemahan2 != null) {
return terjemahan2.get(0).getDayak();
}
else if (terjemahan3 != null) {
return terjemahan3.get(0).getDayak();
}
else
{
// decide what to do in this condition
}

I can't figure out what's wrong, my logic seems correct

I know that what's messing up is my checkIfEdu method. Everything else is fine because I've tried it without that method. However, it's reading all the data into the InvalidStudentEmails file and its because of that method! i know it, everything else if fine because when I take that method out, it does everything correctly. Please help!!!
import java.util.Scanner;
public class CheckStudentEmail
{
public static void main (String[] args) throws Exception
{
java.io.File filein = new java.io.File("StudentEmailData.txt");
java.io.File fileout1 = new java.io.File("ValidStudentEmails.txt");
java.io.File fileout2 = new java.io.File("InvalidStudentEmails.txt");
Scanner input = new Scanner(filein);
java.io.PrintWriter validOutput = new java.io.PrintWriter(fileout1);
java.io.PrintWriter invalidOutput = new java.io.PrintWriter(fileout2);
writeHeadings(validOutput, invalidOutput);
StudentEmail student = new StudentEmail();
while (input.hasNext())
{
student.readStudentData(input);
if (student.checkPeriod() == true && student.checkAtSymbol() == true
&& student.checkIfEdu() == true)
student.writeEmails(validOutput);
else
student.writeEmails(invalidOutput);
}
input.close();
validOutput.close();
invalidOutput.close();
}
public static void writeHeadings(java.io.PrintWriter validOutput, java.io.PrintWriter invalidOutput)
{
validOutput.printf("%-20s%20s", "Name", "Email Address (Valid)"); validOutput.println(); validOutput.println();
invalidOutput.printf("%-20s%20s", "Name", "Email Address (Invalid)");
invalidOutput.println();
invalidOutput.println();
}
}
Here are my methods
import java.util.Scanner;
public class StudentEmail
{
private String stuName;
private String stuEmail;
StudentEmail()
{}
StudentEmail(String name, String email)
{
stuName = name;
stuEmail = email;
}
public void readStudentData(Scanner input)
{
stuName = input.next();
stuEmail = input.next();
}
public boolean checkPeriod()
{
if (stuEmail.indexOf(".") != -1)
return true;
else
return false;
}
public boolean checkAtSymbol()
{
int atSymbol;
if (stuEmail.indexOf('#') != -1)
{
atSymbol = stuEmail.indexOf('#');
if (stuEmail.indexOf('#', atSymbol+1) != -1)
return false;
else
return true;
}
else
return false;
}
public boolean checkIfEdu()
{
int lengthOfEmail = stuEmail.length();
int position = lengthOfEmail - 3;
String checkWord = stuEmail.substring(position);
if (checkWord == "edu")
return true;
else
return false;
}
public void writeEmails(java.io.PrintWriter output)
{
output.printf("%-20s%20s", stuName, stuEmail);
output.println();
}
}
you compare strings with the equals() method. Using '==' is comparing object references
Did you check what's the checkIfEdu() return?
Another thing is, as I have tried to run your checkIfEdu() it always return false. Because you are comparing it as reference.
To compare String, this should be like this:
if (checkWord.equals("edu")) {

Categories

Resources