samedi 25 avril 2020

Java : Need suggestion on Good Design

I am working on building characters for Dungeons & Dragons Game. The characters have Innate abilities such as Strength, Dexterity, Constitution, Intelligence, Wisdom, Charisama.

My question is: How can I design characters in the game such that the code allows the abilities to be added later without modifying the implementation of character class?

Can you suggest some good design for such problem?

Self-driving cars future? Looking for different opinions

I'm writing a research paper on self driving cars and their future. I would really appreciate the view points of different people on the same.

vendredi 24 avril 2020

Transaction issue when DB Call happens after Rest Call

I am using Spring Boot and my application is just Monolithic for now, may switch to microservices later.

SCENARIO 1: Here My DB call Does NOT depend on REST Response

@Transactional
class MyService {

    public void DBCallNotDependsOnRESTResponse(){

        //DB Call
        //REST Call
    }
}

SCENARIO 2: Here My DB call depends on REST Response

@Transactional
class MyService {

    public void DBCallDependsOnRESTResponse(){

        //REST Call
        //DB Call, HERE DB CALL DEPENDS ON REST RESPONSE
    }
}

In case of Scenario 1, I have no issues as DB gets rolled back incase REST fails.

BUT, incase of Scenario 2, REST call cannot be rolled back, incase if any exception occurs at DB call.

I already searched in google for above, I found some solutions like we need to use something like Pub-Sub model system seems, BUT I could not able to get that concept to my head clearly.

I will be glad if someone could able to provide solution for SCENARIO 2. How Other Ecommerce businesses handling their transactions effectively, I guess my query related to some Architecture design.. Please advice some good architecture approach to solve above Transaction issue. Do you think using some Messaging system like Kafka will solve above issue..? FYI, currently, my application is Monolithic, shall I use Microservices? Do I need to use two-phase-commit or Sagas will solve my problem? Does Sagas can be used for Monolithic application?

In Game Programming (And OOP Generally), When do we Decide to Use the Command vs the State Design Pattern?

I'm reading in Game Programming Patterns that Commands should be used to give directions for actors, and States are used to indicate a single state the actor would be in (standing, jumping, moving, etc).

I'm currently working on a problem in my codebase right now that I can't seem to wrap my head around in a good way. I currently have 3 "Interaction States" that my characters can be in - Passive, Melee Combat, or Ranged Combat.

And there are several what I think of as Commands currently that a character can be in - Moving, Talking, Attacking, etc. But a character can't be attacking in a passive state, or talking in a combat state - my question is do these commands make more sense as Commands or as States, and I can build a concurrent/hierarchical state machine?

Also, should we think of Commands as the actions that move characters from state to state (e.g. if I right click an enemy I pass the "attack" Command into the State constructor to move from "move" state to "attack" state)? I guess I'm just having a hard time conceptualizing what to do here and how states and commands interact.

Example State, would be attached to a character object:

public class MeleeState : InteractionState
{
    public override void HandleInput(Character character, InteractionCommands command)
    {
        base.HandleInput(character, command);

        if (command == InteractionCommands.CHANGETOPASSIVE)
        {

        }
        else if (command == InteractionCommands.CHANGETORANGED)
        {

        }
        else
        {

        }
    }
}

Example Command:

public class Attack : Command
{

    Attack(Character aggressor, Enemy victim)
    {

    }

    public override void Execute()
    {
        base.Execute();
    }

    public override void Undo()
    {
        base.Undo();
    }

    // Update is called once per frame
    void Update()
    {

    }
}

Avoid Conditional Statments while constructing an object

I need some suggestion to implement elegant way to avoid if-else. I really cannt avoid the conditional check, I need to do the check and then add certain properties to the object.

@Override
    public Summary addPropertyBasedOnType(AssignmentEvent assignmentEvent, String userId) {

        Summary summary = new Summary();
        summary.setTimestamp((new Timestamp(System.currentTimeMillis())).toString());
        summary.setUserId("");
        summary.setGradingProgress(GradingProgress.Started);
        summary.setComment(COMMENT);

        if (list.contains(assignmentEvent.getItemType())) {
            summary.setGradingProgress(GradingProgress.Incomplete);
            summary.setScoreMaximum(ASSIGNMENT_MAX_SCORE);
            summary.setScoreGiven(ASSIGNMENT_MAX_SCORE);
        } else if (assignmentEvent.getItemType().equalsIgnoreCase("some string")) {
            summary.setGradingProgress(GradingProgress.PendingManual);
        } else if (assignmentEvent.getItemType().equalsIgnoreCase("test string")) {
            if (assignmentEvent.getLatestUserAssignmentData().getScoreSource().getSource() == 0) {
                summary.setGradingProgress(GradingProgress.FullyGraded);
                summary.setScoreGiven(assignmentEvent.getLatestUserAssignmentData().getScore());
                summary.setScoreMaximum(ASSIGNMENT_MAX_SCORE);
            }

            if (assignmentEvent.getLatestUserAssignmentData().getScoreSource().getSource() == 1) {
                summary.setGradingProgress(GradingProgress.Started);
            }
        } else {
            summary.setGradingProgress(GradingProgress.Incomplete);
            summary.setScoreGiven(assignmentEvent.getLatestUserAssignmentData().getScore());
            summary.setScoreMaximum(ASSIGNMENT_MAX_SCORE);
        }
        return summary;
    }

I was thinking Factory Pattern but I think it is an overkill for this.

need repository design pattern advice

I have many entities and repositories. My entities are two types: Erasable and indelible. So i have two base classes for entities.

Indelible entities implements this base class:

public abstract class BaseEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public DateTime InsertedDate { get; set; }
    public DateTime? UpdatedDate { get; set; }
    //For recovering
    public DateTime? DeletedDate { get; set; }
    public bool Active { get; set; }
}

Erasable entities implement this base class:

    public abstract class BaseErasableEntity
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]       
    public int Id { get; set; }
    public DateTime InsertedDate { get; set; }
    public DateTime? UpdatedDate { get; set; }
}

Repositories that use an erasable entity implement this base class:

 public class BaseErasableRepository<TEntity, TRepository> : DbContext, IBaseErasableRepository<TEntity> where TEntity : BaseErasableEntity where TRepository : DbContext
{
    public BaseErasableRepository(DbContextOptions<TRepository> options) : base(options)
    { }
    protected DbSet<TEntity> Entities { get; set; }
    public IEnumerable<TEntity> GetAll()
    {
        return Entities ?? throw new CannotFindEntityException();
    }
    public TEntity GetById(int id)
    {
        var entity = Entities.Find(id) ?? throw new CannotFindEntityException(id);
        return entity;
    }
    public void Update(TEntity entity)
    {
        Entities.Update(entity);
        SaveChanges();
    }
    public void Delete(TEntity entity)
    {
        Entities.Remove(entity);
        SaveChanges();
    }
    public IEnumerable<TEntity> GetFiltered(Func<TEntity, bool> condition = null)
    {
        return Entities.Where(condition) ?? throw new CannotFindEntityException();
    }
}

Repositories that use an indelible entity implement this base class:

 public class BaseRepository<TEntity, TRepository> : DbContext, IBaseRepository<TEntity> where TEntity : BaseEntity where TRepository : DbContext
{
    public BaseRepository(DbContextOptions<TRepository> options) : base(options)
    { }
    protected DbSet<TEntity> Entities { get; set; }
    public IEnumerable<TEntity> GetAll()
    {
        return Entities.Where(entity => entity.Active == true) ?? throw new CannotFindEntityException();
    }
    public TEntity GetById(int id)
    {
        var entity = Entities.Find(id) ?? throw new CannotFindEntityException(id);
        if(!entity.Active)
            throw new CannotFindEntityException();
        return entity;
    }
    public void Update(TEntity entity)
    {
        Entities.Update(entity);
        SaveChanges();
    }
    public void Delete(TEntity entity)
    { 
        var toBeDeleteEntity = GetById(entity.Id);
        toBeDeleteEntity.Active = false;
        toBeDeleteEntity.DeletedDate = DateTime.Now;
        Entities.Update(toBeDeleteEntity);
        SaveChanges();
    }
    public IEnumerable<TEntity> GetFiltered(Func<TEntity, bool> condition = null)
    {
        return Entities.Where(entity => entity.Active).Where(condition) ?? throw new CannotFindEntityException();
    }
}

My problem: I have more methods for repositories. They are the same for both repository. I have to write same code two times when i add new feature. Is there a better way to use single base repository class?

Spring Rest Does DTOs can be BiDirectional?

I am new to Spring REST Api. Couple of doubts:

DOUBT1:

class UserDTO {
    long id;
    String name;
    int age;

    // getters and setters
}

CASE1:

public void doSomethng(@RequestBody UserDTO userDTO){
    repository.findById(userDTO.getId());
}

CASE2:

public void doSomethng(@RequestBody long id){ //Is this correct?
    repository.findById(id);
}

CASE3:

public void doSomethng(@RequestBody Map<Long, Object> map){ //Is this correct?
    repository.findById(map.get("id"));
}

I actually need to pass only "id" for POST Request.

So, Out of above 3 cases, which is a good practice? for me long id seems reasonable. I am not understanding, in which cases Passing Map as RequestBody is much better than DTO?

DOUBT2: I am currently using DTOs as BiDirectional. So, Using Bidirectional for DTOs is correct? Will am I going to face any issues with below DTOs design?

class UserDTO {
    long id;
    List<OrderDTO> orders;
}

class OrderDTO {
    long orderId;
    UserDTO userDTO;
}