If X (an NP-hard problem) is polynomial-time many-one reducible to problem Y, then Y is NP-hard. Why is it the case?

According to this source,

If A is reduced to B and A ∈ class X, then B cannot be easier than X. This reduction is used to show if a problem belongs to NPH – just reduce some known NPH problem to the given problem. This reduction thus gives a lower bound for the complexity of B.

Now consider the following scenario: X is an NP-hard problem. It is polynomial-time many-one reducible to problem Y. This makes Y NP-hard. My question is, it could be possible that X has a better solution like NP or P, which we could not find. Then why should Y be NP-hard? It could be NP or P. If Y turns out to be P (assume) then X becomes P.

Clean architecture – How do I deal with use case reuse?

Trying to apply Uncle Bob’s clean architecture to an application I’m maintaining and I’m having difficulties with use cases and duplication/reuse. It’s my understanding that usecases should be self contained and that duplication is to be expected but this does not seem to make sense with what I’m dealing with. I feel there are multiple use cases that should end up using other use cases.

Here is a very simplified example of 4 use cases that exist separately but that are also dependent on each other in the following way.

BulkSendUsersToUnit                    SendUserToUnit            AddUserToMandatoryGroups               AddUserToGroup  

Each of them have validation, repository calls and conditions that always apply. Basically if I was doing this with services they would simply be methods that I would call from where I need them.

Can I/should I inject use cases in other use cases using DI?

What am I missing here?

Is it better to have a single query that returns all related entities, or separate queries for each case?


Summary

When writing methods to query for related entities, is it better to have a single method for all related entities or separate methods for each combination?

Full Problem

I’m writing repository classes for a .NET MVC project where each repository is responsible for querying for a specific entity type. I’m using Dapper, so all of the queries are written by hand. The repositories all implement an IRepository<TEntity> interface, which has method TEntity FindById(id).

Fetching just the entity is obviously very straightforward, but I’m faced with a dilemma when it comes to fetching the entity’s children and grandchildren and so forth. Often times, for an entity to be usable, it needs some or all of its descendants. I initially wrote FindById to return the entity with all descendants, which satisfies all use cases, but is also wasteful in many where I only need several descendants.

I wrote out individual methods for fetching various combinations. FindByIdWithChildA or FindByIdWithChildBAndGrandChildC and such. The problem here is that the method names keep getting longer and longer, which makes them a pain to read, and also wastes a lot of space in code.

My next idea was to accept various enum flag values designating which descendants to return. This worked fine for the immediate children, but by the time I got to grandchildren and beyond I had so many possible combinations to implement, and many of them didn’t make sense or wouldn’t be used.

By the time I have all this boilerplate written out, it almost feels like I’m writing a bad ORM instead of repositories. This has certainly slowed down development dramatically, and it has taken focus away from actually implementing new features.

The obvious wrong solution is to not use SQL joins and have the repositories splice together entities and collections of entities using LINQ. Using LINQ with EntityFramework could be an option, but I don’t think that the solution is to switch to another library.

Should I just simplify and have the single method/query return everything? If not, what is the best way to concisely implement separate methods?

This answer indicated that a FindByIdWithChild type method is normal, but I can’t imagine that being good practice for complex queries.

Clarification

So my entities are Sport, Division, SkillLevel, and TeamType. Each Sport has a list of Divisions, SkillLevels, and TeamTypes. Each Division has a single TeamType and a list of SkillLevels.

Suppose I want a Division with its parent Sport, its TeamType, and all of its SkillLevels. Should I do:

  1. DivisionRepository.FindById(id) which returns all of these properties, ignoring any case where I want just a Division or a Division and Sport, Division and TeamType, etc.

  2. DivisionRepository.FindById(id, BitFlagQueryScope) which has a big mess of an implementation to resolve all the possible flags, some of which might not be needed.

  3. DivisionRepository.FindByIdWithSportAndTeamTypeAndSkillLevels(id) and have one of these methods for every combination I need.

In all three cases, I am making one trip to the database. It’s just a matter of how I structure my code.

Additional example, suppose I want a Sport with just its TeamTypes. Elsewhere I will need a Sport with its SkillLevels, etc. Same questions as above. I’m only making one database trip, but should I use different code for these different queries, or just grab everything and discard/not use the excess?

Additional Clarification

In case there’s something wrong with my design overall, here’s how I’m using the entities:

Action(string id) {     var sport = SportRepository.FindById(id); // This needs to either return everything associated with the entity or be changed to allow specification     var model = new SportDisplayModel(sport);     return View(model); } 

I have two models, $ Entity$ DisplayModel, and $ Entity$ EditModel, and I use them for every view.

DDD and CQRS – Define an entity for Scheduling use case

I have a use case of scheduling a person to some work for some time range. Eg. A service for assigning a person A to work for time range X to Z in location C.

The only constraint it has, is one person cannot work on 2 things at same time. Eg. if person A is assigned to work in time 2019-07-21 to 2010-07-25, then person A cannot be assigned to any other work in that time. Eg. Person A for time range 2019-07-23 to 2019-07-27 should not be possible.

I am trying to make a service for it using domain driven design which would assign a person to some work. The entity I thought would be something like:

class Assignment {     PersonId,     startTime,     endTime,     location } 

Now, I wanted to make sure that if I found a entry in my database for Person A in some time range, then the call to create an entry for Person A in time range that is overlapping with the existing ones should fail.

Since, I am using CQRS model with DDD, so I don’t want to make a query to my database asking for all the assignments for that person. This may not always be recent data because of eventual consistency in CQRS model. I know in my primary key, PersonId would be there but I am not sure how can I use start and end time in it.

Any suggestions what I can do to achieve my goal for this? Is doing DDD and CQRS not a good idea in this? Or there is a better way to model this entity so that I can achieve my goal.

comparar resultado case

Possuo uma tebela custo médio tipo numeric, quero que quando o valor for menor que 0 traga a mensagem (Valor negativo) e quando for null, no caso diferente de maior e menor que 0 traga (valor nulo)

Porém ao rodar o comando a baixo esta dando o erro: ERROR: invalid input syntax for type numeric: “Negativo”

Acredito que é por que estou comparando um texto com campo numérico.

Como resolver?

select pr.ean, upper(pr.nome) as nome, pr.unidademedida, se.quantidade, pr.customedioinicial, (CASE
when fpp.customedio>=0 then fpp.customedio when fpp.customedio<=0 then ‘Negativo’

else ‘Valor nulo’ end) as customedio, se.quantidade * pr.customedioinicial as Total

FROM produto PR LEFT JOIN saldoestoque SE ON(pr.id=se.idproduto) LEFT JOIN formacaoprecoproduto FPP ON(fpp.idproduto=pr.id) where se.quantidade is not null order by se.quantidade desc

Is this a correct way to build a use case from initial requirements

I’m trying to practice how to write proper software specification and documentation for a Food Ordering System I’m building for training purposes.

I put my feet in the customer shoes who wants the project and wrote initial requirements that I want to implement in the system (you can find them here on GitHub)

After that I started to build use cases based these initial functional requirements, but I’m not sure if I am on the right path or not.

So, I have some question:

1 – Is the following picture is a correct way of building a simple use case for user registration? enter image description here

2 – Let’s say that the project is in its early stage where I still collecting requirements, should I wait until I finish collecting requirements in order to start building use cases and software diagrams (class, sequential, ER …)?

3 – should I finish building all of system use cases before start the next step of creating processes and data modeling?

Thanks in advance.

What is the best design for this use case regarding bidirectional relationship?

For this question let’s consider a system in which the users can match with each other (let’s say for simplicity exactly like the dating apps).

User1 matches User2 (and the other way around) only in one of the following cases 1. they both like each other 2. one of them special likes the other one and the other one just likes 3. both of them special like each other

The match will be stored in a SQL database, and when the users log in the app they need to fetch their matches, also the information if they were special liked, or special liked, or both.

The design question here is regarding the match entity storage and concept, whether it should be considered as two entities or one.

The first approach is as follows:

create table matches (     id                     char(36)                            not null,     first_user_id          int unsigned                        not null,     second_user_id         int unsigned                        not null,     first_user_superliked  tinyint(1)                          not null,     second_user_superliked tinyint(1)                          not null,     created_at             timestamp default CURRENT_TIMESTAMP not null     PRIMARY KEY (id) ) 

The id will be an unique uuid, so one match will have only this one entity for both users. The fetch query will have to query both first_user_id and second_user_id fields. Example, user with id 4 logs in and need to see his matches, query will be like:

SELECT * FROM matches WHERE first_user_id = 4 OR second_user_id = 4 

The second approach requires two rows for one match, each obviously will have different ids. The structure:

create table matches (     id                     char(36)                            not null,     user_id                int unsigned                        not null,     matchee_id             int unsigned                        not null,     did_superlike          tinyint(1)                          not null,     was_superliked         tinyint(1)                          not null,     created_at             timestamp default CURRENT_TIMESTAMP not null     PRIMARY KEY (id) ) 

With this approach if we want to get the matches of user with id 4, we have to query only based on the field user_id If someone unmatches the other user, we have to delete both rows (or disable via some flag)

As software engineers, what do you think is the best approach for this scenarios ?

I provided a match example, but my question is in general for bidirectional relationships of this type as I see them quite often and would like other opinions in order to improve myself

What is the best design for this use case regarding bidirectional relationship?

For this question let’s consider a system in which the users can match with each other (let’s say for simplicity exactly like the dating apps).

User1 matches User2 (and the other way around) only in one of the following cases 1. they both like each other 2. one of them special likes the other one and the other one just likes 3. both of them special like each other

The match will be stored in a SQL database, and when the users log in the app they need to fetch their matches, also the information if they were special liked, or special liked, or both.

The design question here is regarding the match entity storage and concept, whether it should be considered as two entities or one.

The first approach is as follows:

create table matches (     id                     char(36)                            not null,     first_user_id          int unsigned                        not null,     second_user_id         int unsigned                        not null,     first_user_superliked  tinyint(1)                          not null,     second_user_superliked tinyint(1)                          not null,     created_at             timestamp default CURRENT_TIMESTAMP not null     PRIMARY KEY (id) ) 

The id will be an unique uuid, so one match will have only this one entity for both users. The fetch query will have to query both first_user_id and second_user_id fields. Example, user with id 4 logs in and need to see his matches, query will be like:

SELECT * FROM matches WHERE first_user_id = 4 OR second_user_id = 4 

The second approach requires two rows for one match, each obviously will have different ids. The structure:

create table matches (     id                     char(36)                            not null,     user_id                int unsigned                        not null,     matchee_id             int unsigned                        not null,     did_superlike          tinyint(1)                          not null,     was_superliked         tinyint(1)                          not null,     created_at             timestamp default CURRENT_TIMESTAMP not null     PRIMARY KEY (id) ) 

With this approach if we want to get the matches of user with id 4, we have to query only based on the field user_id If someone unmatches the other user, we have to delete both rows (or disable via some flag)

As software engineers, what do you think is the best approach for this scenarios ?

I provided a match example, but my question is in general for bidirectional relationships of this type as I see them quite often and would like other opinions in order to improve myself