mercredi 2 juin 2021

class diagram for bank class on low and high acount balance

I am learning system design and stuck at some point. I have a bank class containing balance and account number. I want to trigger alerts on low balance and give investment options on high balance(keeping in mind if I want to extend it in future). How will I design this functionality. Should I make this a part of bank class or a separate class.

For triggering alerts, I am thinking to apply strategy design pattern. Please help me in making the class diagram/design.

Circuit Breaker for asynchronous channel along with Dead Letter Channel

I have a requirement to use circuit breaker along with a Dead Letter Channel (DLC). The errored out messages should go to DLC. The other messages should not be consumed while the circuit is open. Right now I have implemented like below:

public void configure() throws Exception {
// @formatter:off

    int threshold = 2;
    long failureWindow = 30000;
    long halfOpenAfter = 120000;
    RoutePolicy routePolicy = 
      new ThrottlingExceptionRoutePolicy(threshold, failureWindow, halfOpenAfter, null);

    errorHandler(deadLetterChannel("seda:errorQueue").
               useOriginalMessage().maximumRedeliveries(3).redeliveryDelay(1000));



    from("timer://myTimer?period=5s")
    .routeId("InputFolderToTestSedaRoute")
    .setBody(exchangeProperty(Exchange.TIMER_FIRED_TIME))
    .convertBodyTo(String.class)
    .to("seda://testSeda")
    .log("**** Input data published to  testSeda - ${body}***** :")
    ;

    from("seda://testSeda")
    .routeId("TestSedaToOutputFolderRoute")
    .routePolicy(routePolicy)
    .to("file://?autoCreate=false&fileName=TimerFile-${exchangeProperty.CamelTimerCounter}")
    ;

    //Error Handling route!

    from("seda:errorQueue")
    .routeId("ErrorHandlingRoute")
    .log("***** error body: ${body} *****")
    .to("file://?fileName=TimerFile-${exchangeProperty.CamelTimerCounter}.txt")
    .log("***** Exception Caught: ${exception} *****")
    ;

    // @formatter:on

}

The problem is that this won't work as expected if DLC is enabled. But if I comment the line starting with "errorHandler(deadLetterChannel()" it will work - means the above code will work ONLY with default error handler.

My question is - I want the error messages to go to error Queue AND I want the circuit breaker enabled. Is there any way? Thank you very much for your time.

mardi 1 juin 2021

Patterns in React (wrapper)

Good day. I'm building a tree of components and want to use functions of root component in other components of tree. I throw function reference through all tree. Also I use the object if me need get value from the function in not root componet. Can you help me? Can you show me how to do this as HOC ? If it will be not so hard for you show examples on my code.

import React from 'react';

class Page extends React.Component{

    Answer = {
        value : ''
    }

    doSomething(){

        console.log(this.Answer.value);
        console.log('Ready!');
    }
    
    render(){
        return(
            <div>
                <div>
                    <Body 
                        ParentFunc={()=>this.doSomething()} 
                        ParentParameters={this.Answer}
                    />
                </div>
            </div>
        )
    }
}

export default Page

class Body extends React.Component{
    render(){

        const{
            ParentFunc,
            ParentParameters
        } = this.props
        
        return(
            <div>
                <div>
                    <SomeComponent 
                        ParentFunc={()=>ParentFunc()}
                        ParentParameters={ParentParameters}
                    />
                </div>
            </div>
        )
    }
}

class SomeComponent extends React.Component{

    getAnswer(){
        
        const{
            ParentFunc,
            ParentParameters
        } = this.props

        ParentParameters.value = 'Some text'
        
        ParentFunc()
    }
    
    render(){
        
        return(
            <div onClick={()=>this.getAnswer()}>
                We can?
            </div>
        )
    }
}


Pass exception to calling function in python

I have a simple best practice question. The setting is that i simply have one function calling another one. The code ist little dummy for better understanding:

def called_function(x):
    y = x * 3
    try:
        z = 3 / x
    except my_crazy_exception as e: 
        print("I want at least to know y!")
        print(y)
        # Does this make sense:
        # ??? raise my_crazy_exception ????

if __name__ == "main":
    for i in my_crazy_list:
        try:
            called_function(i)
        except my_crazy_exception as e:
            print("I want to know i!")
            print(i)
       

Know i want to know information from the called function and as well from the calling function. So i want to pass the exception from the origin to the next higher function. My idea would be know just to raise another excepterin in the except: part of the called function. But would this be best practice?

A good design-pattern approach to aggregate JSON-Data in Java

I need to extract (aggregate) particular information about satellites (this should be done in external Modules which will be loaded by e.g. reflection). Furthermore, the result of such aggregation, which can be hierarchically indefinitely deep, should be output by modules too (e.g. sysout, write to JSON)

An Aggregation of this JSON-data could be for instance:

- Sattelite A
   - Transponder B
      - 20 radio programmes
      - 10 tv programmes
   - Transponder C
      - 1 radio programme
      - 100 tv programmes

or

Sattelite a
   - english TV-Programme a
   - english TV-Programme b
Sattelite b
   - english TV-Programme a
   - english TV-Programme b
   - english TV-Programme c

Module-Overview

Any idea, which approach (design patterns, classes) would be appropriate to tackle this? I thought about generic composite.

My query is to make a single instance of a static class but ensure that no other instance of static class is there

I am new in C# and my question is to create single instance of a static c# class but we don't want to use singleton pattern for it. How would you suggest to create single instance of a static class?

Builder pattern without inner class

Lets say I have this builder pattern. I searched everywhere but couldn't find why would I need to use inner class if outer class has public consturctor.

public class User {

private final String firstName;
private final String surname;
private final int age;


public User(UserBuilder userBuilder) {
    this.firstName = userBuilder.firstName;
    this.surname = userBuilder.surname;
    this.age = userBuilder.age;
}



public static class UserBuilder {

    private final String firstName;
    private final String surname;
    private int age;

    public UserBuilder(String firstName, String surname) {
        this.firstName = firstName;
        this.surname = surname;
    }

    public UserBuilder age(int age) {
        this.age = age;
        return this;
    }


    public User build() {
        User user = new User(this);
        return user;
    }
}
}

Here I could rewrite this code without using inner class as :

public class User {

private String firstName;
private String surname;
private int age;


public User(String firstName, String surname) {
 this.firstName = firstName;
 this.surname= surname;
}


public User age(int age) {
    this.age = age;
    return this;
}

}
}

When I read about builder pattern they say this pattern prevents big consturctor blocks. And they use inner with setters (with fluent pattern). I don't understand why we need to create inner class I could do the same thing it without using an inner class if my constructor is public. Here another example for more complex variables:

class NutritionFacts {
  private final int servingSize;
  private final int servings;
  private int calories;
  private int fat;
  private int sodium;
  private int carbohydrate;


    public NutritionFacts(int servingSize, int servings) {
        this.servingSize = servingSize;
        this.servings = servings;
    }
    public NutritionFacts calories(int val)
    { calories = val; return this; }
    public NutritionFacts fat(int val)
    { fat = val; return this; }
    public NutritionFacts sodium(int val)
    { sodium = val; return this; }
    public NutritionFacts carbohydrate(int val)
    { carbohydrate = val; return this; }
    
@Override
public String toString() {
    return "NutritionFacts{" +
            "servingSize=" + servingSize +
            ", servings=" + servings +
            ", calories=" + calories +
            ", fat=" + fat +
            ", sodium=" + sodium +
            ", carbohydrate=" + carbohydrate +
            '}';
}
}