Convert kj::Promise<kj::Exception> to kj::Promise<void> - promise

I can return a kj::Exception where a kj::Promise is expected, like so:
kj::Promise<void> someFunc() {
return KJ_EXCEPTION(FAILED, "some description");
}
But what if I end up having a kj::Promise<kj::Exception> in a place where I don't have a waitScope? For instance:
kj::Promise<void> someFunc(kj::Promise<void> somePromise) {
return somePromise.then([]() {
return KJ_EXCEPTION(FAILED, "some description");
});
}
There my compiler complains that there is no valid conversion between kj::Promise<kj::Exception> and kj::Promise<void>.
Is there a way around that?

I'm a little surprised that I didn't prohibit Promise<Exception> in the first place; using such a construction likely leads to a lot of problems.
You can avoid it in your code by explicitly declaring the return type of the lambda to be Promise<void>, i.e.:
return somePromise.then([]() -> kj::Promise<void> {

Related

Project Reactor: Obtain Size of List Contained Within a Mono

I'm trying to do something again here in project reactor that I'm sure is reeeeeal simple for any of you project reactor gurus out there!
I've been searching and scratching around with this one for a while now, and feel I'm once again hitting a wall with this stuff.
All I'm trying to do is determine if a List of objects contained within a Mono is empty or not.
This is what I have so far:
private Mono<Boolean> isLastCardForAccount(String accountId) {
return cardService.getAccountCards(accountId)
.hasElement();
}
I'm thinking the above might work, but I'm having difficulty figuring out how to extract/access the 'Boolean' contained within the returned Mono. I think I have to use 'subscribe' somehow right?
I've mucked around with this stuff for a while now, but still no luck.
Here is how 'getAccountCards' is defined:
public Mono<List<Card>> getAccountCards(final String accountId) {
return cardCrudRepository.getCardsByAccountId(accountId)
.collectList();
}
From CardCrudRepository:
// #Query("SELECT * FROM card WHERE account_id = :accountId") <-Not sure if I need this
Flux<Card> getCardsByAccountId(String accountId);
And lastly, how I'm using 'isLastCardForAccount':
public Mono<Void> updateCardStatus(String accountId, String cardId, String cardStatus) {
return accountService.getAccount(accountId)
.map(Account::getClientId)
.map(clientId -> createUpdateCardStatusServiceRequestData(clientId, cardId, cardStatus))
.flatMap(requestData -> cartaClient.updateCardStatus(requestData)
.then(Mono.defer(() -> isCardBeingCancelled(cardStatus) ? allCardsCancelledForAccount(accountId) ? removeAccount(accountId) :
(isLostOrStolen(cardStatus) ? replaceCard(cardId, cardStatus).flatMap(this::updateCardNumber) : Mono.empty()) : Mono.empty())));
}
As always, any and all help and insight is tremendously appreciated!
I am not sure if this would resolve the issue but this way you can try to write your logic
return accountService.getAccount(accountId)
.map(Account::getClientId)
.map(clientId -> createUpdateCardStatusServiceRequestData(clientId, cardId, cardStatus))
.flatMap(requestData -> cartaClient.updateCardStatus(requestData)
.then(Mono.defer(() ->
Mono.zip(
Mono.just(isCardBeingCancelled(cardStatus)),
isLastCardForAccount(accountId),
Mono.just( isLostOrStolen(cardStatus) )
)
.map(tuple -> {
WRITE YOUR IF ELSE LOGIC
})
The idea is to use zip and then use the tuple for writing logic. The Tuple would be of type Tuple3 of <Boolean, Boolean ,Boolean>. I made the assumption that isLostOrStolen(cardStatus) returns Boolean.
One way of doing that is by using filterWhen operator like this:
.then(Mono.defer(() -> {
if (isCardBeingCancelled(cardStatus)) {
return Mono.just(accountId)
.filterWhen(this::allCardsCancelledForAccount)
.flatMap(this::removeAccount);
} else if (isLostOrStolen(cardStatus)) {
return replaceCard(cardId, cardStatus).flatMap(this::updateCardNumber);
}
return Mono.empty();
}))
You can use filterWhen in the case of asynchronous filtering. Check this section of Which operator do I need? reference and this How to filter Flux asynchronously.
As a side note, this is not going to work as you expect:
private Mono<Boolean> isLastCardForAccount(String accountId) {
return cardService.getAccountCards(accountId)
.hasElement();
}
public Mono<List<Card>> getAccountCards(final String accountId) {
return cardCrudRepository.getCardsByAccountId(accountId)
.collectList();
}
The collectList() will emit an empty List if there is no card. I'd use exists query instead:
public Mono<Boolean> isLastCardForAccount(final String accountId) {
return cardCrudRepository.existsByAccountId(accountId);
}

rxjs BehaviorSubject that emits via distinctUntilChanged

I'm wanting to implement an Observable / Subject with 3 particular attributes
Remember last emitted value and be able to surface it via a getter (BehaviorSubject)
Only emit when value changes
It must have a strong type such that the getter is known to be available by a consumer (aka. BehaviorSubject.getValue())
I'm thinking of just extending BehaviorSubject but want to make sure I'm not introducing any potential gotchas based on my novice understanding.
export class DistinctUntilChangedBehaviorSubject<T, TValue> extends BehaviorSubject<T> {
constructor(
initialValue: T,
private _distinctKeySelector?: (value: T) => TValue,
private _comparer?: _Comparer<TValue, boolean>
) {
super(initialValue);
}
public subscribe() {
// I'm particularly interested in knowing if this has any gotchas.
// Mostly things like creating subscriptions that don't get disposed as expected.
return super.distinctUntilChanged(
this._distinctKeySelector,
this._comparer
).subscribe.apply(this, arguments);
}
}
So 2 questions:
Does this seem like a reasonable approach / are there any gotchas here?
Is there another preferred way of doing this?
I do not know really why, but I tend to prefer composition over extension.
So I would do something along these lines
import {BehaviorSubject} from 'rxjs';
export class BehaviourSubjectAugmented<T> {
bs: BehaviorSubject<T>;
constructor(initialValue: T, private comparer: (p: T, q: T) => boolean) {
this.bs = new BehaviorSubject(initialValue);
}
getValue() {
return this.bs.getValue();
}
asObservable() {
return this.bs.asObservable()
.distinctUntilChanged(this.comparer);
}
complete() {
return this.bs.complete();
}
next(value: T) {
return this.bs.next(value);
}
}
Turns out my original idea causes a call stack exceeded issue. I'm assuming that distinctUntilChanged must call subscribe internally thus causing infinite recursion.
I ended up finding a simpler way to get what I needed by simply adding a method to an ISubject instance.
function distinctUntilChangedBehaviorSubject(
initialValue: number
): ISubject<number> & { getValue(): number } {
const observer = new BehaviorSubject<number>(initialValue);
const observable = observer.distinctUntilChanged();
const subject: ISubject<number> = Subject.create(
observer,
observable
);
return Object.assign(
subject,
{
getValue: () => observer.getValue()
}
);
}

How to refactor cascade if statements

I found this question on https://github.com/arialdomartini/Back-End-Developer-Interview-Questions#snippets
And I am curious about your opinion, I just can't find an decent solution of this refactor, and what pattern would apply in this very common case.
function()
{
HRESULT error = S_OK;
if(SUCCEEDED(Operation1()))
{
if(SUCCEEDED(Operation2()))
{
if(SUCCEEDED(Operation3()))
{
if(SUCCEEDED(Operation4()))
{
}
else
{
error = OPERATION4FAILED;
}
}
else
{
error = OPERATION3FAILED;
}
}
else
{
error = OPERATION2FAILED;
}
}
else
{
error = OPERATION1FAILED;
}
return error;
}
Do you have any idea of how to refactor this?
Actually, I feel there is way more space for refactoring than what suggested by Sergio Tulentsev.
The questions in the repo you linked are more about starting a conversation on code than closed-ended questions. So, I think it is worth to discuss the smells and design flaws of that code, to set up the refactoring goals.
Smells
I see these problems:
The code violates some of the SOLID principles. It surely violates the Open Closed Principle, as it is not possible to extend it without changing its code. E.g., adding a new operation would require adding a new if/else branch;
It also violate the Single Responsibility Principle. It just does too much. It performs error checks, it's responsible to execute all the 4 operations, it contains their implementations, it's responsible to check their results and to chain their execution in the right order;
It violates the Dependency Inversion Principle, because there are dependencies between high-level and low-level components;
It has a horrible Cyclomatic complexity
It exhibits high coupling and low cohesion, which is exactly the opposite of what is recommended;
It contains a lot of code duplication: the function Succeeded() is repeated in each branch; the structure of if/elses is replicated over and over; the assignment of error is duplicated.
It could have a pure functional nature, but it relies instead on state mutation, which makes reasoning about it not easy.
There's an empty if statement body, which might be confusing.
Refactoring
Let's see what could be done.
Here I'm using a C# implementation, but similar steps can be performed with whatever language.
I renamed some of the elements, as I believe honoring a naming convention is part of the refactoring.
internal class TestClass
{
HResult SomeFunction()
{
var error = HResult.Ok;
if(Succeeded(Operation1()))
{
if(Succeeded(Operation2()))
{
if(Succeeded(Operation3()))
{
if(Succeeded(Operation4()))
{
}
else
{
error = HResult.Operation4Failed;
}
}
else
{
error = HResult.Operation3Failed;
}
}
else
{
error = HResult.Operation2Failed;
}
}
else
{
error = HResult.Operation1Failed;
}
return error;
}
private string Operation1()
{
// some operations
return "operation1 result";
}
private string Operation2()
{
// some operations
return "operation2 result";
}
private string Operation3()
{
// some operations
return "operation3 result";
}
private string Operation4()
{
// some operations
return "operation4 result";
}
private bool Succeeded(string operationResult) =>
operationResult == "some condition";
}
internal enum HResult
{
Ok,
Operation1Failed,
Operation2Failed,
Operation3Failed,
Operation4Failed,
}
}
For the sake of simplicity, I supposed each operation returns a string, and that the success or failure is based on an equality check on the string, but of course it could be whatever. In the next steps, it would be nice if the code is independent from the result validation logic.
Step 1
It would be nice to start the refactoring with the support of some test harness.
public class TestCase
{
[Theory]
[InlineData("operation1 result", HResult.Operation1Failed)]
[InlineData("operation2 result", HResult.Operation2Failed)]
[InlineData("operation3 result", HResult.Operation3Failed)]
[InlineData("operation4 result", HResult.Operation4Failed)]
[InlineData("never", HResult.Ok)]
void acceptance_test(string failWhen, HResult expectedResult)
{
var sut = new SomeClass {FailWhen = failWhen};
var result = sut.SomeFunction();
result.Should().Be(expectedResult);
}
}
Our case is a trivial one, but being the quiz supposed to be a job interview question, I would not ignore it.
Step 2
The first refactoring could be getting rid of the mutable state: each if branch could just return the value, instead of mutating the variable error. Also, the name error is misleading, as it includes the success case. Let's just get rid of it:
HResult SomeFunction()
{
if(Succeeded(Operation1()))
{
if(Succeeded(Operation2()))
{
if(Succeeded(Operation3()))
{
if(Succeeded(Operation4()))
return HResult.Ok;
else
return HResult.Operation4Failed;
}
else
return HResult.Operation3Failed;
}
else
return HResult.Operation2Failed;
}
else
return HResult.Operation1Failed;
}
We got rid of the empty if body, making in the meanwhile the code slightly easier to reason about.
Step 3
If now we invert each if statement (the step suggested by Sergio)
internal HResult SomeFunction()
{
if (!Succeeded(Operation1()))
return HResult.Operation1Failed;
if (!Succeeded(Operation2()))
return HResult.Operation2Failed;
if (!Succeeded(Operation3()))
return HResult.Operation3Failed;
if (!Succeeded(Operation4()))
return HResult.Operation4Failed;
return HResult.Ok;
}
we make it apparent that the code performs a chain of executions: if an operation succeeds, the next operation is invoked; otherwise, the chain is interrupted, with an error. The GOF Chain of Responsibility Pattern comes to mind.
Step 4
We could move each operation to a separate class, and let our function receive a chain of operations to execute in a single shot. Each class would deal with its specific operation logic (honoring the Single Responsibility Principle).
internal HResult SomeFunction()
{
var operations = new List<IOperation>
{
new Operation1(),
new Operation2(),
new Operation3(),
new Operation4()
};
foreach (var operation in operations)
{
if (!_check.Succeeded(operation.DoJob()))
return operation.ErrorCode;
}
return HResult.Ok;
}
We got rid of the ifs altogether (but one).
Notice how:
The interface IOperation has been introduced, which is a preliminary move to decouple the function from the operations, complying the with the Dependency Inversion Principle;
The list of operations can easily be injected into the class, using the Dependency Injection.
The result validation logic has been moved to a separate class Check, injected into the main class (Dependency Inversion and Single Responsibility are satisfied).
internal class SimpleStringCheck : IResultCheck
{
private readonly string _failWhen;
public Check(string failWhen)
{
_failWhen = failWhen;
}
internal bool Succeeded(string operationResult) =>
operationResult != _failWhen;
}
We gained the ability to switch the check logic without modifying the main class (Open-Closed Principle).
Each operation has been moved to a separate class, like:
internal class Operation1 : IOperation {
public string DoJob()
{
return "operation1 result";
}
public HResult ErrorCode => HResult.Operation1Failed;
}
Each operation knows its own error code. The function itself became independent from it.
Step 5
There is something more to refactor on the code
foreach (var operation in operations)
{
if (!_check.Succeeded(operation.DoJob()))
return operation.ErrorCode;
}
return HResult.Ok;
}
First, it's not clear why the case return HResult.Ok; is handled as a special case: the chain could contain a terminating operation never failing and returning that value. This would allow us to get rid of that last if.
Second, our function still has 2 responsibility: to visit the chain, and to check the result.
An idea could be to encapsulate the operations into a real chain, so our function could reduce to something like:
return operations.ChainTogether(_check).Execute();
We have 2 options:
Each operation knows the next operation, so starting from operation1 we could execute the whole chain with a single call;
Operations are kept unaware of being part of a chain; a separate, encapsulating structure adds to operations the ability to be executed in sequence.
I'm going on with the latter, but that's absolutely debatable. I'm introducing a class modelling a ring in a chain, moving the code away from our class:
internal class OperationRing : IRing
{
private readonly Check _check;
private readonly IOperation _operation;
internal IRing Next { private get; set; }
public OperationRing(Check check, IOperation operation)
{
_check = check;
_operation = operation;
}
public HResult Execute()
{
var operationResult = _operation.DoJob();
if (_check.Succeeded(operationResult))
return Next.Execute();
return _operation.ErrorCode;
}
}
This class is responsible to execute an operation and to handle the execution to the next ring if it succeeded, or to interrupt the chain returning the right error code.
The chain will be terminated by a never-failing element:
internal class AlwaysSucceeds : IRing
{
public HResult Execute() => HResult.Ok;
}
Our original class reduces to:
internal class SomeClass
{
private readonly Check _check;
private readonly List<IOperation> _operations;
public SomeClass(Check check, List<IOperation> operations)
{
_check = check;
_operations = operations;
}
internal HResult SomeFunction()
{
return _operations.ChainTogether(_check).Execute();
}
}
In this case, ChainTogether() is a function implemented as an extension of List<IOperation>, as I don't believe that the chaining logic is responsibility of our class.
That's not the right answer
It's absolutely debatable that the responsibilities have been separated to the most appropriate classes. For example:
is chaining operations a task of our function? Or should it directly receive the chained structure?
why the use of an enumerable? As Robert Martin wrote in "Refactoring: Improving the Design of Existing Code": enums are code smells and should be refactored to polymorphic classes;
how much is too much? Is the resulting design too complex? Does the complexity of the whole application need this level of modularisation?
Therefore, I'm sure there are several other ways to refactor the original function. In a job interview, or in a pair programming session, I expect a lot of discussions and evaluations to occur.
You could use early returns here.
function() {
if(!SUCCEEDED(Operation1())) {
return OPERATION1FAILED;
}
if(!SUCCEEDED(Operation2())) {
return OPERATION2FAILED;
}
if(!SUCCEEDED(Operation3())) {
return OPERATION3FAILED;
}
if(!SUCCEEDED(Operation4())) {
return OPERATION4FAILED;
}
# everything succeeded, do your thing
return S_OK;
}

DART - can I cast a string to an enum?

Is there a way to convert a string to an enum?
enum eCommand{fred, joe, harry}
eCommand theCommand= cast(eCommand, 'joe');??
I think I just have to search for the enum (eg loop).
cheers
Steve
I got annoyed with the state of enums and built a library to handle this:
https://pub.dev/packages/enum_to_string
Basic usage:
import 'package:enum_to_string:enum_to_string.dart';
enum TestEnum { testValue1 };
main(){
final result = EnumToString.fromString(TestEnum.values, "testValue1");
// TestEnum.testValue1
}
Still more verbose than I would like, but gets the job done.
I have came up with a solution inspired from https://pub.dev/packages/enum_to_string that can be used as a simple extension on List
extension EnumTransform on List {
String string<T>(T value) {
if (value == null || (isEmpty)) return null;
var occurence = singleWhere(
(enumItem) => enumItem.toString() == value.toString(),
orElse: () => null);
if (occurence == null) return null;
return occurence.toString().split('.').last;
}
T enumFromString<T>(String value) {
return firstWhere((type) => type.toString().split('.').last == value,
orElse: () => null);
}
}
Usage
enum enum Color {
red,
green,
blue,
}
var colorEnum = Color.values.enumFromString('red');
var colorString: Color.values.string(Color.red)
Dart 2.6 introduces methods on enum types. It's much better to call a getter on the Topic or String itself to get the corresponding conversion via a named extension. I prefer this technique because I don't need to import a new package, saving memory and solving the problem with OOP.
I also get a compiler warning when I update the enum with more cases when I don't use default, since I am not handling the switch exhaustively.
Here's an example of that:
enum Topic { none, computing, general }
extension TopicString on String {
Topic get topic {
switch (this) {
case 'computing':
return Topic.computing;
case 'general':
return Topic.general;
case 'none':
return Topic.none;
}
}
}
extension TopicExtension on Topic {
String get string {
switch (this) {
case Topic.computing:
return 'computing';
case Topic.general:
return 'general';
case Topic.none:
return 'none';
}
}
}
This is really easy to use and understand, since I don't create any extra classes for conversion:
var topic = Topic.none;
final string = topic.string;
topic = string.topic;
(-:
As of Dart 2.15, you can use the name property and the byName() method:
enum eCommand { fred, joe, harry }
eCommand comm = eCommand.fred;
assert(comm.name == "fred");
assert(eCommand.values.byName("fred") == comm);
Just be aware that the byName method throws an ArgumentError if the string is not recognized as a valid member in the enumeration.
For the Dart enum this is a bit cumbersome.
See Enum from String for a solution.
If you need more than the most basic features of an enum it's usually better to use old-style enums - a class with const members.
See How can I build an enum with Dart? for old-style enums
This is the fastest way I found to do this :
enum Vegetable { EGGPLANT, CARROT, TOMATO }
Vegetable _getVegetableEnum(dynamic myVegetableObject) {
return Vegetable.values.firstWhere((e) => describeEnum(e) == myVegetableObject);
}
i had the same problem, a small enum and a string, so i did this
dynamic _enum_value = EnumFromString(MyEnum.values, string_to_enum);
dynamic EnumFromString(List values, String comp){
dynamic enumValue = null;
values.forEach((item) {
if(item.toString() == comp){
enumValue = item;
}
});
return enumValue;
}
i know this is not the best solution, but it works.
Static extension methods would make this nice (currently unimplemented).
Then you could have something like this:
extension Value on Keyword {
/// Returns the valid string representation of a [Keyword].
String value() => toString().replaceFirst(r'Keyword.$', '');
/// Returns a [Keyword] for a valid string representation, such as "if" or "class".
static Keyword toEnum(String asString) =>
Keyword.values.firstWhere((kw) => kw.value() == asString);
}
FOUND ANS
Check this article. Very well explained: Link
extension EnumParser on String {
T toEnum<T>(List<T> values) {
return values.firstWhere(
(e) => e.toString().toLowerCase().split(".").last ==
'$this'.toLowerCase(),
orElse: () => null,
),
}
}
The cleanest way is to use built-in functionality:
enum EmailStatus {
accepted,
rejected,
delivered,
failed,
}
EmailStatus.values.byName('failed') == EmailStatus.failed;
=> true

Are all Refactorings parameterized?

The question is about refactorings. Consider a rename method refactoring. This refactoring can be visualized as meta-method that takes old and new names, and changes the old method name to the new. so, for refactoring
foo()
{
.........
.........
}
to
boo()
{
.........
.........
}
the meta method for refactoring would be ...
renameMethod (foo, boo)
This is called parametrized refactoring. My question is can all refactorings mentioned in http://www.refactoring.com/catalog/ be thought of as having some parameters or are there refactorings that do not need such parameters?
There are some "code cleanups" which don't require parameters. Whether you'd call them refactorings or not I don't know, but:
if (condition) {
return firstValue;
} else {
return secondValue;
}
to:
return condition ? firstValue : secondValue;
or even more so:
if (condition) {
return true;
} else {
return false;
}
to:
return condition;
But even within the "proper" refactoring catalog there are some which don't require parameters. For example, the hide method refactoring just makes a method private, and "reduce scope of variable" just moves a declaration.

Resources