My code is as below
private fun validateInput(): Boolean {
if (etReportRow1.text.toString() == ""
|| etReportRow2.text.toString() == ""
|| etReportRow3.text.toString() == "")
return false
else
return true
}
The compiler tell me
Redundant 'if' statement less... (Ctrl+F1) This inspection reports if
statements which can be simplified to single statements. For example:
if (foo()) { return true } else { return false } can be
simplified to return foo().
Won't the suggested code go into loop?
All statments in the form:
if(condition){
return false
} else {
return true
}
can be simplified into:
return !condition
So in your case it would lead to:
return !(etReportRow1.text.toString() == "" || etReportRow2.text.toString() == "" || etReportRow3.text.toString() == "")
Or:
return
etReportRow1.text.toString().isNotEmpty() &&
etReportRow2.text.toString().isNotEmpty() &&
etReportRow3.text.toString().isNotEmpty()
Note: the isNotEmpty() is an extension method:
public inline fun CharSequence.isNotEmpty(): Boolean = length > 0
To avoid duplicate code you could also use a Sequence:
public fun validateInput() = sequenceOf(etReportRow1, etReportRow2, etReportRow3)
.map { it.text.toString() }
.all { it.isNotEmpty() }
Because a boolean expression evaluates to a boolean value, you can simply return the result of the expression itself, without having to explicitly return true or false.
You can further simplify things using the following single-expression function:
private fun validateInput() = etReportRow1.text.toString() != "" &&
etReportRow2.text.toString() != "" &&
etReportRow3.text.toString() != ""
try
return !(etReportRow1.text.toString() == "" || etReportRow2.text.toString() == "" || etReportRow3.text.toString() == "")
I think this should work:
private fun validateInput() = !(etReportRow1.text.toString.isEmpty()
|| etReportRow2.text.toString().isEmpty()
|| etReportRow3.text.toString().isEmpty() )
Even more concise:
public fun validateInput() = setOf(
etReportRow1, etReportRow2, etReportRow3
).none {
"${it.text}".isEmpty()
}
Related
I am fairly new to writing Junits in such detail.
The method
returns boolean true/false
accepts two params of same non-primitive type.
This method does a whole lot of validations by comparing the two instances of the similar type using if else conditions.
And few more validations while iterating through the collection based fields of the params .
I tried writing the base scenario, but unclear as to how to do it for the underlying if_conditons. especially with regard to mocking the data.
What I tried and aware: There are lots of methods under AssertClass which I can use to validate, however for this method that return boolean based on quite a bunch of conditions, how do I write? do I have to write individual asserts for each condition under the #Test annotated method?
below is my code :
public boolean checkEligblity(A newversion, A currentversion) {
if (currentversion.getPurchaseOrders().isEmpty())
return true;
if (currentversion.getReceiptNotice() != newversion.getReceiptNotice()
|| currentversion.getSizeType() != newversion.getSizeType()
|| currentversion.getNumInPrices() != newversion.getNumInPrices())
return true;
boolean storeM = newversion.getReceiptNotice() == PASSED;
if (currentversion.getOrderInfo() != newversion.getOrderInfo()) {
if (storeM || containsCustomerString(currentversion.getOrderInfo())
|| containsCustomerString(newversion.getOrderInfo()))
return true;
}
List<PurchaseOrders> newVersionPurchaseOrders = newversion.getPurchaseOrders();
List<PurchaseOrders> currentVersionPurchaseOrders = currentversion.getPurchaseOrders();
for (Iterator<PurchaseOrders> newPOIterator = newVersionPurchaseOrders.iterator(); newPOIterator.hasNext();) {
PurchaseOrders newPO = newPOIterator.next();
for (Iterator<PurchaseOrders> currentPOIterator = currentVersionPurchaseOrders.iterator(); currentPOIterator
.hasNext();) {
PurchaseOrders currentPO = currentPOIterator.next();
if (newPO.getSku() == currentPO.getSku()
&& newPO.getSkuId() == currentPO.getSkuId()
&& newPO.getOrgin() == currentPO.getOrgin()
&& newPO.getTarget() == currentPO.getTarget()
&& newPO.getShippingDate()== currentPO.getDepratureDate()) {
if (currentPO.getStatusCode().equals(newPO.getStatusCode())
&& currentPO.getItemsInQty().equals(newPO.getItemsInQty())
&& currentPO.getVendorId().equals(newPO.getVendorId())
&& currentPO.getCodeInd().equals(newPO.getCodeInd())
&& currentPO.getPriceType().charAt(0) == newPO.getPriceType().charAt(0)) {
boolean matchingFound = true;
if (storeM && currentPO.getInbound() != newPO.getInbound()) {
matchingFound = false;
}
if (matchingFound) {
newPOIterator.remove();
currentPOIterator.remove();
break;
}
}
}
}
}
if (!newVersionPurchaseOrders.isEmpty() || !currentVersionPurchaseOrders.isEmpty()) {
return true;
}
return false;
}
private boolean containsCustomerString(String ticketingInfo) {
if (orderInfo == null)
return false;
if (orderInfo.startsWith(PASS))
return true;
return false;
}
I want to make a code to assign logic input for my sheet. I use IF to make it. My code ran successfully but the logic didn't work. I have checked it many times, but I couldn't find something wrong. Can you help me with this? I'm stuck. Please review my example sheet and my script for more information. Thank you! https://docs.google.com/spreadsheets/d/1eV2SZ45Gs6jISgh_p6RIx-rfOGlHUM6vF114Mgf6c58/edit#gid=0
function logic(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var activeCell = ss.getActiveCell();
if (activeCell.getColumn() == 1 && activeCell.getRow() > 1 && ss.getSheetName() == "mama" && activeCell.getValue() == "Yes") {
activeCell.offset(0,1).clearContent();
activeCell.offset(0,1).setValue("1");
} if (activeCell.getColumn() == 1 && activeCell.getRow() > 1 && ss.getSheetName() == "mama" && activeCell.getValue() == "Hafl") {
activeCell.offset(0,1).clearContent();
activeCell.offset(0,1).setValue("1/2");
} if (activeCell.getColumn() == 1 && activeCell.getRow() > 1 && ss.getSheetName() == "mama" && activeCell.getValue() == "No") {
activeCell.offset(0,1).clearContent();
activeCell.offset(0,1).setValue(0);
}
}
You can simplify your code this way.
(Note that I use the const variable declaration instead of var (ES6 - V8 engine))
function logic() {
const ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
const activeCell = ss.getActiveCell();
const activeCellValue = activeCell.getValue();
if (activeCell.getColumn() === 1 && activeCell.getRow() > 1 && ss.getSheetName() == "mama") {
switch(activeCellValue) {
case 'Yes':
activeCell.offset(0, 1).clearContent();
activeCell.offset(0, 1).setValue('1');
break;
case 'Half':
activeCell.offset(0, 1).clearContent();
activeCell.offset(0, 1).setValue('1/2');
break;
case 'No':
activeCell.offset(0, 1).clearContent();
activeCell.offset(0, 1).setValue('0');
break;
}
}
}
This way you only have to test the common conditions once.
Using the Switch function clearly shows the behavior of the script depending on the input value 'ActiveCellValue'.
If you need that only one action resolve per run, you need to use else if to chain the statements:
if(statement){
Action
}else if (statement2){
Action2
}else if...
I have a method inside a class that is not returning a value.
These are the relevant variables that are being used in the method, they are in the private part of the class
int hieght_of_plane = 0 ;
int position_of_plane = 0 ;
bool landing_gear = true ;
bool is_flying = false ;
bool is_alive = true ;
And here is the method that is not returning true or false, it is in the public section of the class.
bool check_for_alive()
{
if (is_flying == false)
{
return true ;
}
if (is_flying == true)
{
if (hieght_of_plane <= 3)
{
if (landing_gear == false)
{
is_alive = false ;
return false ;
}
else if (landing_gear == true)
{
return true ;
}
}
}
}
The method seems to not do anything and then I get the no return value error
warning: control reaches end of non-void function [-Wreturn-type]
I assume that it should return false in this instance because is_flying = false so the method should return false, but it isn't.
The case that falls through is when flying == true and hieght_of_plane is greater than 3.
if (is_flying == true)
{
if (hieght_of_plane <= 3)
{
The 2nd if statement does not have an else, which is necessary for returning a value.
Edit 1: An else clause
The else clause should be used for the "not" case of the if statement.
For example:
if (is_flying == false)
{
return true;
}
else // This means is_flying == true
{
if (hieght_of_plane <= 3)
{
if (landing_gear == false)
{
is_alive = false ;
return false ;
}
else // implies landing_gear == true
{
return true ;
}
else // implies hieght > 3
{
return ????
}
}
You could also reduce this down to one Boolean expression.
Edit 2: Simplification
There are two functionalities here: Return true/false for a combination of conditions and to set is_alive based on a condition.
Let's say that one condition is true, all others is false.
bool check_for_alive()
{
if (is_flying && (height_of_plane <= 3) && (landing_gear == false))
{
is_alive = false;
}
return is_flying && (height_of_plane <= 3) && (landing_gear == true);
}
Note: The above does not consider the case of `(height_of_plane > 3), since this is not specified in the OP's original code.
the control flow would reach the end of the function when is_flying is true and hieght_of_plane is > 3. you MUST return something there.
and one more thing is the you don't always need to check that if (something == true) instead if (something) would enough, I've pointed some more below the code.
bool check_for_alive() {
if (!is_flying)
return true;
// if you reached here is_flying is true no need to check
if (hieght_of_plane <= 3) {
if (!landing_gear) {
is_alive = false;
return false;
} else {
// if you're here landing_gear is false no need to check
return true;
}
}
// what to return if we reach here? yes the control flow could reach
// here when is_flying is true and hieght_of_plane is > 3
// you must return something here.
}
I have this code:
val leftEnoughRoom = if(fx1 > eachSideBesidesFace){
true
}else{
false
}
And get the warning:
This inspection reports if statements which can be simplified to single statements. For example:
if (foo()) {
return true
} else {
return false
}
can be simplified to return foo().
What does it want me to do? When I do:
if(fx1 > eachSideBesidesFace){
val leftEnoughRoom = true
}else{
val leftEnoughRoom = false
}
Then leftEnoughRoom is not reachable below any more
fx1 > eachSideBesidesFace
is a boolean statement. You don't need the if-else:
val leftEnoughRoom = fx1 > eachSideBesidesFace
As a sidenote, you can click the underlined expression, hit Alt+Enter and then have Android Studio automatically optimize the code.
I want to simplify this if statement to be more 'human readable'
void NewFan::checkData()
{
if(!ui->firstNameEdit->text().isEmpty() && !ui->lastNameEdit->text().isEmpty() &&
(!ui->peselEdit->text().isEmpty() && (ui->birthDateEdit->text().size()==10 &&
!ui->townEdit->text().isEmpty() && !ui->addressEdit->text().isEmpty()) ||
ui->peselEdit->text().size()==11))
ui->addButton->setEnabled(true);
else
ui->addButton->setDisabled(true);
}
Is there any other way than rewrite it to nested if statement?
If human readability is what your after, you should break down your complex conditional into easy-to-digest bits
void NewFan::checkData()
{
bool firstname_ok = !ui->firstNameEdit->text().isEmpty();
bool lastname_ok = !ui->lastNameEdit->text().isEmpty();
bool birthdate_ok = ui->birthDateEdit->text().size() == 10;
bool town_ok = !ui->townEdit->text().isEmpty();
bool address_ok = !ui->addressEdit->text().isEmpty();
bool pesel_ok = ui->peselEdit->text().size() == 11;
bool pesel_alt_ok = birthdate_ok && town_ok && address_ok;
bool can_add = firstname_ok && lastname_ok && (pesel_ok || pesel_alt_ok);
ui->addButton->setEnabled(can_add);
}
You can group some of the non-empty cases perhaps
inline bool notEmpty(Edit const* e)
{
return !e->text()->isEmpty();
}
template<typename... Args>
bool notEmpty(Edit const* e, Args const*... args)
{
return notEmpty(e) && notEmpty(args...);
}
if (notEmpty(foo, bar, baz))
//
split it up in several parts:
void NewFan::checkData()
{
bool valid = true;
if(ui->firstNameEdit->text().isEmpty())
valid=false;
if(ui->lastNameEdit->text().isEmpty())
valid=false;
if(!ui->peselEdit->text().isEmpty())
valid=false;
if((ui->birthDateEdit->text().size()==10 &&
!ui->townEdit->text().isEmpty() && !ui->addressEdit->text().isEmpty()) ||
ui->peselEdit->text().size()==11)
valid=false;
ui->addButton->setEnabled(valid);
}
This also allows you to build an error message as you go through the validation.
If you want to make it more readable I would use nested ifs.
But, if you want to keep everything in one single if then I don't see any apparent redundancy in the conditions to make it shorter.
If you want to make it more readable you can use variables instead of the function calls.