lundi 30 septembre 2019

callback to clean pointers (MCVE : auto eject traitor Soldier from Vehicle)

In my game, Soldier that becomes a traitor will be automatically ejected from Turret, Tank, and a lot of holder. (MCVE)

A Soldier can reside in 1 Turret and 1 Tank at the same time.
A Soldier can reside in at most 1 Turret and at most 1 Tank.

Here is the Soldier, Turret and Tank class (In real cases, they are in 3 files) :-

#include <iostream>
#include <string>
#include <vector>
struct Soldier{
    private: int team=0;
    public: void setTeam(int teamP){
        team=teamP;
        //should insert callback
    }
};
struct Turret{
    Soldier* gunner=nullptr;
    //currently it is so easy to access Turret's gunner
};
struct Tank {
    std::vector<Soldier*> passenger;
    //currently it is so easy to access Tank's passenger by index
};
std::vector<Soldier*> global_soldier;
std::vector<Turret*> global_turret;
std::vector<Tank*> global_tank;

Here is the main().
Currently whenever programmer want to set team of any instance of Soldier, he has to do the ejection manually :-

int main(){
    Soldier soldier1; global_soldier.push_back(&soldier1);
    Turret turret1;   global_turret.push_back(&turret1);
    turret1.gunner=&soldier1;
    //v game loop
    soldier1.setTeam(2);
    //v manual ejection (should be callback?)
    for(auto& ele: global_turret){  
        if(ele->gunner==&soldier1){
            ele->gunner=nullptr;
        }
    }
    for(auto& ele: global_tank){
        for(auto& elePass: ele->passenger){
            if(elePass==&soldier1){
                elePass=nullptr;
            }
        }
    }
    //^ manual ejection
    std::cout<<"should print 1="<<(turret1.gunner==nullptr)<<std::endl;
}

This leads to a lot of boilerplate code after every call of Soldier::setTeam(int) (maintenance problem) and performance problem.

How to fix it?

Current advantage that I don't want to lose :-
- It is so easy to access the Turret's gunner, and one of a Tank's passenger by index.

My workaround (MCVE)

In Soldier, I created a callback hub (callback_changeTeams).
In Turret and Tank, I create a callback definition to Soldier (Turret::ChangeTeam and Tank::ChangeTeam).

Here is the working code.
Soldier :-

class Soldier;
struct Callback{
    public: virtual void changeTeam_virtual(Soldier* soldier)=0;
};
std::vector<Callback*> callback_changeTeams;
struct Soldier{
    private: int team=0;
    public: void setTeam(int teamP){
        if(team==teamP){

        }else{
            team=teamP;
            for(auto callback :callback_changeTeams) 
                callback->changeTeam_virtual(this);
        }
        //should insert callback
    }
};

Turret :-

struct Turret;
std::vector<Turret*> global_turret;
struct Turret{
    Soldier* gunner=nullptr;
    struct ChangeTeam : public Callback{
        public: virtual void changeTeam_virtual(Soldier* soldier){
            for(auto& ele: global_turret){  
                if(ele->gunner==soldier){
                    ele->gunner=nullptr;
                }
            }
        }
    };
};

Tank (similar as Turret's ) :-

struct Tank;
std::vector<Tank*> global_tank;
struct Tank {
    std::vector<Soldier*> passenger;
    struct ChangeTeam : public Callback{
        public: virtual void changeTeam_virtual(Soldier* soldier){
            for(auto& ele: global_tank){
                for(auto& elePass: ele->passenger){
                    if(elePass==soldier){
                        elePass=nullptr;
                    }
                }
            }
        }
    };
};

Main :-

std::vector<Soldier*> global_soldier;
int main(){
    Turret::ChangeTeam turretCallback;
    Tank::ChangeTeam tankCallback;
    callback_changeTeams.push_back(&turretCallback);
    callback_changeTeams.push_back(&tankCallback);
    Soldier soldier1; global_soldier.push_back(&soldier1);
    Turret turret1;   global_turret.push_back(&turret1);
    turret1.gunner=&soldier1;
    //v game loop
    soldier1.setTeam(2);
    //v should be callback

    std::cout<<"should print 1="<<(turret1.gunner==nullptr)<<std::endl;
}

Disadvantages:-

1. Duplication code between Turret & Tank.
Not so bad, but in real case, I have a lot of Turret-like (that store a pointer to Soldier) and Tank-like (that store array of Soldier). It would be a lot of code duplication.

2. Still Bad performance. I have to iterate every Turret and Tank whenever I just change a team setting of a Soldier.
This can be solved by cache parent Turret and Tank, so iteration is not required.
However, in real case, I have a lot of parent type and it would be dirty e.g. :-

struct Soldier{
    //... some field / functions ...
    Turret* parentTurret;
    Tank* parentTank;
    SomeParentClass1* parent1;
    SomeParentClass2* parent2;   // bra bra bra.. ... dirty messy
};

My random ideas (not much useful) : Smart pointer (std::shared_ptr); std::unordered_map ; change design-pattern; make the callbacks commit as batch; I am using Entity Component System.

Do I need a data transfer object pattern from client to server?

I am putting together a simple REST based web-service backend using Spring. I have a domain model called User which contains all of the possible fields that a certain user need within the life-cycle of application. Depending on which way the information is flowing, I am using a certain POJO.

For serialization/marshalling:

Persistence (database) > UserDao > User > UserService > UserController > UserDto > Client

OR

Persistence > UserDao > User > UserService > FriendsService > FriendsController > FriendsDto > Client

Where UserDto encapsuates select few fields from the User.

What pattern should I use for the other way around (deserialization/unmarshalling) when I am mapping POST requests from client?

Client > UserController > UserSomePattern? > UserService > UserDao > Persistence

Similarly, UserSomePattern will map certain fields from User but not necessarily ditto as UserDto. What should my UserSomePattern POJO be called, if any?

Singleton Design Pattern Double Checked Locking

if (searchBox == null) { //1
synchronized (SearchBox.class) {
    if (searchBox == null) {  //2
        searchBox = new SearchBox();
        }
    }
}

}

here is my custom class for singleton pattern. in this code, I use double-checked locking as above. As I read many posts on some source, they say that double-check is useful because it prevents two concurrent threads run at same times make two different objects. As per threading concept, at a time an only single thread gets executed by thread scheduler. Then how 2 threads will try to execute the above code.

Please explain to me. What have I understood wrong?

Thanks :)

Spring batch falls under which design pattern

I was going through the famous GoF - Gang of Four.

And i happen to work a lot around Spring-batch framework . So i was wondering which design pattern it falls under.

I think Spring batch should fall under - Chanin Of Responsibility design pattern where - each layer delegates commands to a chain of processing objects.

Am I correct?

Any comments,suggestions and answers are welcome.

dimanche 29 septembre 2019

Code refactor to replace throw exception technique with operation result

I need to do some refactoring for the below code as i am looking replacing the throw invalidoperationexception technique with another one returning an operationresult object ,also i need to return a json object. i need your advice regarding refactoring the below code in general as well.

looking for several design patterns , and i got an idea of replacing throw expectation with returning an object with boolean flag if operation is succeed or not , and a string with Error message if any exception rules.

//Method to return json with operation result public void UpdateNINByID(int ID) { try { m_logger.Log(LogLevel.Info, string.Format("UpdateNINByID is Started for ID {0}", ID));

            o_tdsAlert = new tdsAlert();
            o_dmAlert.GetSrcDestDataByID(o_tdsAlert, ID);

            if (o_tdsAlert.DATA_SEARCH_EFGHEGCA_SI_HAS_ACC.Count == 0)
            {
                m_logger.Log(LogLevel.Trace, string.Format("UpdateNINByID - No data found in source for ID {0}", ID));
                return;
            }

            ConvertNinToUpperCase(o_tdsAlert);

            var drSrc = o_tdsAlert.DATA_SEARCH_EFGHEGCA_SI_HAS_ACC.FirstOrDefault();

//I need to refactor this oALRTNINExtractionConfig = oALRTNINExtractionConfig.GetALRTNINConfig(drSrc.Country, drSrc.MethodType);

            SourceData srcIDs = CreateValidListSrcList(drSrc, drSrc.MethodType);
            List<CleansedIDs> cleansedIDs = GetCleansedIDs(drSrc, srcIDs);
            TransformToDTCC_Client_DATA(o_tdsAlert, drSrc, cleansedIDs);

            o_dmAlert.updateDtcc_Client_DataByID(o_tdsAlert);

            if (oALRTNINExtractionConfig.IsHandleAlertRowUpdates)
                AlertCleansing();

            if (oALRTNINExtractionConfig.IsSendNotification)
                SendNotification(srcIDs);

            m_logger.Log(LogLevel.Info, string.Format("UpdateNINByID - is Finished for ID {0}", ID));
        }
        catch (Exception ex)
        {
            m_logger.LogException(LogLevel.Error, "UpdateNINByID - NIN ByID Exception", ex);
            throw;
        }
    }

//I need to refactor public ALRTNINExtractionConfig GetALRTNINConfig(string Country, string MethodType) { var ALRTNINExtractionConfigs = JsonConvert.DeserializeObject( File.ReadAllText(ConfigurationManager.AppSettings["ALRTNINExtractionConfig"])); if (ALRTNINExtractionConfigs == null) throw new InvalidOperationException("ALRTNINExtractionConfigs is null");

        IEnumerable<ALRTNINExtractionConfig> oALRTNINExtractionConfiglst = ALRTNINExtractionConfigs.ALRTNINExtractionConfiglst;

        if (!oALRTNINExtractionConfiglst.Where(r => r.Country == Country).Any())
            Country = MethodType = Default;

        oALRTNINExtractionConfiglst = oALRTNINExtractionConfiglst.Where(r => r.Country == Country);
        if (!oALRTNINExtractionConfiglst.Any())
            throw new InvalidOperationException("Country isnot set in configuration");
        if (!oALRTNINExtractionConfiglst.Where(r => r.MethodType.Contains(MethodType)).Any())
            throw new InvalidOperationException("MethodType isnot set in configuration");
        var aLRTNINExtractionConfig = oALRTNINExtractionConfiglst.Where(r => r.MethodType.Contains(MethodType)).FirstOrDefault();
        return aLRTNINExtractionConfig;
    }

I am excepting some code refactor recommendations , also i can share the whole code if needed.

I am trying to implement the strategy design pattern in the below snippet using Java 8 .Looking for better ways to implement?

I have below service implementation :-

package Java8.controller;

import java.util.function.Function;

public class ServiceImpl implements ITicket {

    Function<Integer,Double> ticketCal;

    public ServiceImpl(Function<Integer,Double> ticketCal){
        this.ticketCal= ticketCal;
    }

    @Override
    public double calculateFare(int quantity) {
        return ticketCal.apply(quantity);
    }

}

Below are the strategies that I have created :-

Recliner ticket strategy :-

package Java8.controller;

import java.util.function.Function;

public interface ReclinerTicketStrategy {

    default Function<Integer,Double> reclinerTicketStrategy(){

        return (noOfTickets)->{
            return noOfTickets * 200.00;
        };
    }
}

VIP Ticket strategy :-

package Java8.controller;

import java.util.function.Function;

public interface VipTicketStrategy {

    default Function<Integer,Double> vipTicketStrategy(){

         return (noOfTickets)->{
             return noOfTickets*400.00;
        };

    }
}

Below is the main class which is using the strategy :-

package Java8.controller;

public class Main implements ReclinerTicketStrategy {

    public Main(){

        ITicket ticketsVip = new ServiceImpl(reclinerTicketStrategy());
        System.out.println(ticketsVip.calculateFare(5));

}

    public static void main(String args[]){
        Main main = new Main();
    }


}


My question is whether is this the correct way of housing the strategy function in the interface as a default method? OR are there better ways to have it?

samedi 28 septembre 2019

Is there a way to make changes to a node application without reloading the whole application?

I built an application that downloads a pdf from a certain URL and emails it to certain people based on a certain schedule. For this, I used the request, nodemailer and node-schedule packages. I created a file called Jobs.js where all jobs are held. Its structure looks like below:

module.exports = { 
    Jobs: [
    {
        URL: http://something.com, 
        Schedule: "6 * * * *",
        Sender: me@something.com, 
        Reciever: me2@something.com, 
        Subject: "periodic update", 
        SuccessMessage: "Please find attached this pdf",
        FailedMessage: function(){
            return `Unable to send email but you can download from {this.URL}`
        }
    },
    {
        URL: http://something.com, 
        Schedule: "7 * * * *",
        Sender: me3@something.com, 
        Reciever: me4@something.com, 
        Subject: "periodic update", 
        SuccessMessage: "Please find attached this pdf",
        FailedMessage: function(){
            return `Unable to send email but you can download from {this.URL}`
        }
    }
  ]
}

Right now, I am running the application through nodemon, so when a new job is added and the file saved, it restarts the whole application automatically. I don't like this as what if the job is added when the one of them was running ! It would restart the whole app and that job would not complete. I want that when a job is added the application is aware and just adds that job to schedule. The scheduling code with node-schedule is pretty straightforward:

Jobs.forEach((job) => {
    schedule.scheduleJob(job.schedule, function(){
        downloadPDF(job); 
        sendEmail(job);                 
}); 

I am currently studying design patterns and wondering if there could be one that solves this problem. What I think I might have done correctly so far is that I have isolated what varies.

Which Design Pattern should I use for the following situation?

I need to decide how to create an elegant solution for the following problem.

  • I receive a list of "ClassA" objects.
  • I have an interface and four different implementations.
  • The interface method uses a class "ClassA".
  • ClassA has PropertyB and PropertyC.
  • Depending of the value of PropertyB I want to decide which implementation of the interface should I use for each object of the List.

I need an elegant solution but I can't think of any.

Does anybody has any idea if how can I implement this? An advice of which Design Pattern should I study?

Thanks in advance.

Stock Movement Domain Drivent Design

Hi All it is my first attempt to domain driven design so please bear with me

I have two Documents in system Good Receipt and Goods Issue. On Approval of these documents I need to update stock movement register I have following rules

On Goods Receipts Approval.

  • Update Average Cost in material Table

  • Add row with positive Quantity and new average cost in Stock movement table

ON Goods Issue Approval

  • Check Stock Balance
  • Add row in material movement with negative Quantity

Below is my design so for

     public class MaterialMovementEntity
         {
            public DateTime MovementDate { get; }
                 public int Quantity { get;  }
                 public int MaterialId { get;  }
                 public string DocInstanceType { get; }
                 public int DocInstaanceId { get; set; }
            public MaterialMovementEntity(DateTime _MovementDate
                                               , string _Quantity
                                               , string _DocInstanceType
                                               , string _MaterialID
                                               , int _DocInstaanceId)
                        {
                MovementDate = _MovementDate;
                MaterialID = _MaterialID;
                Quantity = _Quantity;
                DocInstanceType = _DocInstanceType;
                DocInstaanceId = _DocInstaanceId;
                    }


    public void Stockin()
    {
        if(quantity<0)
        //through Exception invalid quantity
        //... other rule check
              //Shoudl I place new Average Cost Calculation here 

    }
    public void StockOut()
    {
        if (quantity>0)
        {
            //through Exception invalid quantity
        }

      StockBalance=materialservice.GetCurrentStock(MaterialID);
        if(StockBalance<-1*Quantity)
        {
            //through Exception
        }

    }


 }
In Calling Service
First i prepare movement object then call Stockin And Stock Out
MovementID MaterialID MovementDate Quantity AverageCost DocInstanceID DocInstanceType
1            1          2019-09-28    50            68           1              GR
2            1          2019-09-28   -10            68           1              GI
3            1          2019-09-28    15            63.09        2              GR

My Queries

  • Where to do Average Cost Calculation is it a value object or child entity
  • As I Prepare the movement with overloaded constructor it is ready to persist. so should i remove stockin and Stockout method and move all rules in constructor?

I am not using docinstancetype as indicator of stockin and out as more docinstance type may arise that are doing stockin and out Average cost column need to be saved in material movement also. but I am confussed how to send it during object creation

Mimicking Java 8 using VBA (Excel)

I want to learn about Design Patterns and be able to apply them in Excel VBA. So to learn about patterns I bought a book that seems promising: “Head First Design Patterns”; it presents the material clearly. However, the code exercises/examples are in Java 8. VBA does not have direct counterparts for some things (e.g. “Extends”) so I need to work out how to accomplish the same/similar in VBA.

I am following along with the exercises and doing what I think parallels the Java in VBA. What I am asking here is “am I on the right track?” I know it’s a lot to ask and maybe the question is too broad, but maybe not.

There are some differences in the “Main” procedures because I haven’t completely mimicked the Java in VBA. I am more interested in the “Duck” and “Mallard” implementations.

Any suggestions are greatly appreciated.

Here’s the Java for a part of on exercise:

    public abstract class Duck {
    FlyBehavior flyBehavior;
    QuackBehavior quackBehavior;

    public Duck() {
    }

    public void setFlyBehavior(FlyBehavior fb) {
        flyBehavior = fb;
    }

    public void setQuackBehavior(QuackBehavior qb) {
        quackBehavior = qb;
    }

    abstract void display();

    public void performFly() {
        flyBehavior.fly();
    }

    public void performQuack() {
        quackBehavior.quack();
    }

    public void swim() {
        System.out.println("All ducks float, even decoys!");
    }

    public class MallardDuck extends Duck {

    public MallardDuck() {

        quackBehavior = new Quack();
        flyBehavior = new FlyWithWings();

    }

    public void display() {
        System.out.println("I'm a real Mallard duck");
    }
}

    public class MiniDuckSimulator {

    public static void main(String[] args) {

        MallardDuck mallard = new MallardDuck();
        FlyBehavior cantFly = () -> System.out.println("I can't fly");
        QuackBehavior squeak = () -> System.out.println("Squeak");
        RubberDuck  rubberDuckie = new RubberDuck(cantFly, squeak);
        DecoyDuck   decoy = new DecoyDuck();

        Duck     model = new ModelDuck();

        mallard.performQuack();
        rubberDuckie.performQuack();
        decoy.performQuack();

        model.performFly(); 
        model.setFlyBehavior(new FlyRocketPowered());
        model.performFly();
    }
}

Here’s what I’ve done in VBA:

'@Folder("SimUDuck.Objects.HeadFirst")
Option Explicit
Private Type TObject
    FlyBehavior As IFlyBehavior
    QuackBehavior As IQuackBehavior
    DuckModel As IDuckModel
End Type
Private this As TObject

Private Sub Class_Terminate()
    With this
        Set .FlyBehavior = Nothing
        Set .QuackBehavior = Nothing
    End With
End Sub

Public Property Get DuckModel() As IDuckModel
    Set DuckModel = this.DuckModel
End Property
Public Property Set DuckModel(ByVal model As IDuckModel)
    With this
        Set .DuckModel = model
    End With
End Property
Public Property Get FlyBehavior() As IFlyBehavior
    Set FlyBehavior = this.FlyBehavior
End Property
Public Property Set FlyBehavior(ByVal behavior As IFlyBehavior)
    Set this.FlyBehavior = behavior
End Property
Public Property Get QuackBehavior() As IQuackBehavior
    Set QuackBehavior = this.QuackBehavior
End Property
Public Property Set QuackBehavior(ByVal behavior As IQuackBehavior)
    Set this.QuackBehavior = behavior
End Property

Public Sub performFly()
    this.FlyBehavior.Fly
End Sub
Public Sub performQuack()
    this.QuackBehavior.Quack
End Sub

Public Sub Swim()
    'todo
End Sub
Public Sub Display()
    this.DuckModel.Display
End Sub

'@PredeclaredId
'@Folder("SimUDuck.Models.HeadFirst")
Option Explicit
Private Type TModel
    Display As String
End Type
Private this As TModel
Implements IDuckModel
Private Sub IDuckModel_Display()
    Debug.Print this.Display '"I'm A Mallard Duck"
End Sub

Public Function CreateDuck(ByVal duck As DuckObject) As IDuckModel
    With duck
        Set .FlyBehavior = New FlyWithWingsBehavior
        Set .QuackBehavior = New QuackBehavior
    End With
    With New MallardDuckModel
        .Display = "I'm A Mallard Duck"
        Set CreateDuck = .Self
    End With
End Function
Public Property Get Self() As IDuckModel
    Set Self = Me
End Property
Public Property Get Display() As String
    Display = this.Display
End Property
Public Property Let Display(ByVal value As String)
    this.Display = value
End Property

Public Sub MainDuck()
    Dim duck As DuckObject
    Set duck = New DuckObject
    With New MallardDuckModel
        Dim model As IDuckModel
        Set model = .CreateDuck(duck)
    End With
    With duck
        Set .DuckModel = model
        .performFly
        .performQuack
        .Display
        Dim FlyBehavior As IFlyBehavior
        Set FlyBehavior = New FlyRocketPoweredBehavior
        Set .FlyBehavior = FlyBehavior
        Dim QuackBehavior As IQuackBehavior
        Set QuackBehavior = New SqueakBehavior
        Set .QuackBehavior = QuackBehavior
        .performFly
        .performQuack
        .Display
    End With
    Set duck = New DuckObject
    With New ModelDuckModel
        Set model = .CreateDuck(duck)
    End With
    With duck
        Set .DuckModel = model
        .performFly
        .performQuack
        .Display
    End With
End Sub

Problem with desgin new app ios by xamarin

We have a problem in the application of ios by language xamarin problem in the design has been lifting the application and the image splash excellent and also login the rest of the application very bad pictures of the survivor of quality and lines cut with it on Android excellent

In a modular laravel application, What would be the right place for model-model relation logic?

Let's say we have a User module and Order module, what would be the right place to put the user-order relation logic? Should it be in its own module, or just in one of the above?

vendredi 27 septembre 2019

Subclasses or Additional fields in the base class for Identification

I am developing a game which has all sorts of Entities. An Entity can have name, image, xposition, yposition etc. Also, there can many types of entities such as:

  • The entity may or may not be a coin (for point collection) - star
  • The entity may or may not allow the ball to pass through - Permeability
  • The Entity may or may not be throne (which will burst the ball) - Enemy

Now if I need to check if the ball is colliding with the entity is permeable or not, if it is a coin or not , if it is an Enemy or not.

In this kind of situation, is it better to have a just one class with all the above-mentioned fields (name, xposition, yposition..) + boolean fields such as isCoin, isPermeable, isEnemy?

OR

A subclass derived from base class Entity for Coin, Permeability and Enemy?

Note - At this stage, I can't think of any additional thing the coin subclass, or the enemy subclass will be doing. In a sense, it is more for identification, not so much for adding extra functionality to the subclass.

Thanks

Design of an auditable system which doesn't require complex diffing on save

We're currently trying to design a simple module for our system in order to make it auditable, but we're not sure on what the best strategy is. We want to try and nail it as early as possible because after the application goes live, migrating all the data to a different strategy could be a kerkuffle.

Strategy 1 – Our current choice

The system we are currently experimenting with consists in creating a new record every time an update is made and when querying, simply get the ones with the latest created_on timestamp. In the case that we have parent-child relationship and the child is to be updated, we would just update the child, not the parent. When querying those, we would apply the same strategy for every dependant relationship.

Strategy 2 – not so fond of it

Another strategy we have thought of would be to have two columns in each table, a valid_from and a valid_to timestamps. Every time we update a record, we would populate the valid_to to the previously valid record, and leave the current one with an empty value. We would follow a similar fetching strategy as the previous case.

To wrap up, I want to highlight that the main reason why we don't stick with strategy 1 is because in order to save the data, it requires us to go through a fairly complex diffing process which we're not fond of. Every time the frontend calls our API with a new payload we fetch the latest aggregate (parent + children + grandchildren, etc), do a full diff and identify what to update.

So my question to you folks is, have you used any other auditing strategies your proud of and would like to share?

jeudi 26 septembre 2019

Does Inheritance contradict Dependency Inversion Principle

The dependency Inversion principle says that (Head First Java):

  • Depend upon abstractions. Do not depend upon concrete classes.

What does it mean with respect to inheritance? As a subclass depends on concrete class.

I am asking for a case when say - There is an interface Bird (doesn't have fly method as some birds cant fly), which represents all Non-Flying Birds. So I create a class - NonFlyingBird which implements Bird.

Now I want to make a class for Birds that can fly. As NonFlyingBirds and FlyingBirds have the same attributes I extend the FlyingBirds from NonFlyingBirds and Implement Flyable to give it flying behavior.

Do Doesn't it break the dependency Inversion principle as FlyingBirds is extending from a concrete class NonFlyingBirds?

interface Bird {   // Represents non Flying birds

    void getColor();
    void getHeight();
    ...
 }



class NonFlyingBird implements Bird {
     void getColor();
     void getHeight();
      ...
  }


class FlyingBird extends NonFlyingBird implements Flyable { // Does it break Dependency Inversion principle by extending concrete NonFlyingBird class? 

    Flyable fly;
    ...
  }

Note - The only reason I am extending is because the FlyingBird has the same attributes and methods as NonFlyingBird + the flying behaviour. So it kind of makes sense to reuse code by inheritance.

Is wrong to use a Mediator as something looks like a Facade?

As a Way to decouple my Presentation from my Application, I searched for many samples and ways trying to find the right approach.

After studied a little about the sample from Mathew Renze here https://github.com/matthewrenze/clean-architecture-demo and Jason Taylor here https://github.com/JasonGT/NorthwindTraders, I see myself between a few questions, but until now, without answers.

I tried to create a clean app (gathering knowledge from Clean Architecture's book) but sometimes I just get confused.

Now, my question is: Isn't my Mediator a Facade pattern? First, let me explain how did I created my classes:

In-time: I'm using the Mediatr to create the Mediator Pattern.

I have a controller wich is injected with the mediator:

public class CategoryController : Controller
{
    private readonly IMediator _mediator;

    public CategoryController(IMediator mediator) => _mediator = mediator;

    [HttpGet]
    public ActionResult List()
    {
        var request = new GetCategoriesRequest();

        var response = _mediator.Send(request).Result;

        var viewModel = new List<CategoryViewModel>();

        foreach (var category in response)
        {
            var categoryViewModel = new CategoryViewModel
            {
                Id = category.Id,
                ParentId = category.ParentId,
                Name = category.Name,
                Uri = category.Uri
            };
            viewModel.Add(categoryViewModel);
        }

        return View(viewModel);
    }
}

and the Handler has this code

public class GetCategoriesHandler : RequestHandler<GetCategoriesRequest, List<GetCategoriesResponse>>
{
    private readonly IDocDevsDbContext _context;

    public GetCategoriesHandler(IDocDevsDbContext context)
    {
        _context = context;
    }

    protected override List<GetCategoriesResponse> Handle(GetCategoriesRequest request)
    {
        var categories = _context.Categories.AsQueryable();
        if (request.Id > 0)
            categories = categories.Where(cat => request.Id == 0 || cat.Id == request.Id);
        if (!string.IsNullOrWhiteSpace(request.Name))
            categories = categories.Where(cat => !string.IsNullOrWhiteSpace(cat.Name) && cat.Name.ToLower().Equals(request.Name.ToLower()));
        if (!string.IsNullOrWhiteSpace(request.Uri))
            categories = categories.Where(cat => !string.IsNullOrWhiteSpace(cat.Uri) && cat.Uri.ToLower().Equals(request.Uri.ToLower()));

        var response = new List<GetCategoriesResponse>();
        foreach (var category in categories)
        {
            var res = new GetCategoriesResponse
            {
                Id = category.Id,
                ParentId = category.ParentId,
                Name = category.Name,
                Uri = category.Uri
            };
            response.Add(res);
        }

        return response;
    }
}

Inside my Handler class I'm executing the rules and validations. I know this is just a Query but in few Commands I can have something like: - Invoice Order (database) - Lower Stock (database) - Generate Sale Notification (service) - Increase Buyer Milestone (database) - Commit Changes

So, should I have all those rules on the mediator as private methods? Or should I have classes for every step (invoice, stock, milestone) and make my mediator work as a Facade? OR AM I TOTALLY WRONG ABOUT EVERYTHING (it could happen more often then I want :lol:).

Any tips, hints, blogs, discussion will make me a lot happier guys.

Thanks

how to validate two fields in separate classes?

I am trying to validate two fields in separate @ConfigurationProperties classes. Properties in these classes are set by spring container. I can't merge these two classes because of application design. How can achieve this validation?

I tried Observer pattern but its for one-to-many not many-to-one.

Trying to validate if multipleQueuesEnabled is set to false then url should not be null and urls should be null. And if multipleQueuesEnabled is set to true then urls should not be null and url should be null.

First Properties Class:-

@ConfigurationProperties(prefix = "aws.sqs")
@Validated
public class SqsProducerStarterProperties

    @NotNull
    private boolean multipleQueuesEnabled;


    public boolean isMultipleQueuesEnabled() {
        return multipleQueuesEnabled;
    }

    public void setMultipleQueuesEnabled(boolean multipleQueuesEnabled) {

        this.multipleQueuesEnabled = multipleQueuesEnabled;
    }

}

Second Properties Class:-

@ConfigurationProperties(prefix = "aws.sqs.fifo")
@Validated
public class SqsFifoStarterProperties {

    private Map<String, String> urls;

    private String url;

    @Override
    public Map<String, String> getUrls() {
        return urls;
    }

    public void setUrls(Map<String, String> urls) {
        this.urls = urls;
    }

    @Override
    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
       this.url = url;
    }
}

Any thoughts about how can I achieve validation in above scenario. Properties will be set by spring container so I don't have control over it.

How to avoid type checking

I am working on a project which has some GameObject. It can be anything a ball, a coin, a plant. And I have to pass the list of GameObject to some other class which renders the objects on-screen.

The GameObjects can be moveable and non-moveable. Some GameObjects can allow passing objects through them(Pervious) and some not. Some GameObjetcs have thrones (which might explode the ball) and some not. Some GameObjects are coins which are collected when the ball hits them.

So I did this -

Class GameObject{

// All things common to both entities. 
// Feilds - hasThrones, canPassthrough, isCoin
...
...
}

Class MovingGameObject extends GameObject implements Moveable{
    moveable logic;
...
...
}

Class FlyingGameObject extends GameObject implements Flyable{
    Flyable logic;
...
...
}

And I now have a List < GameObjects >.

Problem When I am making the moveable objects move, I am doing something like:

if gameobject is an instance of MovingGameObject{
        // do something
}

if gameobject is an instance of FlyingGameObject{
        // do something
}

I know this is bad code. How do I refactor it to not use type checking?

One way I can think of is using lists. But That's not really a way as now what if I want a swimming object now? Then I do have to store in a new list for swimming objects.

Thanks

Storing Handler's Object in PubSub?

I came to JS from c#, so I am using class syntax/architecture.

My "handler" functions(that I want to store in Pub/Sub object), work with object's parameters(passed in the constructor) in which they are encapsulated.

But they are being stored and called as anonymous functions of undefined object.

So I came up with making PubSub's subscribe method require object, then bind Object to handler, using "handler.call(Object, args)". This allows my Object to change it's parameters in response to some event. May be it is better to use Observer pattern in this situation?

class EventBus
{
    constructor()    {
        this.subscribers = {};
    }

    subscribe(subName, object, handler)    {
        this.subscribers[subName].push({object: object, handler: handler});
    }

    publish(subName, eventArgs)    {
        const sub = this.subscribers[subName];
        sub[0].handler.call(sub[0].object, (eventArgs));
    }
}

My renderer object, which functions I want to call, using events:

class Renderer
{
    constructor(tileSize)
    {
        this.tileSize = tileSize;
    }

    render(tile)
    {
        ctx.fillText(this.getTileGraphics(tile), tile.x*tileSize, tile.y*tileSize);       
    }

    getTileGraphics(tile){...}
}

//and this is my html code :

<script>
    const eventBus = new EventBus();
    var renderer = new Renderer(tileSize=32);     
    eventBus.subscribe("OnTileRender", renderer, renderer.render);
<script>

So is my approach fine and I can continue with this, or it's better using Pub/Sub for handlers, not dependant on outer function's parameters?

Spring mvc: One step view or Two Step View?

I am reading famous Fauler's book "Enterprise application patterns" And I can't understand difference between One step view(top part) and Two Step View(bottom part)

enter image description here

I read all text but I understood only one thing

In case of two step view I have 1 additional intermediate logical view. It is really not clear for me why do I need it. In my practice I use spring - mvc for web application. Could you explain which pattern is used inside this framework? Could I choose it ?

mercredi 25 septembre 2019

What is the name of the design pattern used by this validation code?

I have found it convenient to implement validation directly in the risen exception classes like:

>>> class IsNoneError(ValueError):
...     @classmethod
...     def validate(cls, value):
...         if value is None:
...             raise cls
... 
>>> IsNoneError.validate(1)
>>> IsNoneError.validate(None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in validate
__main__.IsNoneError

As there is nothing new under the sun I guess someone had already invented this exception-validator class pattern. What is its name then, which I may use talking to other pythonists to be understood?

Also, what are possible drawbacks of this design pattern?

Implementing the Options pattern with a class injected during ConfigureServices - AddScoped

I have a small class to obtain a series of information about my user on several of my MVC applications. A minimal reproducible example would be:

public class InformationGetter
    {
        public string GetUserInformation(string connectionStr, string storedProcedureName, int userId)
        {
            // Do SQL work
            return info;
        }
}

I'm injecting it on the ConfigureServices step using

services.AddScoped<InformationGetter>

And then in my classes I simply call it from the DI.

Now, obviously the connectionStr and storedProcedure only changes per application but right now I'm passing it as parameter.

I've tried to make those parameters public and configure it using services.Configure but when I call it from my controllers, I get null values.

            services.AddOptions();
            services.Configure<InformationGetter>(options =>
            {
                options.ConnectionString = Configuration.GetSection("Model").GetSection("ConnectionString").Value;
                options.StoredProcedureName = "prInformationGetter";
            });

I'm not sure if the reason why this is failing it's because I'm missing an interface on my original class or am I failing to understand this concept.

I've also thought on doing something like services.AddInformationGetter(options => {}) but my understanding is that this pattern is to implement middlewares and not DI specifically.

I tried checking the documentation (docs.microsoft.com) but I got even more confused.

how to model this invoice requirements

In some business domain, I received invoicing requirements as follows:

+ Invoice Items are of two types: a service or a fee.
    - Invoice Service Item is taxable. fee is not.
+ Invoice Items (services and fees) cost is calculated in two manners: 
    - As a whole: the service or fee has a fixed cost.
    - By Individual: the cost is multiplied by Individuals count.

I’ve been reading about design patterns, domain driven design, inheritance and polymorphism, and I wanted to practice what I learnt in this side greenfield project. I want to come to a model for the Invoicing sub domain, that captures the domain ubiquitous language. I’ve come to this model, but It doesn’t feel right! model

Predict Series using python

In a coding Problem I need to find the pattern in below given series. Could anyone can help me on that?

1 1 2 2 4 2 6 _ _ _ _ _ _

Microsoft Azure Service Bus: request-response-based operations

Can anyone post a sample code in Node.js to acheive Request Response pattern using Azure Service Bus.

Just to summarise my problem I have two systems that cannot communicate directly with each other via API or other means, so I need to communcate via Azure Service Bus . The two system should communicate using request response pattern with AMQP. I have found something clearly states here in this link http://www.cloudcasts.net/devguide/Default.aspx?id=13051

Also find some documentation here https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/service-bus-messaging/service-bus-amqp-request-response.md

But I may need its sample code in Node.js as Iam new to Node.js

Java: How to replace multiple nested if-else statements with a more maintainable design

I need to execute a different action doAction1(), doAction2() ... depending on the value and/or type of some variables and return value of some functions. All combinations could be possible, in principle.

The quick solution is to test all combinations within nested if-else statements but the resulting code is quite ugly and difficult to maintain and extend (in case for instance I have new conditions to test for). I include some sample code below. I am using Java SE 8:

public static boolean myFunct () {
    return true;  // hardcoded, it could also return false
}

public static void main(String[] args) {

    int x = 1;  // hardcoded, it could also be =2
    Object o = new String();  // hardcoded, it could also be an Integer

    // here I begin to test to decide which action to execute
    if (x == 1) {
        if (o instanceof String) {
            if ( myFunct() ) {
                // do this if x==1 AND o is a String AND myFunct() returns true
                doAction1();  
            }
            else {
                doAction2();
            }
        }
        else if (o instanceof Integer) {
            if ( myFunct() ) {
                doAction3();
            }
            else {
                doAction4();
            }
        }
    }
    else if (x == 2) {
        if (o instanceof String) {
            if ( myFunct() ) {
                doAction5();
            }
            else {
                doAction6();
            }
        }
        else if (o instanceof Integer) {
            if ( myFunct() ) {
                doAction7();
            }
            else {
                doAction8();
            }
        }
    }
}

private static void doAction8() {
    // do some work...
}

private static void doAction7() {
    // do some work...
}

private static void doAction6() {
    // do some work...
}

private static void doAction5() {
    // do some work...
}

private static void doAction4() {
    // do some work...
}

private static void doAction3() {
    // do some work...
}

private static void doAction2() {
    // do some work...
}

private static void doAction1() {
    // do some work...
}

I read about a RuleEngine design pattern that could elegantly apply to this kind of cases and replace the nested if-else statements but cannot really find how to implement it for my case.

Thank you in advance for your recommendations.

Combining rows if text is same before certain character in R

I have a data frame similar to this. I want to sum up values for rows if the text in column "Name" is the same before the - sign.

enter image description here

mardi 24 septembre 2019

Should i enforce the splitting of single file components in Vue.js 2?

As far as i know, the Way to go using Vue are the single file components. I literally use them every time as a single file. Someone now wants me to apply the separation of concerns (S in SOLID) and use the single file components as described on the official page on every single file component. This means, that a file like this becomes three:

<!-- my-component.vue -->
<template>
  <!-- HTML here -->
</template>

<script>
export default {}
</script>

<style>
.my-class {}
#id {}
</style>

Will become this:

<!-- my-component.vue -->
<template>
  <!-- HTML here -->
</template>
<script src="script.js"></script
<style src="style.css"></style>
// script.js
export default {}
/* style.css */
.my-class {}
id {}

In my opinion is this just a bloated way to apply a pattern that will cause more confusion. There are 3 Files instead of one for every single component.

Now my question is: Am i right, assuming that Single File Compoents are still the way to go and the splitting of them is only a good way to go if there are many lines of code (then you've done something wrong anyway..)? I also need to know if this way is scalable or does it get annoying, crawling through many files for one component? Or do I take something completely wrong?

I really need facts, so please don't (only) argue on opinions. Thank you in advance.

What pattern can I use to avoid instancing unnecessary blocks from pipeline?

My ASP.NET Core application is using our self-designed pipelines to process requests. Every pipeline contains 1+ blocks, and the number of blocks have no any limit. it can be up to 200+ blocks in real instance, the pipeline will go through all blocks by a sequence from a configuration, like:

Pipeline<DoActionsPipeline>().AddBlock<DoActionAddUserBlock>().AddBlock<DoActionAddUserToRoleBlock>()... 

Like above example(just an example), and there are 200+ blocks configured in this pipeline, the blocks could be DoActionAddUserBlock, DoActionAddUserToRoleBlock, DoActionAddAddressToUserBlock, and so on. many actions are mixed in one pipeline. (Please don't ask why mix them, it's just an example, it doesn't matter to my question.)

For this example, in each block, we will check the action name first, if match, then run logics. but this is pretty bad, it has to instance all blocks and go throgh all of them to get a request done.

Here is sample code, not very good, but it shows my pain:

public class DoActionAddUserBlock : BaseBlock<User, User, Context>
{
    public override User Execute(User arg, Context context)
    {
        if (context.ActionName != "AddUser")
        {
            return arg;
        }

        return AddUser(arg);
    }

    protected User AddUser(User user)
    {
        return user;
    }
}

public abstract class BaseBlock<TArg, TResult, TContext>
{
    public abstract TResult Execute(TArg arg, TContext context);
}

public class Context
{
    public string ActionName { get; set; }
}
public class User
{

}

I want to avoid instancing blocks by conditions, I think it should be in pipeline-configuration level. how can I reach this? Attributes? or something others.

[Condition("Action==AddUser")] // or [Action("AddUser")] // or [TypeOfArg("User")]
public class DoActionAddUserBlock : BaseBlock<User, User, Context>
{
    public override User Execute(User arg, Context context)
    {
        return AddUser(arg);
    }

    //...
}

MVC design pattern and timers

I am tring to understand MVC design pattern but using timers in the design is a little bit confusing.

I have an application that show the webcam on a gui. The model contains the webcam logic (initialize, get_frame ecc) The view contains the widgets (I am using PyQt but the framework is not the problem here) that show the image.

I am using a timer (Qt timer) to call update_frame every 1/30 s. update_frame calls model.get_frame to get the new image.

Should the timer belonging to the view ? What if get_frame waits the image to be ready ( like a blocking function ) and I want to update the image as soon as a new image is ready ? Where do I put the infinite loop ?

How to best implement transaction around business process in Java Spring Boot Application

I have looking for the best approach to handle error handling and retries for the following business feature.

begin business transaction

  1. User logs unto a website and triggers next step by clicking a button

  2. Book a venue : this calls a spring boot microservice which insert record to secure booking

  3. Send confirmation letter user

    • calls multiple springboot micro-services to fetch letter details and aggregates the data

    • generate letter by calling pdf generation microservice

    • sends letter by calling a external API

    • Log an event using a messaging queue

finish business transaction

The above flow is implemented in a restful endpoint The steps is called from a Java method, but steps 2 and 3a,b and c are delegates to sub methods.

My question is, what is the best approach to achieve a transaction like operation for this functionality, so that : - if booking venue (db insert) fails the letter is not sent out - if the notification fails, the database insert should be rolled back

I know about the @Transactional https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/transaction/annotation/Transactional.html

But, I will like a few ideas of pattern for this.

All the methods invoked have exception handling using @ControllerAdvice

Is there a Java @Transactional wrapper used to perform the following events - ( database operation, file reads, asynchronous call, messaging etc) as an atomic operation

Any ideas will be appreciated

DateTimeFormatter pattern postfixed by numeric literal only works if a space is present in the pattern

I saw some similar problems, and that bugs were already fixed regarding issues like this. Now I wonder if I am doing something wrong, or this case is still not covered. My problem is that I have to parse a date followed by zeroes, so the pattern would be yyyyMMdd'0000'. However it fails, but if I put a space in it works: yyyy MMdd'0000'

    DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("yyyy MMdd'0000'").toFormatter().withResolverStyle(ResolverStyle.STRICT);
    System.out.println(formatter.parse(formatter.format(ZonedDateTime.now())));
    formatter = new DateTimeFormatterBuilder().appendPattern("yyyyMMdd'0000'").toFormatter().withResolverStyle(ResolverStyle.STRICT);
    System.out.println(formatter.parse(formatter.format(ZonedDateTime.now())));

I know that I could replace the literal part with the hours and minutes patterns, and it would work, but I would like to use it as a validator mechanism on the input, so it should fail on other values, without additional coding. I tried it with Oracle JDK 1.8.0_221 and OpenJDK 13+33

Thanks!

Using a message broker with end user clients directly

I want to find a way to implement push messages from a server to multiple end user clients with the same message.

One of the options I found was to use a message broker and use it to implement the pub/sub pattern. What I'm not sure about is what supposed to be considered a consumer in such a scenario.

What I thought that the general architecture is when using a message broker is:

End user clients <----> Message broker <---> Server (The clients and server can also speak to one another on things that are not related to topic messages)

And the process I at least that is supposed to happen is this:

1) The end user client registers to a specific topic by sending an initial message directly to the message broker.

2) The server got a message about a topic which he wants every end user will get, so it adds a message to the topic.

3) The message broker instantly sends the message to all the end users by itself without the usage of other push message services like SignalR, Pusher etc. (without the usage of them meaning that it might use it behind the scene, but the developer doesn't actually program the sending of the messages).

After that I heard that the consumer is not supposed to be end user clients, but other servers?

Is my description of the process correct? Or is it something else?

What's wrong with composition and aggregation?

It's pretty strange to see all those answers about composition/aggregation/association. Who/What is the source of those notions?

https://www.geeksforgeeks.org/association-composition-aggregation-java/

wikipedia?!?! https://en.wikipedia.org/wiki/Object_composition

https://softwareengineering.stackexchange.com/questions/61376/aggregation-vs-composition

and finally my lovely stackoverflow (at least I glad that answers were not marked as verified) What is the difference between association, aggregation and composition? What is the difference between aggregation, composition and dependency?

There is a great book "Design Patterns" (GoF) https://en.wikipedia.org/wiki/Design_Patterns

It describes two most common techniques for reusing functionality in object-oriented systems: 1) class inheritance (is-a) 2) object composition (has-a)

"Object composition is an alternative to class inheritance. Here, new functionality is obtained by assembling or composing objects to get more complex functionality."

"Composition" is a very descriptive term to express relationship between objects unlike "Association". Why all those sources above use term "Composition" in the wrong way?!

Let's go further.

Objects could be composed in two ways: 1) Aggregation 2) Acquaintance

"Consider the distinction between object aggregation and acquaintance and how differently they manifest themselves at compile- and run-times. Aggregation implies that one object owns or is responsible for another object. Generally we speak of an object having or being part of another object. Aggregation implies that an aggregate object and its owner have identical lifetimes."

aggregate object and its owner have identical lifetimes!!!

"Acquaintance implies that an object merely knows of another object. Sometimes acquaintance is called "association" or the "using" relationship. Acquainted objects may request operations of each other, but they aren't responsible for each other. Acquaintance is a weaker relationship than aggregation and suggests much looser coupling between objects."

"It's easy to confuse aggregation and acquaintance, because they are often implemented in the same way. In Smalltalk, all variables are references to other objects. There's no distinction in the programming language between aggregation and acquaintance. In C++, aggregation can be implemented by defining member variables that are real instances, but it's more common to define them as pointers or references to instances. Acquaintance is implemented with pointers and references as well."

Guys, please, help me to figure out what's going on here...

Chain of resposibility in Java

currently, I'm trying to understand the chain of responsibility, but there's some piece of code in it, that I can't understand at all. Let's start from begining.

For first, I have to create an interface:

public interface ChainLink {
void setNextChain(ChainLink link);
void process(Model model);
}

Next step is creating the pojo class:

public class Model {

private int number;

public Model(int number) {
    this.number = number;
}

public int getNumber() {
    return number;
 }
}

Now, I have to create three separated classes, for each process:

First is for negative number

public class NegativeNumber implements ChainLink {

ChainLink link;
@Override
public void setNextChain(ChainLink link) {
    this.link = link;
}
@Override
public void process(Model model) {
    if (model.getNumber() < 0){
        System.out.println("Given number is "+model.getNumber()+" and it's negative");
    }else {
        link.process(model);
    }
 }
}

Second one is for number equals to 0

public class ZeroNumber implements ChainLink {
ChainLink link;
@Override
public void setNextChain(ChainLink link) {
    this.link = link;
}

@Override
public void process(Model model) {
    if (model.getNumber() == 0){
        System.out.println("Given number is equal to 0");

    }else {
        link.process(model);
    }
 }
}

And the third one, for possitive numbers

public class PositiveNumber implements ChainLink{
private ChainLink link;
@Override
public void setNextChain(ChainLink link) {
    this.link = link;
}

@Override
public void process(Model model) {
    if (model.getNumber() > 0){
        System.out.println("Given number is "+model.getNumber()+" and it's positive");

    }else {
        link.process(model);
    }
 }
}

Now, I have to chain it up on Main class.

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    ChainLink negativeLink = new NegativeNumber();
    ChainLink zeroLink = new ZeroNumber();
    ChainLink positiveLink = new PositiveNumber();

    negativeLink.setNextChain(zeroLink);
    zeroLink.setNextChain(positiveLink);

    Scanner scanner = new Scanner(System.in);

    while (true){
        int number;
        System.out.println("Enter the number");
        number = scanner.nextInt();
        negativeLink.process(new Model(number));
    }
 }
}

So the thing that I'd like to make sure about, is how the process class are working. So in first, we're creating the instance of our interface, and then overriding methods in it. And now I'm not sure if I understand how "setNewChain" method works, is it just about taking the instance of our interface which is "link" (not this in method parameter) and overwriting it with another interface process? (in this case, if number is not less than 0, then we have to call the another chain which is "ZeroNumber" because this one, can't do much here, because number is >=0 and so on.

Creating polygon shapes using Nazca

I am new in python and trying to create patterns and export them to .gds, or .dxf file format. I am using predefined Nazca shapes but I have some problems to create square and rectangle. 1) Square rotated like a diamond and couldn't find how to make it square. (Fig. 1 Supposed to be square, not diamond) 2) Tried to generate rectangle in different aspect ratios by adding squares one after another but couldn't find how to generate a rectangle without adding squares. (Fig. 2 Supposed to be rectangle)

import nazca as nd

with nd.Cell('square') as hole:
    square_shape = nd.geometries.circle(radius=25, N=4)
    nd.Polygon(points=square_shape).put(0)

hole.put(array=[200, [100, 0], 200, [0, 100]])
hole.put(array=[200, [100, 0], 134, [0, 150]])

nd.export_gds(filename= 'squtest.gds')

lundi 23 septembre 2019

How do I design an runtime-assign-valued enum?

class MyFileOperation
{
    int iUserReadPos;
    string sArticleBuffer;
    string sExtraInfo;
    enum Offset
    {
        ofsUserReadPos = 0, ofsArticleBuffer, ofsExtraInfo
    };
public:
    MyFileOperation(string filename)
    {
        /*By reading the file, I know the values of iUserReadPos, sArticlBuffer and sExtraInfo*/
        /*Then I want to assign the values Offset items*/
        ofsUserReadPos = 0;
        ofsArticlBuffer = sizeof(iUserReadPos);
        ofsExtraInfo = sizeof(string::size_type) + sArticlBuffer.length();
    }
    void MoveTo(Offset ofs)
    {
        f.seekp(ios::beg+ofs);
    }

    void SomeUsingOfMoveTo()
    {
        MoveTo(ofsExtraInfo);
    }
};

I want to assign valus for the Offset items, and directly use these values conveniently. Of course this code can't compile. I wonder if there is new c++ features such as enum class or other design can solve this problem.

Factory pattern desgin c#

I got project to do and I need to create program that creates file for specific embosser machine (machine that creates plastic bank card for example). I have 3 embosser machine and all of them creates different file. Every file contains card number, last and first name, address, etc. Difference between files is that they contains specific characters for delimiter.

I want to implement this project with factory pattern.

For simplicity let say that I have these embossers: EmbosserA, EmbosserB and EmbosserC.

This is how I created files in my project, and I need advice is this good way.

public enum eType
{ 
     A,
     B,
     C
}

public interface IEmbosser
{
     eType EmbosserType {get;}
     List<EmbosserData> GetEmbosserData();
     void CreateEmosserFile(string path);
}

public class EmbosserA : IEmbosser
{
     public eType EmbosserType => eType.A;
     public List<EmbosserData> GetEmbosserData()
     {
       //Implementation
     }

     public void CreateEmbosserFile(string path)
     {
       //Implementation
     }
}

public class EmbosserB : IEmboser { //... }

public class EmbosserC : IEmboser { //... }

And factory creator

public class EmbosserCreator
{
    public static IEmbosser GetEmbosser(eType EmbosserType)
    {

        switch (EmbosserType)
        {
            case eType.A:
                 return new EmbosserA();
            case eType.B:
                return new EmbosserB();
            case eType.C:
                return new EmbosserC();
            default:
                throw new Exception("...");
        }
    }
}

For data I thought to create abstract class EmbosserData which inherit class EmbosserAData, EmbosserBData, EmbosserCData.

For example:

public abstract class EmbosserData
{
     public string cardNumber {get; set;}
     public string address {get; set;}
     //...
}

public class EmbosserA : EmbosserData
{
     public string IDNumber {get; set;}
     //...
}

public class EmbosserB : EmbosserData
{
     public string Phone {get; set;}
     //...
}

public class EmbosserC : EmbosserData
{
     //other fields
}

My question, is this good approach for my project? If you have any advice for other implementation feel free to write.

java- how to multiple(indefinite) asynchronous callbacks. is there a desing pattern or somehing?

I am not sure if I asked right in title but here is the problem. I have a class that does a jop asyncronously and also has to run on Swing UI thread. like this


SwingUtilities.invokeLater(() -> {
  myobj.dosomething(()->{

   SwingUtilities.invokeLater(() -> {
     myobj.dosomething(()->{
       //here it needs to repeat this again and again. 
       //for an indefinte number of times. So it is hedious to reapat this code
       //for few times  and impossible to make it dynamic based on user input. 

     });
    });
   });
});

Compiling revealing module pattern

I'm writing an app that is using a revealing-ish module pattern. I'm using Gulp for compilation, so I can set the order of compilation. Aside from some jQuery, there aren't any other frameworks or libraries at play.

I'm trying to break the files up:

  • The site's main JS file,
  • one for a respective feature's general settings,
  • one for the feature's UI,
  • and another for the feature's data.

I'm trying to namespace as follows:

myApp
myApp.dashboard
myApp.dashboard.ui
myApp.dashboard.data

The problem is the namespace nesting because (for example) my dashboard.ui.js file is referenced in dashboard.js

I receive Uncaught TypeError: Cannot set property 'ui' of undefined when it tries to access the myApp.dashboard.ui.

I've tried every order of compilation I can think of. I'm guessing there's something wrong with my pattern but I'm not sure what. Here's an example of the code.

// app.js

let myApp = (function(){

    const $els = {
        menu: $('#menu')
        // etc.
    };

    const eventHandlers = () => {
        //site-wide click event handlers (for example)
    };

    const utils = {
        // utility functions
    };

    const init = () => {
        // set some site variables, etc.
        eventHandlers();
    };

    return {
        init,
        utils
    };
})(myApp || {});

//dashboard.js

myApp.dashboard = (function (parent){

    // ! need access to the UI
    let ui = parent.dashboard.ui;

    const eventHandlers = () => {
        ...
    };

    const init = () => {
        eventHandlers();
    };

    return {
        init
    };

})(myApp || {});

//dashboard.ui.js

myApp.dashboard.ui = (function (parent){

    // ! need access to the DATA
    let ui = parent.dashboard.data;

    const htmlTemplate = (content) => {
        return `<h1>${content}</h1>`;
    };

    const init = () => {
        eventHandlers();
    };

    return {
        init
    };

})(myApp || {});

//dashboard.data.js

myApp.dashboard.data = (function (parent){

    const getData = (dataObject) => {
        // do XHR look up
        // call setter, etc.
    };

    const parseForm = () => {
        // collect form data.
    };

    return {
        parseForm
    };

})(myApp || {});

Can someone please provide some guidance on how to correct my code so that I can nest the UI and Data portions under the myApp.dashboard namespace and have the three accessible to one another?

If this pattern is way off base, pointers on how to improve it are also welcome.

Containerising application - design pattern

I am working on containerizing a bunch of applications that have the following structure at a high level:-

  1. Read from a DB/File system
  2. Extract the data or do some parsing (Business logic)
  3. Write back the crunched data to datastore.

Let name these 3 steps as s1, s2, and s3.

What is the best way to have a balance between code reuse and making the solution overly complexity? In other terms what is the best design pattern/practice to implement this kind of solutions that are industry-accepted?

Few approached that I could pen own are as follows:-

  1. Separate pods for each application with one container each, having s1, s2, and s3 as part of same code.
    • Benefits: Simple and compact code base. No interprocess/pod communication
    • Limitation: No Code reuse
  2. Separate pods for each application, with each pod having 3 container doing separate functionality as s1, s2, and s3.
    • Benefits: Code reuse.
    • Limitation: Interprocess communication may increase processing latency.
  3. Separate group of pods for s1, s2, and s3 says sg1, sg2, and sg3 respectively running independently. From an application perspective, we create a new pod that talks to the mentioned 3 pod groups to get work done.
    • Benefits: Code reuse.
    • Limitation: Interprocess communication may increase processing latency. Also, maintaining pod groups is an add-on overhead. Increase in complexity

Request to suggest any other alternative if suitable.

Why should we create one interface for this configuration class?

My understanding of interfaces is that they define contracts and classes implementing the interface sign the contract. In that case, we may design classes to depend on the contract and not on the concrete implementation. This has advantages like reducing coupling, enabling polymorphism, and so forth.

Now I have came across one use of interfaces which I didn't get. This is from the ASP.NET Core documentation, regarding configuration. In particular, in the page, one is talking about setting up MongoDB with ASP.NET Core.

They basically define a class and an interface like this:

namespace BooksApi.Models
{
    public class BookstoreDatabaseSettings : IBookstoreDatabaseSettings
    {
        public string BooksCollectionName { get; set; }
        public string ConnectionString { get; set; }
        public string DatabaseName { get; set; }
    }

    public interface IBookstoreDatabaseSettings
    {
        string BooksCollectionName { get; set; }
        string ConnectionString { get; set; }
        string DatabaseName { get; set; }
    }
}

Then they use this as follows:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<BookstoreDatabaseSettings>(
        Configuration.GetSection(nameof(BookstoreDatabaseSettings)));

    services.AddSingleton<IBookstoreDatabaseSettings>(sp =>
        sp.GetRequiredService<IOptions<BookstoreDatabaseSettings>>().Value);

    services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

I must say I gon't get it. The objects of type BookstoreDatabaseSettings are meant to work as DTOs for the settings. They don't provide any functionality at all. So why introduce one interface in the middle?

I don't see here one usage on which one would use some other implementation. I don't see here why one is trying to decouple this, I don't see any use of polymorphism at all, and I really didn't get the point.

So why in this situation, when dealing with settings in ASP.NET Core, one uses interfaces and not the concrete class (for example BookstoreDatabaseSettings) directly?

How do I reuse JUnit test methods for different testing contexts?

Up to this point, I have been developing tests for the support of a certain application in my project. Now that I have a set of tests up and running, I need to provide support for another similar application. The result for both applications should be the same in my system, as they both produce the same actions but from different contexts. The thing is, I am looking for a way with which I could reuse the tests that I have made for the first one, without copying their code for the other test case.

I am currently using JUnit 4 under Java EE 8.

My situation goes something like this. Given a test like the one that follows:

class TestExample {
    Context context;

    @Before
    public void setUp() {
        context = new ContextA();
    }

    @After
    public void terminate() {
        context.dispose();
    }

    @Test
    public void test1() {
        context....
    }
}

abstract class Context {
    @Override
    public void dispose() {
        ...
    }
}

class ContextA extends Context {
}

class ContextB extends Context {
}

I would like to be able to do the test once for ContextA and then for ContextB.

Where to put business logic when working with mvvm

I am making a user login screen using MVVM design pattern but I am stuck when its come to implement the logic for phone number validation. I read out Rules to follow when working with mvvm (Rule no. 4) that View should not have any logic in it, Not even a simple if condition. All logic for the view happens in ViewModel.

Here is my ViewModel class.

public class LoginViewModel extends AndroidViewModel {

    private LoginRepository loginRepository;
    private HashMap<String,String> mNumberParam;
    private MutableLiveData<Boolean> isValidated;

    public LoginViewModel(@NonNull Application application) {
        super(application);
        loginRepository=LoginRepository.getInstance();
        isValidated=new MutableLiveData<>();
    }


    public LiveData<List<OtpEnterModel.Data>> enterNumberApiHit(){
        return loginRepository.enterNumberApiHit(mNumberParam);
    }


    public void onSubmitClick(String number){

        //if mobile number not enter or wrong enter show message ,and tell the view to hide other view
        if (number==null) {
            Toast.makeText(getApplication(), "Invalid mobile number", Toast.LENGTH_SHORT).show();
            isValidated.setValue(false);

        } else {
            //otherwise save mobile number in hashMap ,and tell the view to work further
            isValidated.setValue(true);
            saveNumberParam(number);
        }
    }

    //to save the mobile number in hashMap with key i.e mobile_number.
    private void saveNumberParam(String mobileNumber) {

        //if hashMap null then initialize it
        if (mNumberParam ==null) {
            mNumberParam = new HashMap<>();
        }
        mNumberParam.put(MyConstant.MOBILE_NUMBER, mobileNumber);
    }

    public LiveData<Boolean> isValidated(){
      return isValidated;
    }
}

Here is my View class.

public class EnterNumber extends AppCompatActivity implements View.OnClickListener, FragmentManager.OnBackStackChangedListener {

    //dataType
    private Context context;
    private FragmentManager manager;
    private LoginViewModel loginViewModel;

    //views
    private EditText enterMobileEDT;
    private ProgressBar progressBar;
    private Button btnNumber;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enter_number);

        manager=getSupportFragmentManager();
        context = EnterNumber.this;
        loginViewModel= ViewModelProviders.of(this).get(LoginViewModel.class);

        init();
        setListener();
    }

    //all views initialize here
    private void init() {
        enterMobileEDT = findViewById(R.id.enterMobileET);
        progressBar=findViewById(R.id.progressBar);
        btnNumber=findViewById(R.id.btn_number);
    }

    //listener for views
    private void setListener() {
        btnNumber.setOnClickListener(this);
        manager.addOnBackStackChangedListener(this);
    }

    //check for mobile number and send otp by hitting API
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_number) {
            loginViewModel.onSubmitClick(enterMobileEDT.getText().toString());
            numberValidation();
        }
    }

    //check for editText length
    public void numberValidation() {

        loginViewModel.isValidated().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {

                if(aBoolean){
                    loginApiHit();
                }
                hideShowView(aBoolean);
            }
        });
    }

    //hide and show the view based on condition
    public void hideShowView(boolean wantToShowProgress) {

        if(!wantToShowProgress){
            progressBar.setVisibility(View.INVISIBLE);
            btnNumber.setEnabled(true);

        }else {
            progressBar.setVisibility(View.VISIBLE);
            btnNumber.setEnabled(false);
        }
    }

}

How Can I move all if/else condition from View to ViewModel?

Background image pattern with hoverable effect

Do you have any idea on how to make this kind of pattern? I only have a background image like this and I want the 4 light-colored hexagons to be a link.

enter image description here

Should literals be replaced by generic interfaces

I'm writing code which is using the strategy pattern however I am unsure if I am going overboard with the amount of abstraction I'm using. I am randomly generating numbers for my application using various probability distributions such as normal distributions or uniform distributions or generating numbers constantly (not randomly at all)

The different algorithms have different literal return types, some return Ints whereas others return Floats and Doubles.

Following the interface segregation principle I created ITYPEValuePicker interfaces which each have the following definition:

public interface ITYPEValuePicker
{
    public TYPE getTYPE();
}

where "TYPE" is a specific data type such as float, int, etc.

Now my random algorithms implement these interfaces and can be used in the code

GaussianValuePicker implements IFloatValuePicker, IDoubleValuePicker

and

UniformValuePicker implements IFloatValuePicker, IDoubleValuePicker, IIntValuePicker

and

ConstantValuePicker implements IIntValuePicker, IFloatValuePicker, IDoubleValuePicker

A significant portion of my code is dependent on randomly selected values and randomly selected algorithms to select those values. My question is: is there a reason why I should not be replacing all magic numbers with these generic "IValuePicker"s and having the actual getting of any value be delegated to the the specific algorithm.

For example:

public class chicken
{
    float height;
    int age;

    public chicken(float height, int age)
    {
        this.height = height;
        this.age = age;
    }

    public boolean isSuperOld()
    {
        if (age > 99) 
        {
            return true;
        }
        return false;
    }
}

vs

public class chicken
{
    IFloatValuePicker height;
    IIntValuePicker age;

    public chicken(IFloatValuePicker height, IIntValuePicker age)
    {
        this.height = height;
        this.age = age;
    }

    public boolean isSuperOld()
    {
        if (age.getInt() > 99) 
        {
            return true;
        }
        return false;
    }
}

sorry for the contrived example, but I hope that it illustrates the delayed, almost (lazy [I'm not sure this is the correct term]?) evaluation of the different values. Is this an example of YAGNI (I understand that whether it's YAGNI or not is pretty context heavy) or is this a valid use of interfaces?

java inheritance and design patterns advises

I and doing an app in Android which can run different ML models and I want to create some classes to represent the data of the results, each ML model has it owns variables/result, for example, a classification problem has labels meanwhile other do not have them.

I want to use inheritance in java and doing something like Result as interface and father of ClassificationResult and RegresionResult so I could do:

Arraylist<Result> resultList;
ClassificationResult cr = new ClassificationResult...
RegresionResult rr = new RegresionResult...
resultList.add(cr)
resultList.add(rr)  

But I face the problem that I cannot call methods from the children like ClassificationResult.getLabels() (I could have all the method of all the children in the interface but it seems weird for me)

I saw some patterns, Factory and Builder but I face the previously described problem with the Factory pattern and with the Builder (having all the variables in one class) most of them would not be initialized.

I would appreciate some ideas about how I should design this

How to place textview in relative layout at random position of the layout?

I am facing the issue to place the textview on the random position in relative layout dynamically. The total count of textview can be 1, 3 , 4 ...or 30. It depend on the array list.

I want to put text view randomly in relative layout. Please guide me to achive it.

dimanche 22 septembre 2019

How to implement the repository pattern with updatable caches

I'm struggling to apply the repository pattern in a project.

The requirement is not complicated:
1. When a client requests some entity list from a server, the client saves them to a local database for caching. 2. If there is a cache, the client should use them (within expire time). 3. When the client gets user action like refresh data or receives some notification, the client should update local data from a remote server whether they expired or not.

I learned the repository pattern abstract persistence of the domain entity.
So an application doesn't need to know where the entity comes from. (from a server or local database and so on.)

But how can I update local data hidden by repository?
By adding flags in the repository method argument?

fun get(id: EntityId, update: Boolean)

But I think that reveals implementation detail.
Should the repository listen to a domain event like UpdateEntityRequested?

Please help. Thank you.

Regular Expression in java aboute a number(like phone number starting 021 and then two repeated number)?

Regular Expression in java about a number(like phone number starting 021 and then two repeated number) for totally eleven digits, for example:

 02177890488
 or
 02177098765 
 or 
 02199123450

pls help me,

i tried this:

^[0][2][1][1-9]\\1[0-9]{6}$

but does not work:(

samedi 21 septembre 2019

Star pattern printing from upside of the base and downside of the base according to the values in array

I am unable to come up with a proper solution to this problem where array with positive and negative values is responsible for the pattern in the output.

This should look something like this.

Array=[2,3,1,-1,-2]

Pattern: * * * * * * * * *

Please find this image if your still unable to understand the problem.

vendredi 20 septembre 2019

How to initialize the classes in factory method which have constructors with multiple parameters

Lets say I have a Shape interface which calculates the area of shape. I add 2 implementations Circle and Square. The challenge I see is both implementations have their own multiple argument constructors. How do I initialize them using a factory pattern. I wanted to solve it using java.

Mask a return from an annonymus object method as a getter for another object

Sorry for the horrible title, not clear how to express this in words, hence the code of the pattern:

class OtherClass:
    def __init__(self, parameter):
        # Do stuff to prepare for calling get_attribute
        pass
    def get_attribute(self):
        return "Something valuable"

class SomeClass:
    def __init__(self):
        self.attribute1 = None

    def get_attribute(self):
        return OtherClass(self.attribute1).get_attribute()

if __name__ == "__main__":
    my_class = SomeClass()
    result =  my_class.get_attribute()
    print(result)

I keep noticing this pattern in an inherited codebase and I can't seem to figure out what is the benefit of this approach. As far as I can tell, it's introducing an object to do something that a function could do.

class SomeClass:
    def __init__(self):
        self.attribute1 = None

def get_attribute(parameter):
    # Do stuff
    return "Something valueable"

my_class = SomeClass()
result =  get_attribute(my_class.attribute1)
print(result)

Is this a design pattern with benefits I'm failing to understand? Or just a byproduct the language allowing you to do the same thing in multiple ways?

Design pattern for game implementation

Sorry for the generic title, if anyone after reading the below has a better one please change it.

I'm implementing a popular board game in python. One game feature includes five piles of tokens from which the player can take. I'm having trouble thinking of a good way to represent this in code. My current implementation looks somewhat like this (simplified for the post):

class Game:
    def __init__(self):
        ...        
        self.tokens = num_tokens

class Player:
    def take_token(self, game):
        game.tokens[token] -= 1
        self.tokens[token] += 1
        return game  # the updated game instance

To me, this clearly seems like a terrible idea, because I'm passing the game state into Player just to manipulate it and then sending it back... there should be a much cleaner way to represent this. The problem is I like having the data stored under self for each object, as that seems a good way to bind the data to the object. Can someone help me identify the proper design pattern here?

Cannot implicitly convert type implementation to interface

all. Having difficulties in structuring application and applying design patterns. Initially was thinking about strategy pattern.

  • I want a common interface for setting and getting Item and Items details;
  • Interface implementations suits different contexts (e.g. furniture, toy) but all have same actions use the implementation
  • according to the context used all items derive from legacy BaseItem that has no properties on it

What I need:

/*client code*/
IItemHolder<BaseItem, BaseItem> itemHolder = null; // want to make it generic, abstract
switch (context)
{
    case "BigItems":
        // Exception "Cannot implicitly convert 'type' implementation to 'interface'
        itemHolder = new BigItemHolder(); 
        break;
    case "SmallItems":
        //itemHolder = new SmallItemHolder();
        break;
}

string itemTypeId = Session.GetSelectedItem(itemHolder.ItemTypeIdConstant);
string itemId = itemHolder.GetItemId(item);
string itemProperty = itemHolder.GetItemProperty(item);

/* structure I have */
class BaseItem { }
class BigItem : BaseItem { }

/* structure I am trying to implement */
interface IItemHolder<TBase> where TBase : BaseItem
{
    string ItemTypeIdConstant { get; }
    string GetItemId(TBase item);
    string GetItemProperty(TBase item);
    TBase GetItem(string itemId);
}

class BigItemHolder : IItemHolder<BigItem>
{
    public string ItemTypeIdConstant => throw new NotImplementedException();

    public BigItem GetItem(string itemId) { /**/ }

    public string GetItemId(BigItem item) { /**/ }

    public string GetItemProperty(BigItem item) { /**/ }
}

Covariance and contravariance in the interface does not help me much as same parameter can be input and output, unless splitting one generic type into two generic types

Task.Factory and factory pattern

Factory pattern is mostly used/recommended to be used while creating an object belonging to a sub class (there should be multiple sub-classes too). One such definition from dofactory - Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses (https://www.dofactory.com/net/factory-method-design-pattern).

Given this definition, is it apt for Task.Factory to be example of factory pattern, as there are no sub classes for Task classs' parents.

Decorator pattern that replace behaviour instead of adding

I've read a lot of posts and understand that decorator pattern is supposed to add functionality to the existing object. However, I have a scenario where one behaviour is replaced, not extended. To demonstrate, assume that I have these classes:

public interface IDoStuff {
    string DoStuff();
    string DoOtherStuff();
}

public class A : IDoStuff {
    public A(){}
    public string DoStuff() {
        ....
    }

    public string DoOtherStuff() {
        ....
    }
}


public class B : IDoStuff {
    protected readonly IDoStuff decoratee;

    public B(IDoStuff decoratee){ 
        this.decoratee = decoratee;
    }

    public string DoStuff() {
        decoratee.DoStuff();
        //More code
    }

    public string DoOtherStuff() {
        ....
        // This does not call decoratee.DoOtherStuff
    }
}

While I decorated the B.DoStuff method, but its DoOtherStuff method is a totally different implementation and cannot reuse the base object at all.

Am I implementing it correctly? Or is this an entirely different pattern?

jeudi 19 septembre 2019

Javascript code design: how to try catch each line in a good way?

My goal is to catch the error of each line and even there is an error, still run the remaining code, like this:

try {
  doFirstThing()
} catch(err) {
  //not important
}
try {
  doSecondThing()
} catch(err) {
  //not important
}
try {
  doSecondThing()
} catch(err) {
  //not important
}
//...
try {
  doLastThing()
} catch(err) {
  //not important
}

My question is: Do I have to try-catch each line to do this? Or there is a clever equivalent way that can have this done in a more elegant manner?

How to remove duplication from CallableStatement boiler plate code?

We have many stored procedures and functions that we call on our DB and the setup for each call in our data access layer is really verbose with setting the inputs and registering the output etc... Is there a better solution to maybe generating the CallableStatement dynamically for any stored procedure or function with any types/amounts of parameters and output type?

We have a home brew solution and it is ugly... full of if/else, fors and whiles... very hard to read and maintain. We have also tried to centralize common boilerplate code for like function calls. I.E. All of the ones that take a Long and return a boolean, all use the same centralized method with dynamic Long and stored procedure string.

The code is from memory please don't pay too much attention to syntax, this is a design question more than anything.

//Client usage in Controller class

certAwarded = PackageName.isCertAwardedFor(personIDToCheck);

//In class that mimics the interface of the database packages 
//There would be a method per public function
public static boolean isCertAwardedFor(Long personID){
    return PackageUtils.isMet(personID, "{? = call PACKAGE.is_met(?)}");
}

//In Package scoped Utility class 
//Attempt to centralize all single input param and return of boolean
//type of procedure calls.
static boolean isMet(Long personID, String proc){
    boolean met = false;
    try(AutoCloseableStatement stmt = new AutoCloseableStatement(proc)){
        CallableStatement callableStmt = stmt.createStatement();
        callableStmt.registerOutParameter(1, OracleTypes.VARCHAR2);
        callableStmt.setLong(2, personID);
        callableStmt.execute();
        met = convertYNtoBool(callableStmt.getString(1));
    }catch(SQLException ex){
        Logger.log(ex);
    }
return met;
}


///////////////////////////////////OR///////////////////////////////

//Client usage in Controller class

certAwarded = PackageName.isCertAwardedFor(personIDToCheck, CertPackageEnum);

//In class that mimics the interface of the database packages 
//There would be a method per public function
public static boolean isCertAwardedFor(Long personID, PackageProc procCall){
    return PackageUtils.call(personID, procCall.IS_CERT_AWARDED);
}

//In Package scoped Utility class 
//Attempt to centralize all single input param and return of boolean
//type of procedure calls.
static boolean isMet(Long personID, String proc){
    try(AutoCloseableStatement stmt = new AutoCloseableStatement(proc)){
        CallableStatement callableStmt = stmt.createStatement();
        LOTS OF CONDITIONS TO CHECK AND SET ALL POSSIBLE INPUTS AND OUTPUTS
    }catch(SQLException ex){
        Logger.log(ex);
    }
    return ?????
}

Looking for Design Pattern to Automate Repeated Task such as Login/Logout

I'm looking to a design pattern to help simplify my code.

My code is using HttpClient to call a web API that gets or posts information, but each session requires a login call first where a cookie is returned as ID, and a logout call is made at the end to close the connection. So my web API class looks like this:

public class APIHelper 
{
    public HttpClient myClient { get; set; }

    public async void Login()
    {
        using (HttpResponseMessage response = await myClient.PostAsync("loginAddress", "loginInput"))
        {
            if (response.IsSuccessStatusCode)
            {                    
                //save cookie
            }
        }
    }

    public async void Logout()
    {
        using (HttpResponseMessage response = await myClient.PostAsync("logoutAddress", ""))
        {
            if (response.IsSuccessStatusCode)
            {                    
                //session ends
            }
        }
    }

    public void GetOrder()  {...}

    public void NewOrder(object OrderData)  {...}

    public void GetCustomer()   {...}

    public void NewCustomer(object CustomerData)    {...}
}

And to use them, I would simply call them in order:

public Main()
{
    APIHelper.Login();
    APIHelper.GetOrder();   //or NewOrder, or GetCustomer, or any other actual API calls
    APIHelper.Logout();
}

Is there anyway I can place the Login/Logout calls inside each of the actual API calls so I don't have to type them up for each call? Ideally I just have to set up the structure once, then for whatever API calls I create, the system will automatically call the Login/Logout at beginning/end. Which design pattern addresses this kind of issue? Any simple example would be very helpful!

Thank you. SC

Another way to create data access layer than repository pattern

Everywhere people create DAL as Repositories. Is there any other/better solution to create data access layer with Dapper?

jquery replace part of a class name with pattern

I select all classes by class that begins with photo-. Replace part of class name by pattern. I need to replace photo-gallery-RID459852 with photo-gallery. Note: the part -RID[0-9] is replaced by ""

$("#Master [class*='photo-']").replace(function(index, css) {
  return (css.match(/(^|\s)-RID\S+/g) || []).join(' ');
}, "");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main id="Master">
  <div class="photo-gallery-RID459852 other any some">
    Algo
  </div>
  <div class="photo-gallery-RID987410 other any some2 other2"></div>
  <div>
    <div>
      <div class="photo-gallery-369841 other any some"></div>
    </div>
  </div>
  <article>
    <div class="photo-gallery-RID36541 here now other any some"></div>
  </article>
</main>

My jsFiddle: https://jsfiddle.net/ngqku78p/

Find the right design pattern

I have a controller class that make its objects visible only behind the login. Now, I want some of these object to be visible outside, The record are already in the database so I do not need to create them, also I do not need to create a new visibleObjectController class because the functions will be exactly the same. The objects just need to behave differently according to a visible or hidden feature.

I am quite sure there is a design pattern I can use for this. just do know which one. Any advise?

Design-pattern to limit access one class to another

I have class Shop and class Customer. So I want to specify the way class Customer can interract with class Shop (could not have access to some methods and fields). As far as I understand I need the third class wich will be inherited from Shop class and override access to this fields and methods. At the same time I want to create new Customer instance via Shop class and store all customers there. This means cyclic imports and this is not good. What kind of pattern you could advice me in this situation?