lundi 2 mars 2020

Polling thread in Blazor

I am building a Blazor application with a REST API and Web interface. I will also have a monitoring part of the application that will poll data each second from a lot of different data sources. I have created a long running thread in a separate class that simply polls the data I want and it seems to be working fine. The application template I am using is a Blazor ASP.NET Server application. Simply like this:

 m_pollThread = new Thread(new ThreadStart(PollThread))
 {
    IsBackground = true
 };
 m_pollThread.Start();

What I am wondering now is: is it completely wrong with respect to programming patterns to put this type of polling threads inside of the Blazor application itself? Is there some problems doing like this that will backfire later on (memory consumption, performance of the rest of the application)? The reason why I am asking is because as far as I know, Blazor and ASP.NET Core applications are general "on-request" and wakes up when something is requested, and not executing long-running endless polling tasks. I do not know if I could run that within IIS for instance.

dimanche 1 mars 2020

Should a library have caching implementation inside it

I am working on building a library and wondering if caching should be a part of the library or should the client using it should handle the caching.

What is the proper way of updating class-fields with class-methods?

I often find myself in a situation that I can do either of the two scenarios:

class Foo:
  def __init__(self):
    self.a: str = ''
    self.my_method()

  def my_method(self):
    self.a = ... # some magic that finds the actual value of a

or

class Foo:
  def __init__(self):
    self.a: str = self.my_method()

  def my_method(self):
    a = ... # some magic that finds the actual value of a
    return a

Question: What is the right design choice? (I don't find any of them smart!)


Note: I don't think it is a good idea to turn this method into a function (i.e., taking my_method outside of the class), as I believe it conceptually belongs to that class.

Express type composition in OOP

Suppose we want to write a RPG game which has 3 base character types: Fighter, Mage and Archer. Also we have combined character types like Knight, Paladin and Ranger. In TypeScript we can describe interfaces for characters like this:

    // fighter can fight
    // mage can cast
    // archer can shoot
    // paradin can cast and fight
    // knight can fight and shoot
    // ranger can cast and shoot

    type Fighter = {fight: () => string}
    type Mage = {cast: () => string}
    type Archer = {shoot: () => string}
    type Knight = Fighter & Archer
    type Paladin = Fighter & Mage
    type Ranger = Archer & Mage

The question is how to implement these interfaces using only OOP techniques (imagine that we are working with mainstream OOP language like C#) ?

I had no success expressing this with inheritance without behavior duplication. Currently the only way I see is:

class Paladin {
  constructor(private fighter: Fighter, private mage: Mage) {}

  fight() {this.fighter.fight()}
  cast() {this.mage.cast()}
}

But I don't like that approach because any time I want to create a paladin I also have to create a mage and a fighter which is basically the same person

Angular Strategy + Decorator template design without doing a lots of *ngIf

I've been working on a way of not doing a lots of *ngIf that depends on a type selected by the user

<select [(ngModel)]="type" name="type">
    <option value="a">Type A</option>
    <option value="b">Type B</option>
</select>

<div *ngIf="type === 'a'">
    logic...
</div>

<div *ngIf="type === 'b'">
    logic...
</div>

So i endedup doing this, and i want to know if there exists a simplier way

some-service.ts

export const TYPE_MAP = {};

export class SomeService {
    typeMap = TYPE_MAP;

    constructor() {
    }
}

type-manager.interface.ts

export interface TypeManager {
    someMethod();
}

type-manager.decorator.ts

export function TypeManagerDecorator(aType: string) {
    return function _TypeManagerDecorator<T extends { new(...args: any[]): TypeManager}>(constr: T) {
        TYPE_MAP[aType] = constr;
    };
}

manager-for-type-a.component.ts

@TypeManagerDecorator('a')
@Component({
    selector: 'app-manager-for-type-a',
    templateUrl: './manager-for-type-a.component.html',
    styleUrls: ['./manager-for-type-a.component.css'],
    viewProviders: [
        {
            provide: ControlContainer,
            useExisting: NgForm
        }
    ]
})
export class ManagerForTypeAComponent implements OnInit, TypeManager {

    constructor() {
    }

    ngOnInit() {
    };

    someMethod() {
    };
}

manager-for-type-b.component.ts

@TypeManagerDecorator('b')
@Component({
    selector: 'app-manager-for-type-b',
    templateUrl: './manager-for-type-b.component.html',
    styleUrls: ['./manager-for-type-b.component.css'],
    viewProviders: [
        {
            provide: ControlContainer,
            useExisting: NgForm
        }
    ]
})
export class ManagerForTypeBComponent implements OnInit, TypeManager {

    constructor() {
    }

    ngOnInit() {
    };

    someMethod() {
    };
}

main.component.html

<form #form="ngForm" (ngSubmit)="form.valid" autocomplete="off">

    <select [(ngModel)]="type" name="type" (ngModelChange)="changeTypeManager($event)">
        <option value="a">Type A</option>
        <option value="b">Type B</option>
    </select>


    <ng-container #container></ng-container>

</form>

main.component.ts

@Component({
    selector: 'app-main',
    templateUrl: './main.component.html',
    styleUrls: ['./main.component.css']
})
export class MainComponent implements OnInit, OnDestroy {

    @ViewChild('main', {read: ViewContainerRef, static: true})
    private mainContainer: ViewContainerRef;
    private componentReference: ComponentRef<any>;

    constructor(
        private aService: SomeService,
        private resolver: ComponentFactoryResolver
    ) {

    }

    ngOnInit() {
    }

    private changeTypeManager(aType: string) {
        if(this.componentReference) {
            this.componentReference.destroy();
        }

        if(!this.aService.typeMap[aType]) {
            throw new Error(`No class exists with the decorator @TypeManagerDecorator('${aType}')`);
        }

        const componentFactory = this.resolver.resolveComponentFactory(this.aService.typeMap[aType]);
        this.componentReference = this.mainContainer.createComponent(componentFactory);
    }

}

How to do a unit test to a java method?

i have this method and i need do test unit with Junit, but i dont know how do it! someone can help me? Thanks.

public static boolean esTelefonoFijo(String telefonoFijo) {
    // pattern validate tlp
    Pattern pattern = Pattern.compile("^?[89]\\d{8}$");
    Matcher matcher = pattern.matcher(telefonoFijo);
    return matcher.find();
}

How can use or implement thread safe of chain of responsibility Design Pattern in C#?

I want To use a chain of responsibility in thread-safe state.

Is there any way to Implementation of Thread-safe chain of responsibility Design Pattern Or use a chain of responsibility pattern in class as a theard-safe state?