Is there a way to return several values in a function return statement (other than returning an object) like we can do in Go (or some other languages)?
For example, in Go we can do:
func vals() (int, int) {
return 3, 7
}
Can this be done in Dart? Something like this:
int, String foo() {
return 42, "foobar";
}
Dart doesn't support multiple return values.
You can return an array,
List foo() {
return [42, "foobar"];
}
or if you want the values be typed use a Tuple class like the package https://pub.dartlang.org/packages/tuple provides.
See also either for a way to return a value or an error.
I'd like to add that one of the main use-cases for multiple return values in Go is error handling which Dart handle's in its own way with Exceptions and failed promises.
Of course this leaves a few other use-cases, so let's see how code looks when using explicit tuples:
import 'package:tuple/tuple.dart';
Tuple2<int, String> demo() {
return new Tuple2(42, "life is good");
}
void main() {
final result = demo();
if (result.item1 > 20) {
print(result.item2);
}
}
Not quite as concise, but it's clean and expressive code. What I like most about it is that it doesn't need to change much once your quick experimental project really takes off and you start adding features and need to add more structure to keep on top of things.
class FormatResult {
bool changed;
String result;
FormatResult(this.changed, this.result);
}
FormatResult powerFormatter(String text) {
bool changed = false;
String result = text;
// secret implementation magic
// ...
return new FormatResult(changed, result);
}
void main() {
String draftCode = "print('Hello World.');";
final reformatted = powerFormatter(draftCode);
if (reformatted.changed) {
// some expensive operation involving servers in the cloud.
}
}
So, yes, it's not much of an improvement over Java, but it works, it is clear, and reasonably efficient for building UIs. And I really like how I can quickly hack things together (sometimes starting on DartPad in a break at work) and then add structure later when I know that the project will live on and grow.
Create a class:
import 'dart:core';
class Tuple<T1, T2> {
final T1 item1;
final T2 item2;
Tuple({
this.item1,
this.item2,
});
factory Tuple.fromJson(Map<String, dynamic> json) {
return Tuple(
item1: json['item1'],
item2: json['item2'],
);
}
}
Call it however you want!
Tuple<double, double>(i1, i2);
or
Tuple<double, double>.fromJson(jsonData);
You can create a class to return multiple values
Ej:
class NewClass {
final int number;
final String text;
NewClass(this.number, this.text);
}
Function that generates the values:
NewClass buildValues() {
return NewClass(42, 'foobar');
}
Print:
void printValues() {
print('${this.buildValues().number} ${this.buildValues().text}');
// 42 foobar
}
The proper way to return multiple values would be to store those values in a class, whether your own custom class or a Tuple. However, defining a separate class for every function is very inconvenient, and using Tuples can be error-prone since the members won't have meaningful names.
Another (admittedly gross and not very Dart-istic) approach is try to mimic the output-parameter approach typically used by C and C++. For example:
class OutputParameter<T> {
T value;
OutputParameter(this.value);
}
void foo(
OutputParameter<int> intOut,
OutputParameter<String>? optionalStringOut,
) {
intOut.value = 42;
optionalStringOut?.value = 'foobar';
}
void main() {
var theInt = OutputParameter(0);
var theString = OutputParameter('');
foo(theInt, theString);
print(theInt.value); // Prints: 42
print(theString.value); // Prints: foobar
}
It certainly can be a bit inconvenient for callers to have to use variable.value everywhere, but in some cases it might be worth the trade-off.
Dart is finalizing records, a fancier tuple essentially.
Should be in a stable release a month from the time of writing.
I'll try to update, it's already available with experiments flags.
you can use dartz package for Returning multiple data types
https://www.youtube.com/watch?v=8yMXUC4W1cc&t=110s
you can use Set<Object> for returning multiple values,
Set<object> foo() {
return {'my string',0}
}
print(foo().first) //prints 'my string'
print(foo().last) //prints 0
In this type of situation in Dart, an easy solution could return a list then accessing the returned list as per your requirement. You can access the specific value by the index or the whole list by a simple for loop.
List func() {
return [false, 30, "Ashraful"];
}
void main() {
final list = func();
// to access specific list item
var item = list[2];
// to check runtime type
print(item.runtimeType);
// to access the whole list
for(int i=0; i<list.length; i++) {
print(list[i]);
}
}
Related
I have some code that returns Mono<List<UserObject>>. The first thing I want to do is check the List is not empty, and if it is, throw a NoUsersFoundException. My code looks like this:
IUserDao.java
Mono<List<UserAccount>> getUserProfiles(final Set<UserQueryFilter> filters,
final Set<String> attributes);
GetUserAccount.java
public Mono<UserAccount> doGetUserAccount() {
return userDao.getUserProfiles(filters, attributes)
.map(list -> {
if (CollectionUtils.isEmpty(list)) {
throw new NoUsersFoundException();
}
return list;
})
.map(this::removePermissions)
.map(this::removeDuplicates);
}
I want to write a unit test that will test that the NoUsersFoundException is thrown when userDao.getUserProfiles(filters, attributes) returns an empty list. When I use Mockito#when with a .thenReturn(), the test will, as expected, return immediately once userDao.getUserProfiles(...) is called without continuing the flow into the .map() where the list is checked and exception thrown.
#Mock
private IUserDao userDao;
private UserPolicies userPolicies;
#BeforeEach
public void init() {
userPolicies = new UserPolicies(Set.of("XYZ", USER_AFF, "123"),
Set.of(TestUserConstants.ID, TestUserConstants.SUBSCRIPTION_LEVEL));
}
#Test
void shouldThrowExceptionIfNoUsersFound() {
final Set<UserFilter> filters = new UserFilterBuilder().withId(ID)
.withSubscription(PREMIUM)
.build();
when(userDao.getUserProfiles(filters, userPolicies.getUserAttributeIds()))
.thenReturn(Mono.just(Collections.emptyList()));
testClass = new GetUserAccount(userDao,
userPolicies,
filters,
userPolicies.getUserAttributeIds());
assertThatThrownBy(() -> testClass.doGetUserAccount()).isInstanceOf(NoUsersFoundException.class);
}
I have tried .thenAnswer() but it essentially does the same thing as the method called is not a void:
userDao.getUserProfiles(filters, userPolicies.getUserAttributeIds()))
.thenAnswer((Answer<Mono<List>>) invocationOnMock -> Mono.just(Collections.emptyList()));
I can't see how using reactor.test.StepVerifier would work for this case.
i dont really understand what you are asking for, but we commonly dont "throw" exceptions in reactor. We return a Mono#error downstream, and different operators will react accordingly as the error travels downstream.
public Mono<List<Foobar> fooBar(filters, attributes) {
return daoObject.getUserProfiles(filters, attributes)
.map(list -> {
if (CollectionUtils.isEmpty(list)) {
// Return a mono#error
return Mono.error( ... );
}
return list;
})
}
And then test using the step verifier. With either expectNext or expectError.
// Happy case
StepVerifier.create(
fooBar(filters, attributes))
.expectNext( ... )
.verify();
// Sad case
StepVerifier.create(
fooBar(filters, attributes))
.expectError( ... )
.verify();
I have the following inputs:
A CSV File
An array of grammar rules. The grammar rules are
basically metadata that tells me what which each column datatype
should be.
The output would return back to me a list of records that had any errors. So if column should be a date but I'm given the wrong format. I would return those rows.
The csv file would be something like this:
first_name,last_name,dob,age,
john,doe,2001/05/02
mary,jane,1968/04/01
Metadata:
column:first_name
type:string
column:dob
type:date
I was wondering if the strategy pattern would be the right choice. I was thinking of injecting the proper grammar (metadata) depending upon the file. I have multiple files I want to validate.
This problem needs the Validation Handlers (for your grammar rule). Looking at lower complexity level and expected extensions, I do not feel the need of any specific design pattern. I would suggest following simple OO approach. Alternatively depending upon expected dynamic behavior, COR can be incorporated by putting each Concrete Handler in a chain (COR). Pass each token in a chain so as to give opportunity to handlers in a chain till it gets handled.
public class Extractor {
public static void main(String[] args) {
// PREPARE TEMP_MAP_HANDLERS<Type,Handler>
Map<String, Handler> handlers = new HashMap<>();
handlers.put("FIRST_NAME",new NAMEHandler());
handlers.put("LAST_NAME",new NAMEHandler());
handlers.put("DOB",new DOBHandler());
handlers.put("AGE",new AGEHandler());
// READ THE HEADER
String header = "first_name,last_name,dob,age";// SAMPLE READ HEADER
// PREPARE LOOKUP<COL_INDEX, TYPE_HANDLER>
Map<Integer, Handler> metaHandlers = new HashMap<>();
String[] headerTokens = header.split(",");
for (int i = 0; i < headerTokens.length; i++) {
metaHandlers.put(i, handlers.get(headerTokens[i].toUpperCase()));
}
// DONE WITH TEMP HANDLER LOOKUP
// READ ACTUAL ROWS
// FOR EACH ROW IN FILE
String row = "joh*n,doe,2001/05/02";
String[] rowTokens = row.split(",");
for (int i = 0; i < rowTokens.length;i++) {
System.out.println(rowTokens[i]);
Handler handler = metaHandlers.get(i);
if (!handler.validate(rowTokens[i])){
// REPORT WRONG DATA
System.out.println("Wrong Token" + rowTokens[i]);
}
}
}
}
abstract class Handler {
abstract boolean validate (String field);
}
class NAMEHandler extends Handler{
#Override
boolean validate(String field) {
// Arbitrary rule - name should not contain *
return !field.contains("*");
}
}
class DOBHandler extends Handler{
#Override
boolean validate(String field) {
// Arbitrary rule - contains /
return field.contains("/");
}
}
class AGEHandler extends Handler{
#Override
boolean validate(String field) {
// TODO validate AGE
return true;
}
}
I am using getter/setter accessors in TypeScript. As it is not possible to have the same name for a variable and method, I started to prefix the variable with a lower dash, as is done in many examples:
private _major: number;
get major(): number {
return this._major;
}
set major(major: number) {
this._major = major;
}
Now when I use the JSON.stringify() method to convert the object into a JSON string, it will use the variable name as the key: _major.
As I don't want the JSON file to have all keys prefixed with a lower dash, is there any possibility to make TypeScript use the name of the getter method, if available? Or are there any other ways to use the getter/setter methods but still produce a clean JSON output?
I know that there are ways to manually modify the JSON keys before they are written to the string output. I am curious if there is simpler solution though.
Here is a JSFiddle which demonstrates the current behaviour.
No, you can't have JSON.stringify using the getter/setter name instead of the property name.
But you can do something like this:
class Version {
private _major: number;
get major(): number {
return this._major;
}
set major(major: number) {
this._major = major;
}
toJsonString(): string {
let json = JSON.stringify(this);
Object.keys(this).filter(key => key[0] === "_").forEach(key => {
json = json.replace(key, key.substring(1));
});
return json;
}
}
let version = new Version();
version.major = 2;
console.log(version.toJsonString()); // {"major":2}
based on #Jan-Aagaard solution I have tested this one
public toJSON(): string {
let obj = Object.assign(this);
let keys = Object.keys(this.constructor.prototype);
obj.toJSON = undefined;
return JSON.stringify(obj, keys);
}
in order to use the toJSON method
I think iterating through the properties and string manipulating is dangerous. I would do using the prototype of the object itself, something like this:
public static toJSONString() : string {
return JSON.stringify(this, Object.keys(this.constructor.prototype)); // this is version class
}
I've written a small library ts-typed, which generate getter/setter for runtime typing purpose. I've faced the same problem when using JSON.stringify(). So i've solved it by adding a kind of serializer, and proposing to implement a kind of toString (in Java) buy calling it toJSON.
Here is an example:
import { TypedSerializer } from 'ts-typed';
export class RuntimeTypedClass {
private _major: number;
get major(): number {
return this._major;
}
set major(major: number) {
this._major = major;
}
/**
* toString equivalent, allows you to remove the _ prefix from props.
*
*/
toJSON(): RuntimeTypedClass {
return TypedSerializer.serialize(this);
}
}
A new answer to an old question. For situations where there is no private field for a getter/setter, or where the private field name is different to the getter/setter, we can use the Object.getOwnPropertyDescriptors to find the get methods from the prototype.
https://stackoverflow.com/a/60400835/2325676
We add the toJSON function here so that it works with JSON.stringify as mentioned by other posters. This means we can't call JSON.stringify() within toJSON as it will cause an infinite loop so we clone using Object.assign(...)
I also removed the _private fields as a tidyup measure. You may want to remove other fields you don't want to incude in the JSON.
public toJSON(): any {
//Shallow clone
let clone: any = Object.assign({}, this);
//Find the getter method descriptors
//Get methods are on the prototype, not the instance
const descriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf(this))
//Check to see if each descriptior is a get method
Object.keys(descriptors).forEach(key => {
if (descriptors[key] && descriptors[key].get) {
//Copy the result of each getter method onto the clone as a field
delete clone[key];
clone[key] = this[key]; //Call the getter
}
});
//Remove any left over private fields starting with '_'
Object.keys(clone).forEach(key => {
if (key.indexOf('_') == 0) {
delete clone[key];
}
});
//toJSON requires that we return an object
return clone;
}
Isn't dynamic but it work
export class MyClass{
text: string
get html() {
return this.text.toString().split("\n").map(e => `<p>${e}</p>`).join('');
}
toJson(): string {
return JSON.stringify({ ...this, html: this.html })
}
}
In calling
console.log(myClassObject.toJson())
That is, I'm trying to invoke one constructor from another, and then construct further. I can't figure out from documentation if it can be done.
Here's a contrived example, in case it helps:
class Chipmunk {
Chipmunk.named(this.name);
Chipmunk.famous() {
this.named('Chip'); // <-- What, if anything, goes here?
this.fame = 1000;
}
}
var chip = new Chimpmunk.famous();
There are two possible ways to do this:
class Chipmunk {
String name;
int fame;
Chipmunk.named(this.name, [this.fame]);
Chipmunk.famous1() : this.named('Chip', 1000);
factory Chipmunk.famous2() {
var result = new Chipmunk.named('Chip');
result.fame = 1000;
return result;
}
}
Chipmunk.famous1() is a redirective constructor. You can't assign properties in this one, so the constructor you are calling has to allow all the properties you want to set. That's why I added fame as an optional parameter. In this case you could make name and fame final.
Chipmunk.famous2() is a factory constructor and can just create the instance you want. In this case, fame couldn't be final (obviously it could be if you used the fame parameter in the named constructor).
The first variant would probably be the preferable one for your use case.
This is the documentation in the language spec:
A generative constructor consists of a constructor name, a constructor parameter list, and either a redirect clause or an initializer list and an optional body.
https://dart.dev/docs/spec/latest/dart-language-specification.html#h.flm5xvbwhs6u
The init pattern could be used here : the constructor just calls an init function defined in the class.
It can have an advantage over the redirective constructor in some cases, i can think of two right now :
- if you are saving/restoring the state of your object (in this case, you just write once the restore part).
- if you are pooling (recycling) your objects and need to 'refresh' them when you revive them.
class Chipmunk {
Chipmunk.named(string newName) { nameInit(newName) };
Chipmunk.famous() {
famousInit();
}
nameInit(string newName) {
name = newName ;
}
famousInit() {
nameInit('Chip');
fame = 1000;
}
string name;
num fame;
}
var chip = new Chimpmunk.famous();
Another way is to use a static method that returns an instance of the same class.
It's technically not a constructor and it's not recommended by the Dart Linter, but it can help in situations where you need to choose which constructor to call depending on the value of an argument.
class Chipmunk {
Chipmunk.named(this.name, [this.fame]);
// ignore: prefer_constructors_over_static_methods
static Chipmunk withFame(int fame) {
if (fame > 100) {
return Chipmunk.named('Super Famous Chip', fame);
}
return Chipmunk.named('Chip', fame);
}
String name;
int? fame;
}
var superFamousChip = Chipmunk.withFame(110);
How would I write a simple LINQ to SQL extension method called "IsActive" which would contain a few basic criteria checks of a few different fields, so that I could reuse this "IsActive" logic all over the place without duplicating the logic.
For example, I would like to be able to do something like this:
return db.Listings.Where(x => x.IsActive())
And IsActive would be something like:
public bool IsActive(Listing SomeListing)
{
if(SomeListing.Approved==true && SomeListing.Deleted==false)
return true;
else
return false;
}
Otherwise, I am going to have to duplicate the same old where criteria in a million different queries right throughout my system.
Note: method must render in SQL..
Good question, there is a clear need to be able to define a re-useable filtering expression to avoid redundantly specifying logic in disparate queries.
This method will generate a filter you can pass to the Where method.
public Expression<Func<Listing, bool>> GetActiveFilter()
{
return someListing => someListing.Approved && !someListing.Deleted;
}
Then later, call it by:
Expression<Func<Filter, bool>> filter = GetActiveFilter()
return db.Listings.Where(filter);
Since an Expression<Func<T, bool>> is used, there will be no problem translating to sql.
Here's an extra way to do this:
public static IQueryable<Filter> FilterToActive(this IQueryable<Filter> source)
{
var filter = GetActiveFilter()
return source.Where(filter);
}
Then later,
return db.Listings.FilterToActive();
You can use a partial class to achieve this.
In a new file place the following:
namespace Namespace.Of.Your.Linq.Classes
{
public partial class Listing
{
public bool IsActive()
{
if(this.Approved==true && this.Deleted==false)
return true;
else
return false;
}
}
}
Since the Listing object (x in your lambda) is just an object, and Linq to SQL defines the generated classes as partial, you can add functionality (properties, methods, etc) to the generated classes using partial classes.
I don't believe the above will be rendered into the SQL query. If you want to do all the logic in the SQL Query, I would recommend making a method that calls the where method and just calling that when necessary.
EDIT
Example:
public static class DataManager
{
public static IEnumerable<Listing> GetActiveListings()
{
using (MyLinqToSqlDataContext ctx = new MyLinqToSqlDataContext())
{
return ctx.Listings.Where(x => x.Approved && !x.Deleted);
}
}
}
Now, whenever you want to get all the Active Listings, just call DataManager.GetActiveListings()
public static class ExtensionMethods
{
public static bool IsActive( this Listing SomeListing)
{
if(SomeListing.Approved==true && SomeListing.Deleted==false)
return true;
else
return false;
}
}
Late to the party here, but yet another way to do it that I use is:
public static IQueryable<Listing> GetActiveListings(IQueryable<Listing> listings)
{
return listings.Where(x => x.Approved && !x.Deleted);
}
and then
var activeListings = GetActiveListings(ctx.Listings);