Use constructor arguments to evaluate final values depending on each other. Flutter / Dart - constructor

I have a widget that takes a number representing pages allowed to be displayed on the screen.
If the device is weak a bool can be passed that overrides the initial value.
However, since all values are final I must evaluate it in the constructor before the value is set.
class _A extends StatefullWidget{
_A(this.limitPages,
this.pagesToDisplay: limitPages ? 10 : pagesToDisplay,
)
final int pagesToDisplay;
final bool limitPages;
}
I could declare it in the initializer list, but then I can't pass an argument for pagesToDisplay.
class _A extends StatefullWidget{
_A(this.limitPages)
:this.pagesToDisplay: limitPages ? 10 : pagesToDisplay
final int pagesToDisplay;
final bool limitPages;
}
Is there any way to assert a statement in/before the constructor sets the final value?

If you want to use a parameter in the initializer list, the parameter can't be an initializing parameter, and you need to do the initializing in the initializer list instead:
class _A {
_A(bool limitPages, int pagesToDisplay)
: limitPages = limitPages,
pagesToDisplay = limitPages ? 10 : pagesToDisplay;
final int pagesToDisplay;
final bool limitPages;
}

Related

any() vs any(Class.class) Mockito

I am not able to understand why below two tests are not giving the same result.
#Service
public class SomeManager{
private final SomeDependency someDependency;
#Autowired
public SomeManager(SomeDependency someDependency){
this.someDependency = someDependency;
}
public List<returnType> methodToTest(Arg arg){
List<JsonObject> jo = someDependency.search(arg);
return jo.stream().map(returnType::parse).collect(Collectors.toList());
}
}
Test with any(). This Test pass.
#RunWith(SpringJUnit4ClassRunner.class)
public class TestMethodToTest(){
#Test
public void TestMethod(){
SomeDependency someDependency = mock(SomeDependency.class);
List<JsonObject> expected := \some valid list of JsonObject\
// Here I used any() method.
when(someDependency.search(any())).thenReturn(expected);
SomeManager someManager = new SomeManager(someDependency);
List<returnType> actual = someManager.methodToTest(any(Arg.class));
assertArrayEquals(acutal.toArray(), expected.stream().map(returnType::parse).toArray());
}
}
But since search(Arg arg) method of SomeDependency takes parameter of class Arg so I changed above test like this:
#RunWith(SpringJUnit4ClassRunner.class)
public class TestMethodToTest(){
#Test
public void TestMethod(){
SomeDependency someDependency = mock(SomeDependency.class);
List<JsonObject> expected := \some valid list of JsonObject\
// Here I used any(Arg.class) method.
when(someDependency.search(any(Arg.class))).thenReturn(expected);
SomeManager someManager = new SomeManager(someDependency);
List<returnType> actual = someManager.methodToTest(any(Arg.class));
assertArrayEquals(acutal.toArray(), expected.stream().map(returnType::parse).toArray());
}
}
This second test fails with output java.lang.AssertionError: array lengths differed, expected.length=1 actual.length=0.What's the possible reason behind this?
Note: The value expected.length=1 in output depends on what value is provided by the user as valid list of json objects in the test.
The difference stems from the fact that any matches null, while anyClass does not match null. See ArgumentMatchers javadoc:
any() Matches anything, including nulls and varargs.
any​(Class<T> type) Matches any object of given type, excluding nulls.
You are passing null to your method under test here:
List<returnType> actual = someManager.methodToTest(any(Arg.class));
any() returns null which you pass to method under test.
Note that using argument matchers this way is illegal - you should only call them inside calls to when and verify. You should pass a real instance of Arg to method under test.
See Mockito javadoc
Matcher methods like any(), eq() do not return matchers. Internally, they record a matcher on a stack and return a dummy value (usually null). This implementation is due to static type safety imposed by the java compiler. The consequence is that you cannot use any(), eq() methods outside of verified/stubbed method.

Subquery in Select Projections.constructor

Tried to write subqueries in Select clause with Projections like so
queryFactory.query()
.select(
Projections.constructor(
MemberPaymentDTO.class,
JPAExpressions
.select(coopMember)
.from(coopMember)
.where(memberPayment.memberId.eq(coopMember))
.fetchOne(),
JPAExpressions
.select(paymentTransaction.amount)
.from(paymentTransaction)
.where(paymentTransaction.transactionId.eq(memberPayment.paymentTransaction.transactionId))
.fetchOne().floatValue(),
JPAExpressions
.select(collectionTransaction.price.multiply(collectionTransaction.quantity).sum())
.from(collectionTransaction)
.where(collectionTransaction.member.memberId.eq(memberPayment.memberId.memberId))
.where(collectionTransaction.paymentPeriod.paymentPeriodId.eq(paymentPeriodId))
.fetchOne().floatValue()
)
.from(memberPayment);
The DTO is as follows
public class MemberPaymentDTO {
private CoopMember coopMember;
private float payableAmount;
private float collectionsAmount;
public MemberPaymentDTO(CoopMember coopMember, float payableAmount, float collectionsAmount) {
this.coopMember = coopMember;
this.payableAmount = payableAmount;
this.collectionsAmount = collectionsAmount;
}
}
The problem with the above code is Intellij Compiler complains Cannot resolve method 'constructor(java.lang.Class<re.iprocu.model.MemberPaymentDTO>, re.iprocu.model.CoopMember, float, float)
Is it possible for one to add a subquery to select clause and set in a DTO? How?
I'm not very familiar with QueryDSL but the error is quite specific.
There is no constructor for that takes two float values which, in your case come from:
JPAExpressions
.select(paymentTransaction.amount)
.from(paymentTransaction)
.where(paymentTransaction.transactionId.eq(memberPayment.paymentTransaction.transactionId))
.fetchOne().floatValue()
and:
JPAExpressions
.select(paymentTransaction.amount)
.from(paymentTransaction)
.where(paymentTransaction.transactionId.eq(memberPayment.paymentTransaction.transactionId))
.fetchOne().floatValue()
The API http://www.querydsl.com/static/querydsl/4.0.5/apidocs/com/querydsl/core/types/Projections.html states that the possible uses of Projections.constructor are:
constructor(Class<? extends T> type, Expression<?>... exprs)
Create a constructor invocation projection for the given type and expressions
constructor(Class<? extends T> type, Class<?>[] paramTypes, com.google.common.collect.ImmutableList<Expression<?>> exprs)
Create a constructor invocation projection for given type, parameter types and expressions
constructor(Class<? extends T> type, Class<?>[] paramTypes, Expression<?>... exprs)
Create a constructor invocation projection for given type, parameter types and expressions
which means that you are not making the call correctly. Read the documentation more carefully and search for examples, basically you're misusing the API.

Can you combine named parameter with short-hand constructor parameter?

In dart:
Named parameters function like so-
String send(msg, {rate: 'First Class'}) {
return '${msg} was sent via ${rate}';
}
// you can use named parameters if the argument is optional
send("I'm poor", rate:'4th class'); // == "I'm poor was sent via 4th class"
Short-hand constructor parameters function like so-
class Person {
String name;
// parameters prefixed by 'this.' will assign to
// instance variables automatically
Person(this.name);
}
Is there any way to do something like the below?-
class Person{
String name;
String age;
Person({this.name = "defaultName", this.age = "defaultAge"});
}
//So that I could do something like:
var personAlpha = new Person(name: "Jordan");
Thanks,
Code samples borrowed from dartlang synonyms
Update
Yes, the = is allowed in Dart 2 and is now preferred over the : to match optional positional parameters.
Person({this.name = "defaultName", this.age = "defaultAge"});
Old Answer
You just have to use a colon instead of equals
class Person {
String name;
String age;
Person({this.name: "defaultName", this.age: "defaultAge"});
}
I find this still confusing that optional parameters use = to assign defaults but named use :.
Should ask myself.
You can use the "this." syntax with all argument types.
As answered above, you need ':' for default values for named parameters.
You can even use "this." for function typed parameters:
class C {
Function bar;
C({int this.bar(int x) : foo});
static foo(int x) => x + 1;
}
You can also add an required field to skip the default initialization, like so:
class ProcessArguments {
final String logoImagePath;
final String textLogoImagePath;
ProcessArguments({required this.logoImagePath, required this.textLogoImagePath});
}

Defining final in constructor or as a field in java?

public class IdariPersonel extends Personel {
final int sicilNo;
public IdariPersonel(int idno, int sicilNo){}
}
move the sicilNo definition in constructor, int final sicilNo, it accepts that too. What is difference?
when Defining variable in class scope, the other member function could reference the variable, which is, in this case, sicilNo. when Defining variable in constructor, the variable could only be referenced in constructor.

How do I define a System::Decimal literal for use in an attribute, in C++/CLI?

As far as I can tell, there is no literal suffix for defining a compile-time constant of type System::Decimal (compare to the M suffix in C# -- i.e. Decimal d = 100.5M). Furthermore, the following code is rejected by the compiler:
literal System::Decimal myDecimal = 100.5;
If I can't define a decimal literal, how then can I initialize an attribute that requires a decimal as one of its fields? To illustrate, consider the following code:
using namespace System;
public ref class MyConfigElement : ConfigurationElement
{
public:
[ConfigurationProperty("Money", DefaultValue = 500.0, IsRequired = false)]
property Decimal Money { Decimal get(); void set(Decimal value); }
};
The current value of 500.0 is invalid as it compiles to type double, which is then rejected by the runtime as it doesn't match the type of the property (Decimal).
Is it possible to correctly initialize this attribute's default value?
Try DefaultValue = static_cast<Decimal>(500.0).
Use of static_cast is allowed in constant expressions, as long as it does not require a call to a user-defined conversion function.
Failing that, maybe use a global variable which is a constant expression?
const Decimal MyConfigElementMoneyDefault = 500.0;
public ref class MyConfigElement : ConfigurationElement
{
public:
[ConfigurationProperty("Money", DefaultValue = MyConfigElementMoneyDefault, IsRequired = false)]
property Decimal Money { Decimal get(); void set(Decimal value); }
};