mercredi 19 juin 2019

Pattern to access differently named member functions of derived classes

So I have the following class hierarchy and both the derived classes have differently named member functions which I want to access in a common manner.

class T {}
class T1::T {
    int getIntT1() {}
}
class T2::T {
    int getIntT2() {}
}

I created a template to access these member functions.

template<typename T, int (T::*f)()>
int getInt(T t) {}

I can't change the class definitions, so is there any other way to do this?

How to implement a client that has to login in every 30 min?

I am writing an application which uses the JiraRestClient by atlassian. I cannot create this client on every Jira interaction so I thought of caching this client.

This client performs login in every 35 minutes so I thought of caching it for 30 min and then perform login again.

For that purpose I need a single instance of this client so that all the threads for the Jira interactions can use it. I created a provider class which will keep the time track and will perform the login, if the creation time of the instance is over 30 min, insuring that the instance is always logged in.

public class JiraRestClientProvider {
private static JiraRestClient jiraRestClient;
private static final long EXPIRATION_TIME = 1800L;
private static long creationTime = Instant.now().getEpochSecond();

public static synchronized JiraRestClient getJiraRestClient() {
    if (jiraRestClient == null || Instant.now().getEpochSecond() > creationTime + EXPIRATION_TIME) {
        return createJiraRestClient();
    }
    return jiraRestClient;
}

where createJiraRestClient is a private method that reads the credentials, updates the creation time, and updates the private static variable jiraRestClient.

Another class uses this JiraRestClientProvider class to perform the Jira actions like creating issues or commenting on a issue, etc as follows:

JiraRestClientProvider.getJiraRestClient().
getIssueClient().createIssue(issueInput).claim().getKey();

or

JiraRestClientProvider.getJiraRestClient().getIssueClient()
            .getIssue(issueKey).claim().getCommentsUri().toString();

Now, while writing unit test for the class that's using this I can not mock the static method getJiraRestClient and therefore unable to write unit tests. (Also, I cannot use PowerMock).

My question is, is there a way that I can write my provider class such that I will only have single and fresh instance of JiraRestClient for all threads and I can also unit test it?

Use Factory Method Design Pattern to execute stored procedures

I have a few stored procedures that I want to execute using factory method pattern from a C# console application.

The following is an example of one of the stored procedures I am trying to execute. The others are similar.

   GO
   SET ANSI_NULLS ON
   GO
   SET QUOTED_IDENTIFIER ON
   GO
   CREATE PROCEDURE [dbo].[OrderHeaders_Delete]
       @OlderThanDays int
   AS
   BEGIN
       DELETE FROM dbo.OrderHeader 
       WHERE LastUpdate < DATEADD(d, @OlderThanDays * -1, GETDATE());
   END

Currently I'm using the following code to do the execution.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace Data_Prune
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection mySqlConnection = new SqlConnection(
                "server=MYSERVER;database=MYDATABASE;uid=UID;pwd=PASSWORD");

            SqlCommand mySqlCmd = mySqlConnection.CreateCommand();
            mySqlCmd.CommandText = "EXECUTE OrderHeaders_Delete @OlderThanDays";
            mySqlCmd.Parameters.Add("@OlderThanDays", SqlDbType.Int).Value = "7";
            mySqlConnection.Open();
            mySqlCmd.ExecuteNonQuery();
            mySqlConnection.Close();                
        }
    }
}

How would I integrate this into a factory method pattern so that I can add on the other stored procedures and have it run through them? The purpose of it is to run everyday as kind of a log deletion job, go through all the stored procedures and delete the appropriate logs.

C# - Validation layer based on rules

I'm trying to implement this pattern:

https://mentormate.com/bg/blog/modern-validation-patterns-in-c-sharp/

Starting from the caller I would like to do something like that:

var validatore = new Validator();

validatore.AddRule<TestRule>("OK");
validatore.AddRule<int>(45);

validatore.Validate();

The implementation of the rules:

public interface IValidationRule<T>
{
    string Error { get; set; }
    bool Validate(T arg);
}

public class TestRule : IValidationRule<string>
{
    public string Error { get; set; }
    public bool Validate(string arg)
    {
        return arg == "test";
    }
}

The problem is the concrete implementation of the validator. I assumed something like that:

public interface IValidator
{
    void AddRule<TRule>(dynamic arg);
    ValidationResult Validate();
}

public class Validator : IValidator
{
    public void AddRule<T>(dynamic arg)
    {
        ???
    }

    public ValidationResult Validate()
    {
        forEach ...
    }
}

Where should i put every generic rule in a single collection object (AddRule)? Is my like-implementation on the right way?

mardi 18 juin 2019

Is it possible to use inheritance to implement an ECS in c++?

I'm trying to architect a game I'm writing in C++ as an Entity/Component system (the basic idea being I would have a set of "Entity" classes representing different kinds of data and a set of "Component" classes representing various behaviors a given entity could have). I wanted to implement it using virtual base classes for the components. For instance, I could have a Character entity:

class Character {
public:
    int armor;
    int health;
    std::string name;
};

as well as a Fighter component representing something that can use melee weapons:

class Fighter {
public:
    int damage;
    virtual Direction attack() = 0;
}

and a Mage component representing something that can cast spells

class Mage {
public:
    std::vector<Spell> spellList;
    virtual Spell cast() = 0;
}

Using multiple inheritance to use these, I'd have

class ElvenMage : Character, Mage {
public:
    ElvenMage() {
        this->armor = 0;
        this->health = 10;
        this->name = "elven mage";
        this->spellList = ...;
    }
    virtual Spell cast() {
        // some AI logic to figure out which spell to cast
    }
};

and

class Player : Character, Fighter, Mage {
public:
    Player() {
        this->armor = 5;
        this->health = 20;
        this->name = "Player";
    }
    virtual Direction attack() {
        // some logic to handle player melee input
    }
    virtual Spell cast() {
        // some logic to handle player spell casting input
    }
};

To keep track of all current characters on the map I could do something like

class Engine {
public:
    std::vector<std::unique_ptr<Character>> characters;

I have to store them directly as Characters (not as Fighters or Mages), yet I would need to process fighters and mages separately (for instance, looping through all Characters and if they can cast a spell they do so otherwise they attack with a melee weapon). In the actual game logic, how would I distinguish between an instance of Character that also implements Mage vs. an instance of Character that also implements Fighter?

Is there an easy way to do what I am trying to, or should I completely rethink my design?

(note: this isn't actual code; in the real world I'd actually use a factory or something to create elves or whatever instead of trying to put all the information in the constructor, and I'd probably separate the logic differently, but it illustrates the problem I'm having).

How to execute a stored procedure from a C# console app

I want to execute this stored procedure from a C# console application.

The following is the stored procedure I wrote and am trying to execute.

   GO
   /****** Object:  StoredProcedure [dbo].[OrderHeaders_Delete]    Script 
   Date: 6/18/2019 1:44:23 PM ******/
   SET ANSI_NULLS ON
   GO
   SET QUOTED_IDENTIFIER ON
   GO
   CREATE PROCEDURE [dbo].[OrderHeaders_Delete]
       @OlderThanDays int
   AS
   BEGIN
       DELETE FROM dbo.OrderHeader 
       WHERE LastUpdate < DATEADD(d, @OlderThanDays * -1, GETDATE());
   END

I've already tried it using the following code but I am looking for something more dynamic with parameters and using Factory Method Design Pattern, where I can add on similar stored procedures, run it as a job and have it go through the SP.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;

namespace Data_Prune
{
    class Program
    {
        static void Main(string[] args)
        {
            SqlConnection mySqlConnection =
                new SqlConnection("server=HPDWTVSERVE;database=HPDeParts;uid=RMPsa;pwd=rmp9040"
                );

            SqlCommand mySqlCmd = mySqlConnection.CreateCommand();

            mySqlCmd.CommandText = "EXECUTE OrderHeaders_Delete @OlderThanDays";

            mySqlCmd.Parameters.Add("@OlderThanDays", SqlDbType.Int).Value = "100";

            mySqlConnection.Open();
            mySqlCmd.ExecuteNonQuery();
            mySqlConnection.Close(); 



        }
    }
}

Clean architecture UseCases vs Controller with functions

I just started reading about clean architecture and I'm confused on the definitions of usecase implementations.

Consider a controller class having set of functions that accepts T and returns R after executing some logic

interface IController {
   fun usecase1(param:T) : R 
   fun usecase2(param:T) : R
}

now I can execute the use cases with the IController instance.

Another way is to define each usecases as a class and inject in other objects which requires the functionality.

class UseCase1 {
    fun execute(param:T):R {}
}

class UseCase2 {
    fun execute(param:T):R {}
}

what are the advantages/disadvantages between having usecases as separate units versus having it as functions of some class?

IMO, separate units add contruction and Injection overhead whereas other approach suffers 'inheritance problems over composition'. Which is the right way to go ?