I want to recall a value of an edit method declared inside a form from a class main. How can I do it?
[Form]
public class AdvancedCustomerSchedule extends FormRun
{
Sorting sorting;
edit Sorting edtSorting(boolean set, Sorting _sorting)
{
if (set)
{
sorting = _sorting;
}
return sorting;
}
}
and the class:
class AdvancedCustomerScheduleService
{
static void main(Args args)
{
//I want to call the method edtSorting here.
}
}
UPDATE
FormRun callerForm;
if (args.caller() is FormRun)
{
callerForm = args.caller() as FormRun;
if (formHasMethod(callerForm, identifierStr(edtSorting)))
{
str test = callerForm.edtSorting();
info(test);
}
}
For calling methods defined on forms in general you usually use a pattern like the following:
...
FormRun callerForm;
...
if (_args.caller() is FormRun)
{
callerForm = _args.caller();
if (formHasMethod(callerForm, identifierStr(someMethod)))
{
callerForm.someMethod();
}
...
Have a look at class DirPartyContactInfoFormHandler and its static main method for an example.
Related
I've often found myself having to use annoying patterns like:
ClassA extends BaseClass {
static bool is(val) { ... }
}
ClassB extends BaseClass {
static bool is(val) { ... }
}
...
ClassZ extends BaseClass {
static bool is(val) { ... }
}
BaseClass parser(val) {
if(ClassA.is(val)) {
return ClassA(val);
} else if(ClassB.is(val)) {
return ClassB(val);
...
} else if(ClassZ.is(val)) {
return ClassB(val);
}
}
This is very error prone and requires a lot of monotonous code.
I was wondering if there was a way to expedite this process in a non-language specific (or in a language specific for Dart) way that doesn't involve listing all the pattern matchers after they've been defined. I would like to avoid this as I had too many bugs to count caused by forgetting to list one of the already defined class's pattern matcher.
If you want to cut down the arbitrary conditionals in the BaseClass.parser(), you can use a map as follows:
typedef Specification = bool Function(dynamic val);
typedef Factory = BaseClass Function(dynamic val);
class BaseClass
{
static final Map<Specification, Factory> _factoryMap = {
(val) => val == 'Hello': (val) => ClassA(),
(val) => val == 'There': (val) => ClassB(),
};
static BaseClass? parse(dynamic val)
{
for(var key in _factoryMap.keys)
{
if(key(val)) return _factoryMap[key]!.call(val);
}
throw ArgumentError('No valid factory found!');
}
}
class ClassA extends BaseClass
{ }
class ClassB extends BaseClass
{ }
class ClassC extends BaseClass
{ }
In Python, you can extend type and register the subclass's own specification method without manually listing like this. But I am not aware of such runtime meta programming in Dart for the time being. Maybe you can use source_gen in Dart to generate the conditionals automatically.
Combining the check with the construction of the object would help slightly. That would reduce the potential of accidentally using the wrong check and constructor, and it would reduce the amount of code you'd need to add outside of the class definitions:
ClassA extends BaseClass {
/// Attempts to return a [ClassA] if possible.
///
/// Returns `null` if inappropriate.
static ClassA? tryFrom(dynamic val) { ... }
}
ClassB extends BaseClass {
static ClassB? tryFrom(dynamic val) { ... }
}
...
ClassZ extends BaseClass {
static ClassZ? tryFrom(dynamic val) { ... }
}
BaseClass parser(dynamic val) {
BaseClass object = ClassA.tryFrom(val) ??
ClassB.tryFrom(val) ??
... ??
ClassZ.tryFrom(val);
if (object == null) {
// Throw some exception here.
}
return object;
}
from there, you can make parser use a loop:
typedef TryFromFunction = BaseClass? Function(dynamic);
final tryFromFunctions = [
ClassA.tryFrom,
ClassB.tryFrom,
...
ClassZ.tryFrom,
];
BaseClass parser(dynamic val) {
for (var tryFrom in tryFromFunctions) {
var object = tryFrom(val);
if (object != null) {
return object;
}
}
// Throw some exception here.
}
That wouldn't absolve you of the responsibility of updating some other location whenever a new class is added, but:
The work would be minimal.
You maybe could add unit tests to check that the list is updated. For example, if each of ClassA, ClassB, ..., ClassZ is in a separate file easily distinguished by path or filename, then you could have a test that verifies that tryFromFunctions.length matches the number of those files.
For now, I've used a solution that takes from the others listed and adds a twist. Basically, I create a list of matchers like the others but do the work of adding the matcher in the class itself. Basically,
List<BaseClass Function(dynamic)> _matchers = [];
bool addMatcher(bool Function(dynamic) matcher, BaseClass Function(dynamic) factory) {
_matchers.add((val) {
return matcher(val) ? factory(val) : null;
});
return true;
}
class ClassA extends BaseClass {
static final _ = addMatcher(matches, (val) => ClassA(val));
ClassA(val) { ... }
static bool matches(val) { ... }
}
class ClassB extends BaseClass {
static final _ = addMatcher(...);
...
}
...
BaseClass parser(val) {
for (var matcher in _matchers) {
var object = matcher(val);
if (object != null) {
return object;
}
}
// Throw some exception here.
}
The rational behind this is that I can easily verify that the class is being checked. Unfortunately I'm still not sure how to do this automatically since this was just a quick and dirty solution. I may come back to this with an update if I end up implementing source generation or unit tests for automatic generation/verification.
I want to use jmockit to test the static method in Spock, and combine the where tag to achieve different values of each mock to test different business logic. I tried a lot of writing methods, but they all failed. I hope I can get help or suggestions here. Thank you very much
Here is an example of my business code:
public class MyUtils {
public static int staticMethod(int origin) {
return 0;
}
}
public class MyClass {
public void verify(int origin) {
if (MyUtils.staticMethod(origin) == 1) {
System.out.println("1");
}
if (MyUtils.staticMethod(origin) == 2) {
System.out.println("2");
}
...
}
}
This is my Spock test codeļ¼
def "verify"() {
when:
myClass.verify(0)
then:
true
where:
mock | _
mockStatic(1) | _
mockStatic(2) | _
}
def mockStatic(val){
new MockUp<MyUtils>() {
#Mock
public int staticMethod(int origin) {
return val
}
}
}
I know that power can implement such a function, but because our team has been using jmockit, we want to know whether jmockit can implement such multiple different values of mock in Spock?
Put your method call into a closure and evaluate the closure during each iteration:
package de.scrum_master.stackoverflow.q67882559
import mockit.Mock
import mockit.MockUp
import mockit.internal.state.SavePoint
import spock.lang.Requires
import spock.lang.Specification
import spock.lang.Unroll
class StaticMethodJMockitTest extends Specification {
def jMockitSavePoint = new SavePoint()
def cleanup() {
jMockitSavePoint.rollback()
}
#Unroll
def "verify"() {
given:
mockClosure()
MyClass myClass = new MyClass()
when:
myClass.verify(0)
then:
true
where:
mockClosure << [
{ /* no mock */ },
{ mockStatic(1) },
{ mockStatic(2) }
]
}
def mockStatic(val) {
new MockUp<MyUtils>() {
#Mock
int staticMethod(int origin) {
return val
}
}
}
public static class MyUtils {
public static int staticMethod(int origin) {
return 0;
}
}
public static class MyClass {
public void verify(int origin) {
if (MyUtils.staticMethod(origin) == 1) {
System.out.println("1");
}
if (MyUtils.staticMethod(origin) == 2) {
System.out.println("2");
}
}
}
}
If you wish to use data tables, you need to help the parser a bit by explicitly adding it -> inside in the closure, if the closure is in the first column of the data table. You can also use some nice naming for your unrolled iterations:
#Unroll
def "verify #description"() {
given:
mockClosure()
MyClass myClass = new MyClass()
when:
myClass.verify(0)
then:
true
where:
description | mockClosure
"no mock" | { /* no mock */ }
"mock result 1" | { mockStatic(1) }
"mock result 2" | { mockStatic(2) }
}
The reason for creating and rolling back the save point is that JMockit does not play nice with Spock concerning mock lifecycles and the maintainer has no intention to even think about helping. See JMockit issue #668 for more info.
is it possible to call generic types function.
if not is there a different approach to something like this.
someFunction<T>(){
T.anotherFunction();
}
EDIT
MyModel model = NetworkClient.sendRequest<MyModel>(url);
static Future<T> sendRequest<T>(String URL){
//send request
var res = data.toString();
return T.fromJson(json.decode(res))
}
void main() {
someFunction(Foo());
someFunction(Bar());
}
someFunction<T>(T t) {
if (t is Foo)
t.fooFunc();
else if (t is Bar)
t.barFunc();
else
throw Exception("Unknown type: ${t.runtimeType}");
}
class Foo {
void fooFunc() {
print("foo");
}
}
class Bar {
void barFunc() {
print("bar");
}
}
Put your method (lets say MyMethod) in an interface or base class. Lets say MyInterface.
Then use a constraint on your generic type:
someFunction<T extends MyInterface>(T t){
t.MyMethod();
}
Since you cannot have constructors in an interface, your plan with the fromJson might not work out. I don't know your class structure. But you can write generics with specific constraints in mind.
Is there way to overriding method in Dart like JAVA, for example:
public class A {
public void handleLoad() {
}
}
And when overriding:
A a = new A() {
#Override
public void handleLoad() {
// do some code
}
};
No, Dart does not have anonymous classes. You have to create a class that extends A and instantiate it.
No but it much less useful in Dart because you can just reassign function:
typedef void PrintMsg(msg);
class Printer {
PrintMsg foo = (m) => print(m);
}
main() {
Printer p = new Printer()
..foo('Hello') // Hello
..foo = ((String msg) => print(msg.toUpperCase()))
..foo('Hello'); //HELLO
}
However you will need some extra boilerplate to access instance.
Use type Function:
class A {
final Function h
A(this.h);
void handleLoad(String loadResult) { h(loadResult); }
}
Or
class A {
final Function handleLoad;
A(this.handleLoad);
}
A a = new A((String loadResult){
//do smth.
});
I am a little bit confused: can I override a setter / getter but still use the super setter/getter? If yes - how?
Use case:
class A {
void set value(num a) {
// do something smart here
}
}
class B extends A {
void set value(num a) {
// call parent setter and then do something even smarter
}
}
If this is not possible how can one still preserve the API but expand the logic in the new class. The users of the code already use instance.value = ... so I do not want to change it to method call is possible.
Please help:)
You can access to parent with super. :
class B extends A {
void set value(num a) {
super.value = a;
}
}
Only need call super.value = a
class A {
void set value(String value) {
print(value.toUpperCase());
}
}
class B extends A {
void set value(String value) {
super.value = value;
print(value.toLowerCase());
}
}
void main() {
B b = new B();
b.value = "Hello World";
}