问:
Can I wrap a collection with a static class and still call it repository pattern?
I couldn't find a single example about repository pattern using something else then a database.

My goal is to have a global static repository that stores some objects in memory. I don't want it to be a singleton with it's Instance property because it doesn't have any special function but Add/Removoe... just like a repository.

So let's assume I want to keep a collection of object converters somewhere in memory. Am I misusing the repository pattern for this (becuase it seems to be the most suitable solution here)? Or do you call it something else and repository is reserved only for databases or other storage types?

```<code>public static ConvertersRepository : IConvertersRepository
{
    // this is the actual collection
    private static IList<IObjectConvereter> _converters = new List<IObjectConvereter>;
    public static void AddObjectConverter(IObjectConvereter...) {}
    public static IObjectConvereter GetObjectConverter(...) {}
}
</code>```

答:
Disclaimer: I looked up the Repository pattern because I've never heard of it by this name before. To me it looks just like a standard wrapper around the persistence/database layer.

It's common to use wrappers around data access and change the implementation behind the wrapper as the project progresses, and some of the early implementations are often not even persisting the data on disk. So for the pattern I know, which I think is the Repository pattern you speak of, it doesn't matter if the data is stored in a database. All that matters is that it could be stored in a database - but that's implementation. Still, the pattern strongly implies persistence, so I wouldn't say you're really using the Repository pattern here.

Your question has two parts. One part is the question if what you're doing is the Repository pattern, the other is if it's fine to call something XyzRepository if it doesn't implement the Repository pattern.

That second question depends on the entirety of your or your company's codebase. I've seen many codebases with plenty of classes named ...Repository that had nothing to do with persisting something on disk. In a general case it's perfectly normal to call a class that is a repository of xyz XyzRepository. And what your question describes certainly is a repository of converters. However (!), if in a specific case you have a codebase  where all other classes that are named ...Repository are wrapping persistent storage, then using the name for something that doesn't offer persistency can be confusing or misleading, and therefore should be avoided.

A list of alternative but not necessarily better names:
Converters
ConvertersPool
ConvertersHub
ConvertersCollection
ConvertersStore
ConvertersManager


问:
Why do most language's definition of substring allow substring("abc", 3) => ""
I've seen most languages have it be the case for their substring method that using the length of a given string in the method as the start index will give you an empty string. It is most definitely helpful when writing algorithms involving successive shortening of the string down to an empty string. The problem I have is that it makes most of the summaries of these methods/functions look inaccurate when they describe the result.

For instance, Java's substring for String states that "The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.". This makes sense for all values 0 <= i < len(string). As soon as you use len(string) however, what does that index refer to? In a language like C using C strings, it naturally becomes the null terminator which we treat as an empty string. The implementations I've seen specifically check the range of the indices to be [0, len(string)]. When only one argument is specified we will take the difference between the start index and the length of the string which happens to work out to 0 for startIndex=len(string).

I've come to believe this is just an unspoken convention among languages that go back to the roots of NULL terminated strings to act as empty strings. Can anyone shed some light beyond it's just the way it is?

答:
You're thinking of the meaning of this argument wrong.

Slightly surprisingly, the value doesn't count characters.  What it does count is positions between the characters in the string.

The String "abc" has four such positions: before the a, between a and b, between b and c, and after the c. As usual in computing, we count these positions from 0 to 3. By specifying two such positions, it's immediately clear which characters should and shouldn't belong to the substring: substr("abc", 0, 1) obviously means "a", and substr("abc", 2,3) means "c". And substr("abc", 3) can only mean "Start at the position after the c", which will obviously yield the empty string.

All substring functions I have ever seen work this way, although the only place I've seen this spelt out for me is the emacs online help - that one is a real eye-opener. (Emacs is "focused with maniacal intensity on the deceptively simple-seeming problem of editing text" - Neal Stephenson)

ContentLicense: CC BY-SA 3.0


答:
Your substring function would be an overload of a function that takes the start and end. There you would pass the start and 1 past the last.

This means that the entire string would be 0, length; it also means that an empty string would have both values the same.

Letting the index be between 0 to length inclusive also lets you call them on empty strings (for what it's worth).

Title: Why do most language's definition of substring allow substring("abc", 3) => ""

Body:
I've seen most languages have it be the case for their substring method that using the length of a given string in the method as the start index will give you an empty string. It is most definitely helpful when writing algorithms involving successive shortening of the string down to an empty string. The problem I have is that it makes most of the summaries of these methods/functions look inaccurate when they describe the result.

For instance, Java's substring for String states that "The substring begins at the specified beginIndex and extends to the character at index endIndex - 1.". This makes sense for all values 0 <= i < len(string). As soon as you use len(string) however, what does that index refer to? In a language like C using C strings, it naturally becomes the null terminator which we treat as an empty string. The implementations I've seen specifically check the range of the indices to be [0, len(string)]. When only one argument is specified we will take the difference between the start index and the length of the string which happens to work out to 0 for startIndex=len(string).

I've come to believe this is just an unspoken convention among languages that go back to the roots of NULL terminated strings to act as empty strings. Can anyone shed some light beyond it's just the way it is?


问:
CRUD operations in DDD
I'm designing an application with DDD. I'm moving from flat POCO objects to strong domain models, so my question is:

Would I have to call my basic CRUD operations (located in my repository layer)  from controllers directly, without passing through the domain layer? I can't see any added value to doing that, but I'm not sure if it's inside the DDD practices make that direct call.

答:
Would I have to call my basic CRUD operations (located in my repository layer) from controllers directly?

No, there's nothing that forces or requires you to do that.  You can add as many layers between the controller and your database as you wish, or split it into separate repositories if you like.

Title: CRUD operations in DDD


问:
Maintain hundreds of customized branches over master branch
Currently we have one master branch for our PHP application in a shared repository. We have more than 500 clients who are subscribers of our software, most of whom have some customization for different purposes, each in a separate branch. The customization could be a different text field name, a totally new feature or module, or new tables/columns in the database.

The challenge we face is that as we maintain these hundreds of customized branches and distribute to clients, from time to time we provide new feature and update our master branch, and we would like to push master branch changes to the custom branches in order to update them to the latest version.

Unfortunately this often results in many conflicts in the custom code, and we spend many hours going through every single branch to solve all the conflicts. This is very inefficient, and we've found that mistakes are not uncommon when solving these conflicts.

I am looking for a more efficient way to keep our client release branches up to date with the master branch that will result in less effort during merging.

答:
You are not solving the root cause of the disease by looking at the symptom.  Using a 'code management' approach is symptomatic, but will not solve things for you long term. The root cause is lack of 'well managed' product capabilities, features & their extensions and variations.

Your 'custom' code represents nothing but extensions of the product features & capabilities and data field changes at others.

How extensive the custom features, how different, how contextually similar or not will play a lot into 'sanitizing' your product's code base.

More than how you code and version, this is a place where product management, product architecture and data architecture comes into play. Seriously.

Because, at the end of the day, the code is nothing but your offering of business and product features/ services to your clients. That is what your company is getting paid for.

Getting a better handle on this must come from the 'capabilities' standpoint and not code standpoint.

You, your company, and product can not be everything to everyone. Now that you have a decent revenue base of 500 clients, it's time to productize on what you intend to be.

And if you are offering several things, it would make sense to modularize your product capabilities in an organized fashion.

How broad and deep will your products go? Or else this will lead to 'quality of service' issues & 'product dilution and fragmentation' as you go down the line.

Will you be a CRM or ERP or order processing/ dispatch or Microsoft Excel?

Your existing extensions need to roll up and harmonize, the way a large software major pulls in and merges products acquired from a startup.

You will need to have a strong product management and data architecture person map the following:

Master branch, its product capabilities, and features base

Custom extension features, types, and variations

Significance and variation of 'custom fields'

..to create road map of assimilation and harmonization of all these loose product threads / branches in the grand context of your core application.

PS: Connect with me, I know a person who can help you fix this :)


答:
All the important things have been proposed by good answers here. I'd like to add my five pence as a process suggestion.

I'd like to suggest you solve this problem in a long or mid-term range and adopt your policy, how you develop code. Try to become a flexible learning team. If somebody allowed to have 500 repos instead of making the software configurable, then it is time to ask yourself how you have worked so far and you will do from now on.

Which means:

Clarify the change management responsibilities: if a customer needs some adaptions, who is selling them, who is allowing them and who decides how the code will be changed? Where are the screws to turn if some things must be changes?

Clarify the role, who in your team is allowed to make new repos, and who is not.

Try to make sure that everybody in your team sees the necessity of patterns that allow flexibility to software.

Clarify your management tool: how do you quickly know what customer has what code adoptions. I know, some "list of 500" sounds annoying, but here is some "emotional economy", if you want. If you can't tell the customer's changes in a quick time, you feel even more lost and drawn as if you have to start a list. Then, use that list to group the features the way other people's answers here have shown you:

group customers by minor/major changes

group by subject related changes

group by changes easy to merge and changes difficult to merge

find groups of equal changes made to several repos (oh yes, there will be some).

maybe the most important in order to talk to your manager/investor: group by expensive changes and cheap changes.

This is in no way meant to make a bad pressure atmosphere in your team. I rather suggest that you clarify these points first for yourself and, wherever you feel the support, organize this together with your team. Invite people friendly to the table in order to improve all your experience.

Then, try to establish a long term time window, where you cook this thing on a small flame. Suggestion: try to merge at least two repos every week, and so remove at least one. You may learn that often, you can merge more than two branches, as you get routine and oversight. That way, in one year you can deal the worst (most expensive?) branches, and in two years you can reduce this problem to have a clearly better software. But don't expect more, as in the end nobody will "have time" for this, but you are the one who won't allow this any longer as you are the software architect.

This is how I would try to handle it if I were in your position. However I don't know how your team is going to accept such things, how the software really allows this, how you are supported and also what you still have to learn. You are the software architect - just go for it :-)

Title: Maintain hundreds of customized branches over master branch

Body:
Currently we have one master branch for our PHP application in a shared repository. We have more than 500 clients who are subscribers of our software, most of whom have some customization for different purposes, each in a separate branch. The customization could be a different text field name, a totally new feature or module, or new tables/columns in the database.

The challenge we face is that as we maintain these hundreds of customized branches and distribute to clients, from time to time we provide new feature and update our master branch, and we would like to push master branch changes to the custom branches in order to update them to the latest version.

Unfortunately this often results in many conflicts in the custom code, and we spend many hours going through every single branch to solve all the conflicts. This is very inefficient, and we've found that mistakes are not uncommon when solving these conflicts.

I am looking for a more efficient way to keep our client release branches up to date with the master branch that will result in less effort during merging.


问:
When should we use weak entities when modelling a database?
This is basically a question about what are weak entities? When should we use them? How should they be modeled?

What is the main difference between normal entities and weak entities? Does weak entities correspond to value objects when doing Domain Driven Design?

To help keep the question on topic here is an example taken from Wikipedia that people can use to answer these question:

In this example OrderItem was modeled as a weak entity, but I can't understand why it can't be modeled as a normal entity.

Another question is what if I want to track the order history (i.e. the changes in it status) would that be a normal or weak entity?

答:
See ,a order has many order items(multivalued attribute).
Thus according to rule we create separate table.

Now,let's say 2 customers has same order.e.g both buy iPhone at same price,discount, same date,etc.
So ideally there should be two exact tuples for order of iPhone in orderitem relation. But according to constraint of a relationn,all the tuples should be unique.
So lets relate two orders to same item_line_number.no problem uptil now.
Now consider one of the customer cancels. Is iPhone order.also the item_line_number tuple will be deleted.
Now other customer's who bought iPhone also gets deleted because of M:1 correspondence.
So finally the database is inconsistent.
That's why we use a descriptor key which will be orderid.thus deleting one iPhone ordered doesn't cause database corruption.


问:
Two structs with the same members but different naming, is it a good idea?
I am writing a program that involves working with both polar and Cartesian coordinates.

Does it make sense to create two different structs for each kind of points, one with X and Y members and one is with R and Theta members.

Or is it too much and it is better to have just one struct with first and second as members.

What I am writing is simple and it won't change much. But I am curious what is better from a design point of view.

I am thinking the first option is better. It seems more readable and I will get the benefit of type checking.

答:
Yes, it makes a lot of sense.

The value of a struct is not just that it encapsulates data under a handy name. The value is that it codifies your intentions so that the compiler can help you verify that you don't violate them some day (e.g. mistake a polar coordinate set for a cartesian coordinate set).

People are bad at remembering such niggling details, but good at creating bold, inventive plans. Computers are good at niggling details and bad at creative plans. Therefore it is always a good idea to shift as much niggling-detail maintenance to the computer, leaving your mind free to work on the grand plan.


问:
Passing a list of choices with different arguments for each choice
I am writing a card game, in which I separated the "Core Logic" of the game from the UI. Communication with the player from the core logic part is done via callbacks which the UI implements and handles (in a separate thread if needed). The core logic library calls these callbacks, the UI handles them, passing an object representing the data that needs to be returned, and returns it.

What I'm currently stuck in is implementing the ability for the Core Logic to give the player a "choice" between possible actions. For example, the core logic might want the player to select from the following 3 game actions:

Draw 5 cards from Deck A

Draw 2 cards from Deck B

Allocate 4 points into bucket 1

The point being that each action can be pretty different from the other. How can I represent this information as an object in C#? I can think of 4 ugly ways...

Just pass a list of strings containing the choice text to the UI and have the UI display them, then the user selects between them:

This is the most simplest (and very tempting) approach, but that would be mixing the UI with the Core Logic, which goes against the main idea behind the design.

Pass an object containing an enum and an object, whose actual type depends on the value of the enum (The enum being something like Draw, Allocate, etc., and the object containing things like the number of cards and which deck for the Draw choice, and the number of points and what bucket for the Allocate command)

But that involves a lot of if statements and typecasting and reflection, among other problems, which is ugly. It also means that I would have to make a separate class for almost every type of choice enum, which is also ugly because each class would just be a list of values.

Pass a dictionary contaning string keys and values, the content of the dictionary depending on the type of choice that one can make.

This will still involve a lot of typecasting and I also lose type safety, but at least I wouldn't have to make a class for every single choice.

Pass an object containing an enum and a dynamic object containing an anonymous type whose fields depend on what the value of the enum is.

This makes handling the stuff in the UI a lot more straightforward and I wouldn't have to make multiple classes, but then I lose type safety and basic checks during compile time..

Is there any sort of pattern that people usually use when facing this problem, or should I just pick my poison and go for it? Perhaps I should rethink my entire approach to the whole thing?

In C, I would probably be using a union of structs for this sort of thing. I'm not sure how I would go about it in C#. Perhaps I'm thinking too much in C?

答:
I would either use a base class with inherited classes or an interface with concrete implementations in order to distinguish the kind of choice the user can make.  Interfaces would make more sense if you needed to perform some kind of operation on the choice, but since that isn't in the scope of your question, here is an example of the former option using a base class with inheritance.

```<code>public class ChoiceOption
{
}

public class DrawChoiceType : ChoiceOption
{
    public int NumberToDraw { get; set; }
    public Deck DrawFrom { get; set; }
}

public class AllocatePointsChoiceType : ChoiceOption
{
    public int PointsToAllocate { get; set; }
    public Bucket AllocatePointsTo { get; set; }
}
</code>```

With this structure, your game engine will pass the list of choices to the player and handle the choice made like this:

```<code>List<ChoiceOption> choicesAvailableToPlayer = new List<ChoiceOption>();
choicesAvailableToPlayer.Add(new DrawChoiceType() { DrawFrom = Decks.DeckA, NumberToDraw = 5 });
choicesAvailableToPlayer.Add(new DrawChoiceType() { DrawFrom = Decks.DeckB, NumberToDraw = 2 });
choicesAvailableToPlayer.Add(new AllocatePointsChoiceType () { AllocatedPointsTo = Buckets.Bucket1, PointsToAllocate = 4 });
ChoiceOption playerChose = player.Callback(choicesAvailableToPlayer);
if (playerChose is DrawChoiceType)
{
    //Do whatever needs to be done in the game engine for this selection.
}
else if (playerChose is AllocatePointsChoiceType)
{
     //Do whatever needs to be done in the game engine for this selection.
}
</code>```

I'm not sure how your UI code is displaying these choice options to the user, but it would be very simple to drive the UI from this structure.

Body:
I would either use a base class with inherited classes or an interface with concrete implementations in order to distinguish the kind of choice the user can make.  Interfaces would make more sense if you needed to perform some kind of operation on the choice, but since that isn't in the scope of your question, here is an example of the former option using a base class with inheritance.

public class ChoiceOption
{
}

public class DrawChoiceType : ChoiceOption
{
    public int NumberToDraw { get; set; }
    public Deck DrawFrom { get; set; }
}

public class AllocatePointsChoiceType : ChoiceOption
{
    public int PointsToAllocate { get; set; }
    public Bucket AllocatePointsTo { get; set; }
}

With this structure, your game engine will pass the list of choices to the player and handle the choice made like this:

List<ChoiceOption> choicesAvailableToPlayer = new List<ChoiceOption>();
choicesAvailableToPlayer.Add(new DrawChoiceType() { DrawFrom = Decks.DeckA, NumberToDraw = 5 });
choicesAvailableToPlayer.Add(new DrawChoiceType() { DrawFrom = Decks.DeckB, NumberToDraw = 2 });
choicesAvailableToPlayer.Add(new AllocatePointsChoiceType () { AllocatedPointsTo = Buckets.Bucket1, PointsToAllocate = 4 });
ChoiceOption playerChose = player.Callback(choicesAvailableToPlayer);
if (playerChose is DrawChoiceType)
{
    //Do whatever needs to be done in the game engine for this selection.
}
else if (playerChose is AllocatePointsChoiceType)
{
     //Do whatever needs to be done in the game engine for this selection.
}

I'm not sure how your UI code is displaying these choice options to the user, but it would be very simple to drive the UI from this structure.


问:
Best practice to extend Model in View Model
I'm facing an issue where I have a Model which I want to implement a GUI for. As I'm exploring MVVM and WPF I will of course use a View Model between the View and Model. I will also have a need to add coordinates to some model classes that represents objects that will be drag able in the GUI. At this time, this is the only addition to these particular model classes that I need. At least at this moment. At the same time almost all, if not all, information contained in the model objects is of interest to the view.

The most important model classes are:

Table

Columns

Dependencies

Tables know of its columns.

Columns know which Table they belongs to.

Columns know 1..* Dependencies

Dependencies know 1..* column it represents a dependency to.

It would of course be possible to modify how these objects know of each other, if needed.

The real question here though, is; How do I make the model classes available to the View, when at the same time adding coordinates to Tables, Columns and Dependencies?

One way might be to create something like this:

```<code>public class TableViewModel
{
    public Model.Table ModelTable { get; private set; }
    public List<ColumnViewModel> Columns { get; set; }
    public float X { get; set; }
    public float Y { get; set; }
}
</code>```

Is this a preferred way to forward an "extended" Model object to the View or are there patterns specifically engineered for this task?

Would regular inheritance between the objects in Model and View Model work? I'm not sure though, I like the coupling that would cause.

Or should I create View Model classes that are tailored to fit the View and then map properties from the Model object to the View Model object? This would completely remove the coupling between View and Model, but create two objects in memory, and in this case these might be very big models. Will the garbage collector drop the model objects since there will be no more references to them after they have been mapped to the view model?

答:
The real question here though, is; How do I make the model classes available to the View, when at the same time adding coordinates to Tables, Columns and Dependencies?

Your example ViewModel should do just fine.  Another way that I've seen it accomplished is with a BaseViewModel<T> class that all ViewModels inherit from and takes the type of model and then exposes that as T Model { get; }

Is this a preferred way to forward an "extended" Model object to the View or are there patterns specifically engineered for this task?

The ViewModel has the responsibility of getting whatever models/data and keeping and modifying whatever UI state the View needs.  Your example ViewModel seems to fit this responsibilty.  However, I would only use a ViewModel class within a ViewModel if I'm also presenting the a "sub view" that goes along with that ViewModel.  For instance, I would only use List<ColumnViewModel> if I was going to be looping through them and dynamically adding or including a control that's tied to the ColumnViewModel.

Would regular inheritance between the objects in Model and View Model work?

Although it could work, I think inheriting your ViewModel from the Model would be confusing.  Plus, what if your Model is really a list of Model objects?  Inheritance would be trickier in that case because you would need to make your base class a List<Model> and you would be exposing a bunch of unncessary methods to the View.  I think wrapping is a better alternative.

Or should I create View Model classes that is tailored to fit the View and then map properties from the Model object to the View Model object?

ViewModels are generally tailored to fit the specific needs of a View.  I tend to think of ViewModels as the code-behind for the view.  The mapping of the model properties is generally done through the binding in the WPF View.

Will the garbage collector drop the model objects since there will be no more references to them after they have been mapped to the view model?

This all depends on your context, any references held by the objects in question and a variety of other factors.  Generally, your view model should have the same life-time as your view and that includes the data.  However, if there are specific performance concerns, you can always manually clear out the Model once it's been loaded.


问:
API and a shared API client
We are a startup kind of a project that fired pretty well and as all startups the main goal was to start ASAP. We made our project as a monolith application (PHP) that has 4 sub-applications, but will require more than that in a couple of months. We decided it's time to move to microservices before it's too late, so we try to separate this application into small pieces like:

API

CRM

Workers

Frontend

other sub-projects, something between frontend and CRM.

Currently the project is something similar to the MVC (I understand it's not an MVC in PHP, but lets say it's like that).
We have Routing, Controllers, Views and on the domain layer we have Repositories & Entities.

Entities are not used as raw value objects, but as well know about their children, let's say if we have a $user entity, it knows how to $user->getArticles() retrieve articles belonging to that user. (It uses repositories here).

Services will communicate using the JSON format and HTTP protocol and not AMQP.

Each service will reside on it's own node, all nodes will be on one network and this question is not about performance so I will not discuss about it any longer.

The problem is that all services must communicate with the API and we would really like to stick to working with entities.

Personally, I think the right way would be to migrate entities to a shared sub-project like APIClient and use that as a composer package in all of the project parts.

Despite that, I think there are many nuances here, like maintaining the correct version of the API client for each project.

Question:
What is the proper way to share entity objects and use an API as the only part of the project that communicates with the DB?

Maybe I am overthinking and it's easier to create separate entities for each project, that is, only entities and functionality it needs and make the API Client return only JSON/array/stdClass?

Maybe someone may link to a "success story" on this topic, but PHP related?

I really hope I did ask the question clearly. If not, let me explain the parts you didn't understand.

Edit: I have drawn this diagram, maybe it will be clearer why I'd like to have entities shared.

```<code>  DB
   |
Repository
   |
 Entity ----|
   |        |
  API       |
   |        |
   |        |--------|
[ HTTP ]    | Shared |
   |        |--------|
   |        |
API CLI     |
   |        |
 Entity ----|
   |
do stuff
</code>```

答:
I'm starting a similar project which involves handling data from diferent clients (administrator, client's intranet, front-end and API)

In my design, me have moved ALL of the logic to a layer called service, which is gonna be instantiated in each off the clients.

We are not comunicating with the service layer throught http, but instantiating the "userService" / "authenticationService" everywhere and on every client that needs it.

All 4 apps are are in the same project so that performance wise it is amazingly fast.

With these structure, the UserController on the front-end app just instatiates the UserService and calls a method like -> UserService->getUser();

The good thing is that none of the client have to care about how to get data, because all logic is mantained in the service.

Not sure if I explained myself well, at least I tried.

Title: API and a shared API client


答:
Would I have to call my basic CRUD operations (located in my
  repository layer) from controllers directly, without passing through
  the domain layer?

I think this is ok. Just take a note, that if you have your application split into three layers (UI, domain logic and storage), in your case UI will depend both on domain logic and storage layers.

If persistence is used only from domain logic layer, UI layer is left depending on domain logic layer only.

Without seeing your actual application it's hard to say, if that is good or bad.

Title: CRUD operations in DDD

Body:
I'm designing an application with DDD. I'm moving from flat POCO objects to strong domain models, so my question is:

Would I have to call my basic CRUD operations (located in my repository layer)  from controllers directly, without passing through the domain layer? I can't see any added value to doing that, but I'm not sure if it's inside the DDD practices make that direct call.


答:
The typical entry point for this in DDD is an Application Service. Application services orchestrate calls to repositories and domain objects. They also know about the current execution state and often control the overarching business transaction through a unit of work that is committed at the end of the service method.

For example :

```<code>Create new domain object
Add it to Repository
Commit UoW

or

Get domain object from Repository
Modify it
Commit UoW

etc.
</code>```

The application service can be called from a Controller. In some implementations it is the controller, when people don't want to bother an additional abstraction layer. But that can lead to a Fat Controller.

my basic CRUD operations (located in my repository layer)

While C, R and D are part of a Repository interface, U doesn't have to if you have a Unit of Work. Update of all changed domain entities in the UoW will be done automatically on UoW.Save().

Title: CRUD operations in DDD

Body:
The typical entry point for this in DDD is an Application Service. Application services orchestrate calls to repositories and domain objects. They also know about the current execution state and often control the overarching business transaction through a unit of work that is committed at the end of the service method.

For example :

Create new domain object
Add it to Repository
Commit UoW

or

Get domain object from Repository
Modify it
Commit UoW

etc.

The application service can be called from a Controller. In some implementations it is the controller, when people don't want to bother an additional abstraction layer. But that can lead to a Fat Controller.

my basic CRUD operations (located in my repository layer)

While C, R and D are part of a Repository interface, U doesn't have to if you have a Unit of Work. Update of all changed domain entities in the UoW will be done automatically on UoW.Save().


答:
Data source doesn't mean database. You could perfectly have a Repository that talks to a remote service instead of a DB. The important thing is that from a client code perspective, the Repository looks like it's a collection you can look into, add to or remove from. It's a useful abstraction.

From Martin Fowler's PoEAA :

A Repository mediates between the domain and data mapping layers,
  acting like an in-memory domain object collection

There's probably a lot to say about the static nature of your Repository, notably because a static method can't implement an interface, but in spirit I think it does satisfy the contract.

Title: Can I wrap a collection with a static class and still call it repository pattern?

Body:
I couldn't find a single example about repository pattern using something else then a database.

My goal is to have a global static repository that stores some objects in memory. I don't want it to be a singleton with it's Instance property because it doesn't have any special function but Add/Removoe... just like a repository.

So let's assume I want to keep a collection of object converters somewhere in memory. Am I misusing the repository pattern for this (becuase it seems to be the most suitable solution here)? Or do you call it something else and repository is reserved only for databases or other storage types?

```<code>public static ConvertersRepository : IConvertersRepository
{
    // this is the actual collection
    private static IList<IObjectConvereter> _converters = new List<IObjectConvereter>;
    public static void AddObjectConverter(IObjectConvereter...) {}
    public static IObjectConvereter GetObjectConverter(...) {}
}
</code>```


答:
Yes, while both Cartesian and Polar are (in their place) eminently sensible coordinate representation schemes, they should ideally never be mixed (if you have a point Cartesian{1,1}, it is a very different point from Polar{1,1}).

Depending on your needs, it may also be worth implementing a Coordinate interface, with methods like X(), Y(), Displacement() and Angle() (or possibly Radius() and Theta(), depending on).

Title: Two structs with the same members but different naming, is it a good idea?

Body:
I am writing a program that involves working with both polar and Cartesian coordinates.

Does it make sense to create two different structs for each kind of points, one with X and Y members and one is with R and Theta members.

Or is it too much and it is better to have just one struct with first and second as members.

What I am writing is simple and it won't change much. But I am curious what is better from a design point of view.

I am thinking the first option is better. It seems more readable and I will get the benefit of type checking.


问:
Time Complexity when Loop Variable Depends upon Outer Loop Variable
What is the time complexity of the following piece of code in worst case?

```<code>s = 0;
for( i = 1; i <= n; ++i ) {
    for( j = 1; j <= i * i; j++ ) {
        for( k = 1; k <= j and j % i == 0; k++ )
            s++;
    }
}
</code>```

Each loop depend on the outer loop variable. How should I proceed in such a case?

The innermost loop will run only occasionally, so how can I evaluate this case?

For every increment of i middle loop runs i^2 times. For every iteration of middle loop, I'm not able to calculate how many times the innermost loop will run in terms of the outer loop.

I think innermost loop iterates for i times. The middle loop runs for j = 1 to i^2 and j % i != 0 is in i cases and for other i cases, j % i = 0. As inner loop runs for j % i == 0 it would be iterated i times.

Now for the times the innermost loop runs i times, the middle loop runs i^2 times and the outer loop runs i times, I think the complexity is  n^4.

答:
While the end result is correct, I wouldn't accept what is written in the question as an answer, because I can't really see how it gets to the answer.

The innermost loop: There are two cases. If j % i ≠ 0 then it iterates once, if j % i = 0 then it iterates j times.

The middle loop: Given i, it iterates i^2 times. The value of j will range from 1 to i^2. There are i cases j = i, j = 2i, j = 3i, ..., j = i^2 where j % i = 0, and i^2 - i cases where j % i ≠ 0. The inner loop will iterate once (i^2 - i) times. The inner loop will iterate j times when j = i, j = 2i, j = 3i, ..., j = i^2. The total number of iterations is the sum of (t * i) for 1 ≤ t ≤ i, which is i * (i - 1)/2 * i which is about i^3 / 2. The other cases only involved i^2 - i operations and can therefore be ignored. Summary: Given i, the middle loop performs about i^3 / 2 operations.

The outer loop: i ranges from 1 to n. There are i^3 / 2 operations for each iteration. So the total number of operations is the sum of (i^3 / 2) for i = 1 to n, which is about i^4 / 8.


问:
Advantages and possible drawbacks of using Java for cross-platform development vs. .NET?
If I were to begin writing an application using Java with the intention of porting it to other platforms with little or no modification, would it be wise to consider using the .Net framework instead?

I have no specific targets in mind with respect to platform. At a minimum, Windows/Mac/Linux support would be nice. Also ease-of-use for the end-user is a consideration.

答:
I'd say go with what you like. If you - while coding - keep in mind that the app has to run on different systems and test early and often I bet you're going to be o.k.

I haven't written any java in a long time „in the early days” porting wasn't always fun either. (i.e. 3D graphics come to mind...)

If you choose mono/.net you either need use windows.forms and do all your forms in windows (there is currently no windows.forms ui-editor in linux) or you could use gtk and have your windows-users install gtk first.

I personally have (in 2 projects now) doubled the ui. Wpf for Windows, gtk for the rest...

ContentLicense: CC BY-SA 2.5


答:
substring ("abc", 0) gives you three characters.

substring ("abc", 1) gives you two characters, one less.

substring ("abc", 2) gives you one character, one less again.

At this point you expect substring ("abc", 3) to give you one character less again, which would be zero characters. It's possible to return zero characters (result = "") so that's what it returns.

substring ("abc", 4) should give one character less again, which would be -1 characters. Clearly, that's not possible, so there's no reasonable result that this could return to you. Accordingly, it fails.


问:
A proper way to work with MVC
I got into a debate at work today, I hope you can help me to settle it up.

My colleague wants to separate UI, Model, DB, and Network like so:

Create an API level between UI and controller, that will allow the UI
to query all the models in the APP.

There will be another controller that will break the models into
their DB representations (Ex: UserTablesModel, ScoreTableModel...),
It will be a singleton called DBControler and it will
also provide some utility methods to query the DB (Ex:
insert(tableName, value...).

The ModelTables will use events hub to notify UI with state changes,
and they will be updated from the network layer using DBControler
reference.

I don't like this idea as it creates a coupling between unrelated models in the controller layer. I think it would be wiser to allow the UI to have direct access to Models (maybe make them singletons) and it's up to the model to offer a proper API to access its data and provide an events callback to notify his state change (no events hub). I like the part that models need to be directly updated from the network layer.

Also I don't like the name TableModel, I think the DB needs to be a service accessible by the model, one model can access multiple tables.

What is the proper way to work with MVC?

答:
I'd seriously recommend looking into viewmodels. How the data is presented in the database isn't always how you'd want it presented in the UI.

A common example is prices - where it might be stored as an int or decimal in the DB. However, in the UI, you'd maybe want the currency symbol and digit grouping so:

$1,999 rather than 1999.

Adding this logic to the UI or model makes no sense - and with a viewmodel, the UI & model can be kept clean: the UI just serves up the data, the viewmodel only contains the data and logic required, and the model stores the initial representation of the data.

This page describes its use in ASP.NET MVC, but the general principles are sound.

Title: A proper way to work with MVC


问:
How should you look at unit testing protected members used by the abstract base class?
I have the following class(es) that I want to write unit tests for:

```<code>public abstract class BaseClass
{
    public bool IsFooBar(Order order)
    {
        return order.IsNew && IsFooBarOverride(order);
    }

    protected abstract IsFooBarOverride(Order order);
}

public class SimpleDerivedClass : BaseClass
{
    protected override bool IsFooBarOverride(Order order)
    {
        // Return if the order is with a credit card.
    }
}

public class ComplexDerivedClass : BaseClass
{
    protected override bool IsFooBarOverride(Order order)
    {
        // Return a very complex statement
        // If the order is for a new customer
        // in New York, with an order amount of $500 or more
        // and has at opted for email subscriptions.
    }
}
</code>```

The problem I am running into is that my derived classes contain the majority of my logic for determining the return value of IsFooBar(Order order). I want to test this logic to ensure it is proper. I was under the impression that you should only test the public API of a class, which is IsFooBar(Order order), which belongs to the base class.

Should I redesign my class structure by marking IsFooBar virtual and hope that other developers on the team use base.IsFooBar(order) as part of their return statement?

Should I leave my class structure in tact and test variations of the IsFooBar(Order order) method per derived class as a way to test the logic in the protected class?

答:
I was under the impression that you should only test the public API of a class, which is IsFooBar(Order order), which belongs to the base class.

Not quite.

That method is protected and so is only available to subclasses.

OK, it's accessible outside the class (to a degree), but it's certainly not "public".

... my derived classes contain the majority of my logic for determining the return value of IsFooBar(Order order). I want to test this logic to ensure it is proper.

Since the implementation of these overridden methods is what you need to test, then write tests for the concrete classes (I, for one, don't know how to test an instance method on an abstract class, because you can't instantiate that class so, from a purely practical standpoint, you have to work with (i.e. test) the subclasses.

If the bulk of the code were in [abstract]  base class implementation of a given method, then you might consider writing a [concrete] subclass purely for testing purposes.


问:
Are there any significant disadvantages to depending upon abstractions?
I was reading this wiki on the Stable Abstractions Principle (SAP).

The SAP states that the more stable a package the more abstract it should be. This implies that if a package is less stable (more likely to change) then it should be more concrete. What I don't really understand is why this should be the case. Surely in all cases regardless of stability we should be depending upon abstractions and hiding the concrete implementation?

答:
Think of your packages as an API, to take the example from the paper, take definitions for Reader with string Reader.Read() and Writer with void Writer.Write(string) as your abstract API.

You can then create a class Copy with a method Copier.Copy(Reader, Writer) and the implementation Writer.Write(Reader.Read()) and maybe some sanity checks.

Now, you make concrete implementations, e.g. FileReader, FileWriter, KeyboardReader and DownloadThingsFromTheInternetReader.

What if you want to change your implementation of FileReader? No problem, just change the class and recompile.

What if you want to change the definition of your abstraction Reader? Oops, you cannot just change that, but you will also have to change Copier, FileReader,  KeyboardReader and DownloadThingsFromTheInternetReader.

This is the rationale behind the Stable Abstraction Principle: Make your concretisations less stable than the abstractions.


问:
the future of commercial products
I'm seeing that the open source solutions are growing rapidly & many companies use them now.  What do you think the future for commercial products or solutions will be?</p>

答:
I think there will be enough rooms for both: commercial & open source. The FOSS have great support from community, but it lacks the ability of direction.

Most of technology revolution that I have seen rise to be an entrepreneur. Google, Facebook, Iphone, Ipad,... and they are all associated with some famous name, like Steve Jobs, Mark Zukernberg. The open source community is large, but divided. There are lots of distro for Linux, for example.

Title: the future of commercial products


问:
Using compound statements ("{" ... "}" blocks) to enforce variable locality

Introduction

Many "C-like" programming languages use compound statements (code blocks specified with "{" and "}") to define a variables scope.

Here is a simple example.

```<code>for (int i = 0; i < 100; ++i) {
    int value = function(i); // Here 'value' is local to this block
    printf("function(%d) == %d\n", i, value);
}
</code>```

This is good because it limits the scope of the value to where it is used. It is hard for programmers to use value in ways that they are not meant to because they can only access it from within its scope.

I am almost all of you are aware of this and agree that it is good practice to declare variables in the block they are used to limit their scope.

But even though it is an established convention to declare variables in their smallest possible scope it is not very common to use an naked compound statement (that is an compound statement that is not connected to an if, for, while statement).

Swapping the values of two variables

Programmers often write the code like this:

```<code>int x = ???
int y = ???

// Swap `x` and `y`
int tmp = x;
x = y;
y = tmp;
</code>```

Would it not be better to write the code like this:

```<code>int x = ???
int y = ???

// Swap `x` and `y`
{
    int tmp = x;
    x = y;
    y = tmp;
}
</code>```

It looks quite ugly but I think that this is a good way to enforce variable locality and make the code safer to use.

This does not only apply to temporaries

I often see similar patterns where a variable is used once in a function

```<code>Object function(ParameterType arg) {
    Object obj = new Object(obj);
    File file = File.open("output.txt", "w+");
    file.write(obj.toString());

    // `obj` is used more here but `file` is never used again.
    ...
}
</code>```

Why don't we write it like this?

```<code>RET_TYPE function(PARAM_TYPE arg) {
    Object obj = new Object(obj);
    {
       File file = File.open("output.txt", "w+");
       file.write(obj.toString());
    }

    // `obj` is used more here but `file` is never used again.
    ...
}
</code>```

Summary of question

It is hard to come up with good examples. I am sure that there are betters ways to write the code in my examples but that is not what this question is about.

My question is why we do not use "naked" compound statements more to limit the scope of variables.

What do you think about using a compound statement like this

```<code>{
    int tmp = x;
    x = y;
    y = z;
}
</code>```

to limit the scope of tmp?

Is it good practice? Is it bad practice? Explain your thoughts.

答:
It is indeed a good practice to keep your variable's scope small. However, introducing anonymous blocks into large methods only solves half the problem: the scope of the variables shrinks, but the method (slightly) grows!

The solution is obvious: what you wanted to do in an anonymous block, you should be doing in a method. The method gets its own block and its own scope automatically, and with a meaningful name you get better documentation out of it, too.


答:
Often if you find places to create such a scope it's an opportunity to extract out a function.

In a language with pass-by-reference you would instead call swap(x,y).

For writing the file that would be advisable to use the block to ensure RAII will close the file and free up the resources as soon as possible.

Title: Using compound statements ("{" ... "}" blocks) to enforce variable locality

Body:
Introduction

Many "C-like" programming languages use compound statements (code blocks specified with "{" and "}") to define a variables scope.

Here is a simple example.

```<code>for (int i = 0; i < 100; ++i) {
    int value = function(i); // Here 'value' is local to this block
    printf("function(%d) == %d\n", i, value);
}
</code>```

This is good because it limits the scope of the value to where it is used. It is hard for programmers to use value in ways that they are not meant to because they can only access it from within its scope.

I am almost all of you are aware of this and agree that it is good practice to declare variables in the block they are used to limit their scope.

But even though it is an established convention to declare variables in their smallest possible scope it is not very common to use an naked compound statement (that is an compound statement that is not connected to an if, for, while statement).

Swapping the values of two variables

Programmers often write the code like this:

```<code>int x = ???
int y = ???

// Swap `x` and `y`
int tmp = x;
x = y;
y = tmp;
</code>```

Would it not be better to write the code like this:

```<code>int x = ???
int y = ???

// Swap `x` and `y`
{
    int tmp = x;
    x = y;
    y = tmp;
}
</code>```

It looks quite ugly but I think that this is a good way to enforce variable locality and make the code safer to use.

This does not only apply to temporaries

I often see similar patterns where a variable is used once in a function

```<code>Object function(ParameterType arg) {
    Object obj = new Object(obj);
    File file = File.open("output.txt", "w+");
    file.write(obj.toString());

    // `obj` is used more here but `file` is never used again.
    ...
}
</code>```

Why don't we write it like this?

```<code>RET_TYPE function(PARAM_TYPE arg) {
    Object obj = new Object(obj);
    {
       File file = File.open("output.txt", "w+");
       file.write(obj.toString());
    }

    // `obj` is used more here but `file` is never used again.
    ...
}
</code>```

Summary of question

It is hard to come up with good examples. I am sure that there are betters ways to write the code in my examples but that is not what this question is about.

My question is why we do not use "naked" compound statements more to limit the scope of variables.

What do you think about using a compound statement like this

```<code>{
    int tmp = x;
    x = y;
    y = z;
}
</code>```

to limit the scope of tmp?

Is it good practice? Is it bad practice? Explain your thoughts.


答:
Congratulations, you've got scope isolation of some trivial variables in a large and complex function.

Unfortunately, you've got a large and complex function. The proper thing to do is instead of creating a scope within the function for the variable, to extract it to its own function. This encourages reuse of the code and allows for the enclosing scope to be passed in as parameters to the function and not be pseudo-global variables for that anonymous scope.

This means that everything outside of the scope of the unnamed block is still in scope in the unnamed block.  You are effectively programming with globals and unnamed functions run serially without any way to have code reuse.

Furthermore, consider that in many runtimes, all variable declaration within the anonymous scopes is declared and allocated at the top of the method.

Lets look at some C# (https://dotnetfiddle.net/QKtaG4):

using System;

public class Program
{
    public static void Main()
    {
        string h = "hello";
        string w = "world";
        {
            int i = 42;
            Console.WriteLine(i);
        }
        {
            int j = 4;
            Console.WriteLine(j);
        }
        Console.WriteLine(h + w);
    }
}
```

<p>And when you start digging into the IL for the code (with dotnetfiddle, under 'tidy up' there is also 'View IL'), right there at the top it shows what has been allocated for this method:</p>

```.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    .method public hidebysig static void Main() cli managed
    {
      //
      .maxstack 2
      .locals init (string V_0,
          string V_1,
          int32 V_2,
          int32 V_3)
```

<p>This allocates the space for two strings and two integers at the initialization of the method Main, even though only one int32 is in scope at any given time.  You can see a more in depth analysis of this on a tangential topic of initializing variables at Foreach loop and variable initialization.</p>

<p>Lets look at some Java code instead.  This should look rather familiar.</p>

<pre class="lang-java prettyprint-override"><code>public class Main {
    public static void main(String[] args) {
        String h = "hello";
        String w = "world";
        {
            int i = 42;
            System.out.println(i);
        }
        {
            int j = 4;
            System.out.println(j);
        }
        System.out.println(h + w);
    }
}
</code>```

Compile this with javac, and then invoke javap -v Main.class and you get the Java class file disassembler.

Right there at the top, it tells you how many slots it needs for local variables (output of javap command goes into the explication of the parts of it a bit more):

```<code>  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=3, locals=4, args_size=1
</code>```

It needs four slots. Even though two of these local variables are never in the scope at the same time, it still allocates room for four local variables.

On the other hand, if you give the compiler the option, extracting short methods (such as a 'swap') will do a better job of inlining the method and making more optimal use of variables.

Body:
Congratulations, you've got scope isolation of some trivial variables in a large and complex function.

Unfortunately, you've got a large and complex function. The proper thing to do is instead of creating a scope within the function for the variable, to extract it to its own function. This encourages reuse of the code and allows for the enclosing scope to be passed in as parameters to the function and not be pseudo-global variables for that anonymous scope.

This means that everything outside of the scope of the unnamed block is still in scope in the unnamed block.  You are effectively programming with globals and unnamed functions run serially without any way to have code reuse.

Furthermore, consider that in many runtimes, all variable declaration within the anonymous scopes is declared and allocated at the top of the method.

Lets look at some C# (https://dotnetfiddle.net/QKtaG4):

using System;

public class Program
{
    public static void Main()
    {
        string h = "hello";
        string w = "world";
        {
            int i = 42;
            Console.WriteLine(i);
        }
        {
            int j = 4;
            Console.WriteLine(j);
        }
        Console.WriteLine(h + w);
    }
}

And when you start digging into the IL for the code (with dotnetfiddle, under 'tidy up' there is also 'View IL'), right there at the top it shows what has been allocated for this method:

.class public auto ansi beforefieldinit Program
    extends [mscorlib]System.Object
{
    .method public hidebysig static void Main() cli managed
    {
      //
      .maxstack 2
      .locals init (string V_0,
          string V_1,
          int32 V_2,
          int32 V_3)

This allocates the space for two strings and two integers at the initialization of the method Main, even though only one int32 is in scope at any given time.  You can see a more in depth analysis of this on a tangential topic of initializing variables at Foreach loop and variable initialization.

Lets look at some Java code instead.  This should look rather familiar.

public class Main {
    public static void main(String[] args) {
        String h = "hello";
        String w = "world";
        {
            int i = 42;
            System.out.println(i);
        }
        {
            int j = 4;
            System.out.println(j);
        }
        System.out.println(h + w);
    }
}

Compile this with javac, and then invoke javap -v Main.class and you get the Java class file disassembler.

Right there at the top, it tells you how many slots it needs for local variables (output of javap command goes into the explication of the parts of it a bit more):

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=3, locals=4, args_size=1

It needs four slots. Even though two of these local variables are never in the scope at the same time, it still allocates room for four local variables.

On the other hand, if you give the compiler the option, extracting short methods (such as a 'swap') will do a better job of inlining the method and making more optimal use of variables.


答:
Depending on your unit test framework, you can write an abstract base test class that will contain assertions about what your abstract production class should do.

All subclasses of that base test class will automatically run these "parent" tests as well as any other tests related to their specific concrete System Under Test.

To generate the System Under Test, you can resort to a Factory method (or Factory Property) pattern.

Example with NUnit :

```<code>[TestFixture]
public abstract class BaseTest
{
    protected abstract BaseClass Sut { get; }

    [Test]
    public void An_old__order_should_never_be_FooBar()
    {
        var result = Sut.IsFooBar(new Order {IsNew = false});
        Assert.IsFalse(result, "An old Order should never be FooBar no matter the concrete implementation");
    }
}

public class SimpleDerivedClassTest : BaseTest
{
    protected override BaseClass Sut { get { return new SimpleDerivedClass(); } }

    // Your other, SimpleDerived-specific tests here
}

public class ComplexDerivedClassTest : BaseTest
{
    protected override BaseClass Sut { get { return new ComplexDerivedClass(); } }

    // Your other, ComplexDerived-specific tests here
}
</code>```

As a side note, in the particular example you chose it might not seem so easy to determine what assertions will hold in all circumstances and should therefore go in the base test class. But it is in fact quite trivial (all !IsNew Orders should be !FooBar...)

Title: How should you look at unit testing protected members used by the abstract base class?

Body:
I have the following class(es) that I want to write unit tests for:

```<code>public abstract class BaseClass
{
    public bool IsFooBar(Order order)
    {
        return order.IsNew && IsFooBarOverride(order);
    }

    protected abstract IsFooBarOverride(Order order);
}

public class SimpleDerivedClass : BaseClass
{
    protected override bool IsFooBarOverride(Order order)
    {
        // Return if the order is with a credit card.
    }
}

public class ComplexDerivedClass : BaseClass
{
    protected override bool IsFooBarOverride(Order order)
    {
        // Return a very complex statement
        // If the order is for a new customer
        // in New York, with an order amount of $500 or more
        // and has at opted for email subscriptions.
    }
}
</code>```

The problem I am running into is that my derived classes contain the majority of my logic for determining the return value of IsFooBar(Order order). I want to test this logic to ensure it is proper. I was under the impression that you should only test the public API of a class, which is IsFooBar(Order order), which belongs to the base class.

Should I redesign my class structure by marking IsFooBar virtual and hope that other developers on the team use base.IsFooBar(order) as part of their return statement?

Should I leave my class structure in tact and test variations of the IsFooBar(Order order) method per derived class as a way to test the logic in the protected class?

Body:
Depending on your unit test framework, you can write an abstract base test class that will contain assertions about what your abstract production class should do.

All subclasses of that base test class will automatically run these "parent" tests as well as any other tests related to their specific concrete System Under Test.

To generate the System Under Test, you can resort to a Factory method (or Factory Property) pattern.

Example with NUnit :

[TestFixture]
public abstract class BaseTest
{
    protected abstract BaseClass Sut { get; }

    [Test]
    public void An_old__order_should_never_be_FooBar()
    {
        var result = Sut.IsFooBar(new Order {IsNew = false});
        Assert.IsFalse(result, "An old Order should never be FooBar no matter the concrete implementation");
    }
}

public class SimpleDerivedClassTest : BaseTest
{
    protected override BaseClass Sut { get { return new SimpleDerivedClass(); } }

    // Your other, SimpleDerived-specific tests here
}

public class ComplexDerivedClassTest : BaseTest
{
    protected override BaseClass Sut { get { return new ComplexDerivedClass(); } }

    // Your other, ComplexDerived-specific tests here
}

As a side note, in the particular example you chose it might not seem so easy to determine what assertions will hold in all circumstances and should therefore go in the base test class. But it is in fact quite trivial (all !IsNew Orders should be !FooBar...)


答:
I assume you do not know, yet, of Expression-Oriented languages?

In Expression-Oriented languages, (nearly) everything is an expression. This means, for example, that a block can be an expression as in Rust:

// A typical function displaying x^3 + x^2 + x
fn typical_print_x3_x2_x(x: i32) {
    let y = x * x * x + x * x + x;
    println!("{}", y);
}
```

<p>you may be worried that the compiler will redundantly compute <code>x * x</code> though, and decided to memorize the result:</p>

<pre class="lang-rust prettyprint-override"><code>// A memoizing function displaying x^3 + x^2 + x
fn memoizing_print_x3_x2_x(x: i32) {
    let x2 = x * x;
    let y = x * x2 + x2 + x;
    println!("{}", y);
}
</code>```

However, now x2 clearly outlives its usefulness. Well, in Rust a block is an expression which returns the value of its last expression (not of its last statement, so avoid a closing ;):

// An expression-oriented function displaying x^3 + x^2 + x
fn expr_print_x3_x2_x(x: i32) {
    let y = {
        let x2 = x * x;
        x * x2 + x2 + x // <- missing semi-colon, this is an expression
    };
    println!("{}", y);
}
```

<p>Thus I would say that newer languages have recognized the importance of limiting the scope of variables (makes things cleaner), and are increasingly offering facilities to do so.</p>

<p>Even notable C++ experts such as Herb Sutter are recommending anonymous blocks of this kind, "hacking" lambdas to initialize constant variables (because immutable is great):</p>

<pre class="lang-c prettyprint-override"><code>int32_t const y = [&]{
    int32_t const x2 = x * x;
    return x * x2 + x2 + x;
}(); // do not forget to actually invoke the lambda with ()
</code>```

Body:
I assume you do not know, yet, of Expression-Oriented languages?

In Expression-Oriented languages, (nearly) everything is an expression. This means, for example, that a block can be an expression as in Rust:

// A typical function displaying x^3 + x^2 + x
fn typical_print_x3_x2_x(x: i32) {
    let y = x * x * x + x * x + x;
    println!("{}", y);
}

you may be worried that the compiler will redundantly compute x * x though, and decided to memorize the result:

// A memoizing function displaying x^3 + x^2 + x
fn memoizing_print_x3_x2_x(x: i32) {
    let x2 = x * x;
    let y = x * x2 + x2 + x;
    println!("{}", y);
}

However, now x2 clearly outlives its usefulness. Well, in Rust a block is an expression which returns the value of its last expression (not of its last statement, so avoid a closing ;):

// An expression-oriented function displaying x^3 + x^2 + x
fn expr_print_x3_x2_x(x: i32) {
    let y = {
        let x2 = x * x;
        x * x2 + x2 + x // <- missing semi-colon, this is an expression
    };
    println!("{}", y);
}

Thus I would say that newer languages have recognized the importance of limiting the scope of variables (makes things cleaner), and are increasingly offering facilities to do so.

Even notable C++ experts such as Herb Sutter are recommending anonymous blocks of this kind, "hacking" lambdas to initialize constant variables (because immutable is great):

int32_t const y = [&]{
    int32_t const x2 = x * x;
    return x * x2 + x2 + x;
}(); // do not forget to actually invoke the lambda with ()


答:
Contrasting all the nay-sayers, let's assume real business need.

(for example, deliverable is source code, customers are from same line of business and therefore competitors to each other, and you business model promises to keep their secrets secret)

Furthermore, let's assume that your company has the tools to maintain all the branches, that is either manpower (let's say 100 developers dedicated to merging, assuming 5-day release delay; or 10 devs assuming 50-day release lag is OK), or such awesome automated testing that automated merges are truly tested both to core spec and extension spec in every branch, and thus only changes that don't merge "cleanly" require human intervention. If your customers pay not only for customisations but for maintenance thereof, this may be a valid business model.

My (and nay-sayers) question, is, do you have a dedicated person responsible for delivery to each customer? If you are, say, a 10,000-person company, it may be the case.

This could be handled by plugin architecture in some cases, let's say your core is trunk, plugins could be held in trunk or branches, and configuration for each customer is either a uniquely named file or is held in customer branch.

Plugins could be loaded at run time, or built in at compile time.

Truly many projects are done like this, fundamentally same problem still applies -- simple core changes are trivial to integrate, conflict changes must be either rolled back, or changes are needed to many plugins.

There are cases when plugins are not good enough, that's when so many internals of the core must be tweaked that plugin interface count becomes too large to handle.

Ideally this would be handled by aspect-oriented programming, where trunk is core code, and branches are aspects (that is extra code and instructions how to connect extras to core)

A simple example, you can specify that custom foo is ran before or after core klass.foo or that it replaces it, or that wraps it and can change input or output.

There's a ton of libraries for that, however the problem of merge conflicts does not go away -- clean merges are handled by AOP and conflicts still need human intervention.

Finally such business truly has to concern itself with branch maintenance, namely, is customer-specific feature X so common that it's cheaper to move it to core, even though not all customers are paying for it?


答:
Additional blocks/scopes add additional verbiage.  While the idea carries some initial appeal, you'll soon run into situations where it becomes unfeasible anyway because you have temporary variables with overlapping scope that cannot be properly reflected by a block structure.

So since you cannot make the block structure consistently reflect variable lifetimes anyway as soon as things get slightly more complex, bending over backwards for the simple cases where it does work seems like an exercise in eventual futility.

For data structures with destructors that lock up significant resources during their lifetime, there is the possibility to call the destructor explicitly.  As opposed to using a block structure, this does not mandate a particular order of destruction for variables introduced at different points of time.

Of course blocks have their uses when they are tied with logical units: particularly when using macro programming, the scope of any variable not explicitly named as macro argument intended for output is best restricted to the macro body itself in order not to cause surprises when using a macro several times.

But as lifetime markers for variables in sequential execution, blocks tend to be overkill.


答:
Good practice. Period. Full stop. You make it explicit to future readers that the variable is not used anywhere else, enforced by the rules of the language.

This is provisional politeness for the future maintainers, because you tell them something you know. These facts could take dozens of minutes to determine in a sufficiently lengthy or convoluted function.

The seconds you'll spend documenting this powerful fact by adding a pair of braces will pay off minutes for each maintainer who will not have to determine this fact.

The future maintainer can be yourself, years later, (because you're the only one who knows this code) with other things on your mind (because the project has long been over and you've been reassigned ever since), and under pressure. (because we're doing this graciously for the customer, you know, they've been long time partners, you know, and we had to smooth out our commercial relationship with them because the last project we delivered was not that up to expectations, you know, and oh, it is just a small change and it should not take that long for an expert like you, and we've got no budget so don't do "overquality")

You'd hate yourself for not doing it.


问:
Does testing the characteristics of a runtime have a generally accepted name?
I am working with PowerShell which doesn't seem to have an up-to-date language spec.  This leaves me wondering about some edge cases.  I've taken to testing my assumptions about how PowerShell's runtime behaves.  Here is a concrete example:

```<code>It 'the System.Exception that is thrown is actually a ParameterBindingException.' {
    $o = New-Object psobject -Property @{a=1}
    $o.a | Should be 1
    try
    {
        $o | f
    }
    catch [System.Exception]
    {
        $threw = $true
        $_.Exception.Message | Should match 'The input object cannot be bound because it did not contain the information required to bind all mandatory parameters:  b'
        $_.CategoryInfo.Reason | Should be 'ParameterBindingException'
        $_.Exception -is [System.Management.Automation.ParameterBindingException] | Should be $true
    }
    $threw | Should be $true
}
</code>```

That test asserts part of PowerShell Version 2.0's quirky exception catching behavior. (Evidently PS V2 throws ParameterBindingException that can be caught as Exeception but not ParameterBindingException.)

This kind of test doesn't seem to fit any definition of "Unit Test" or "Integration Test" I have found.  It tests the environment that code is executing in rather than the code itself.

I've spent some time searching for a name for this kind of testing but it seems like I'm just not using the key words.  Is there a generally-accepted term whose definition matches this kind of test?

答:
To my knowledge, there isn't a common, industry standard term for what you're asking about.

Capability based testing is probably the closest term you'll find to match what you're describing.  It's very common within web development to have a run-time test that probes the capabilities of the browser and reacts accordingly.

Capability based testing is fairly orthogonal to unit or integration testing, and I would discourage conflating the two ideas.  Capability based testing occurs at run-time and directs the flow of the code.  Unit and integration testing is intended to measure correctness and to provide validation that code is working as expected.


问:
Create separate GIT repository for publishing with different history?
I'm developing a project, which I'm pushing to private repository on my VPS. However, I'd like to publish it on GitHub.

I make a lot of commits(mostly as backups) which doesn't contain complete implementation of feature. I do not want to include history of these commits in public repo.

So, private history would look like:

Initial commit

Part Feature A

Part Feature A

Part Feature A

Finished Feature A

Part Feature B

Finished Feature B

... etc ...

And desired history of public repo would look like:

Initial commit

Feature A

Feature B

... etc ...

And there must be no track about partial commits made for development backup. So all internals of a GIT repository would look like there were only just Feature commits, no partial commits.

I know, that I can clone repositories to different folders, and copy-paste between these folders. However, GIT is designed for distributed development. So, I'm wondering whether there's some cleaner and more GIT-like way to solve this.

How to manage separate repositories with different histories?

The first commit on public repo can be completly squeezed, but since then I would like to have a nice commit history in public repo.

答:
This begs the question of why you want to do that, but that is your problem. Here are some possible approaches to do that:

Separate branches for features

Keep your master branch in sync with master of the public repository

develop each feature in your local / private repository, but do not sync these branches with the public repository

use git merge --squash to merge these branches as a single commit

Using different repositories

Use a repository for public and private development

develop in your private repository

after a feature is done, use git diff to create a .diff file

apply that diff using patch in the public repository and commit.


答:
I have seen both solutions, so it is definitely context dependent.

For readability, having multiple structs as you suggest is very effective.  However, in some environments, you want to do common manipulations to these structs, and you find yourself duplicating code, such as matrix*vector operations.  It can get frustrating when the particular operation isn't available in your flavor of vector because nobody ported it there.

The extreme solution (which we eventually gave into) is to have a CRTP templated base class with functions get<0>() get<1>() and get<2>() to get the elements in a generic manner.  Those functions are then defined in the Cartesian or Polar struct that derives from this base class.  It solves all of the problems, but comes at a rather silly price: having to learn template metaprogramming.  However, if template metaprogramming is already fair game for your project, it might be a good match.


答:
I think, if you care about native look-and-feel in Mac environment, you may go for mono with keeping the UI and the core loosely coupled. Because in mono you can achieve more native look-and-feel for different platforms using different mono based UI APIs like Cocoa#. But you have to spend more time.

May be Java also supports the APIs for different platforms. But the practice is not common I guess.

Another point is, if using C# makes you more productive, go for mono.

Title: Advantages and possible drawbacks of using Java for cross-platform development vs. .NET?

Body:
If I were to begin writing an application using Java with the intention of porting it to other platforms with little or no modification, would it be wise to consider using the .Net framework instead?

I have no specific targets in mind with respect to platform. At a minimum, Windows/Mac/Linux support would be nice. Also ease-of-use for the end-user is a consideration.


问:
Summing values from JSON end point based on category
I have a JSON end point for projects in a county. I am able to call a list of any of the object properties. What I want to do is to add together either all the values of budget property or the spent_encumbered by the value of category property.

For example, the total cost of all the projects that were for bridges, general county projects, school systems projects, etc.

Ideas I've had:

Return all the values of the category property

Push them all to an array

Do an if statement, if data[i].category === "school system projects" // or whatever array value?

For loop to add up all the returned budget values for the specific category.

Thoughts?

答:
What you are looking for is some sort of a filter/map/reduce.  Fortunately, JavaScript with modern browsers provides exactly that.

Using jQuery to get the data:

```<code>$.getJSON('https://opendata.howardcountymd.gov/resource/ghg6-4crr.json',
           function( data) { cityData = data });
</code>```

This returns a nice array with all the objects already parsed.  Once you've gotten the data, you can run this through a filter, for example:

```<code>var filteredArray = cityData.filter(
  function(value) {
      return value.fiscal_year='2015' && typeof value.spent_encumbered !== 'undefined'
  }
)
</code>```

This can then be reduced into a single number - for example:

```<code>var total_spent_encumbered =
  filteredArray.reduce(
    function(previousValue, currentValue, index, array) {
       return previousValue + Number(currentValue.spent_encumbered) }, 0
  );
</code>```

You can of course, combine all these functions and externalize the filter and reduce internal functions to allow you to mix and match both, giving you a lot of flexibility.

Link to JSFiddle

Body:
What you are looking for is some sort of a filter/map/reduce.  Fortunately, JavaScript with modern browsers provides exactly that.

Using jQuery to get the data:

$.getJSON('https://opendata.howardcountymd.gov/resource/ghg6-4crr.json',
           function( data) { cityData = data });

This returns a nice array with all the objects already parsed.  Once you've gotten the data, you can run this through a filter, for example:

var filteredArray = cityData.filter(
  function(value) {
      return value.fiscal_year='2015' && typeof value.spent_encumbered !== 'undefined'
  }
)

This can then be reduced into a single number - for example:

var total_spent_encumbered =
  filteredArray.reduce(
    function(previousValue, currentValue, index, array) {
       return previousValue + Number(currentValue.spent_encumbered) }, 0
  );

You can of course, combine all these functions and externalize the filter and reduce internal functions to allow you to mix and match both, giving you a lot of flexibility.

Link to JSFiddle


问:
How to optimize/parallelize the following clustering/joining algorithm:
I have relatively-small algorithm that takes up ~60% of the total run-time of my scientific code (57 lines of 3600), so I would like to find a way to optimize what I'm doing and make the code order-independent so that I can apply a cilk_for parallel strcture.

Here's what it does, verbally: I have an std::vector of pointers to custom objects called Segment (vector<Segment*> newSegment). Each Segment contains a std::vector of integers (mesh indices). In this function, I would like to find any Segment that overlaps with any another, with overlap being defined as the member indices overlapping on the number line. If they do overlap, I would like to join them together (insert the A.indices into B.indices) and delete one (delete A).

ex. 1:
A.indices={1,2,3} B.indices={4,5,6} do not overlap; do nothing

ex. 2:
 A.indices={1,2,4} B.indices={3,5,6} do overlap;  A= deleted B.indices={1,2,3,4,5,6}

The overlaps are sparse, but existent.

Here's the current code:

main algorithm:

```<code>//make sure segments don't overlap
for (unsigned i = 0; i < newSegment.size(); ++i) {
    if (newSegment[i]->size() == 0) continue;
    for (unsigned j = i + 1; j < newSegment.size(); ++j) {
        if (newSegment[i]->size() == 0) continue;
        if (newSegment[j]->size() == 0) continue;
        int i1 = newSegment[i]->begin();
        int i2 = static_cast<int>(newSegment[i]->end());
        int j1 = newSegment[j]->begin();
        int j2 = static_cast<int>(newSegment[j]->end());
        int L1 = abs(i1 - i2);
        int L2 = abs(j1 - j2);
        int dist = max(i1,i2,j1,j2) - min(i1,i2,j1,j2);

        //if overlap, fold segments together
        //copy indices from shorter segment to taller segment
        if (dist <= L1 + L2) {
            unsigned more, less;
            if (newSegment[i]->slope == newSegment[j]->slope) {
                if (value_max[i] > value_max[j]) {
                    more = i;
                    less = j;
                } else {
                    more = j;
                    less = i;
                }
            } else if (newSegment[i]->size() == 1) {
                more = j; less = i;
            } else if (newSegment[j]->size() == 1) {
                more = i; less = j;
            } else assert(1 == 0);
              while(!newSegment[less]->indices.empty()) {
                unsigned index = newSegment[less]->indices.back();
                newSegment[less]->indices.pop_back();
                newSegment[more]->indices.push_back(index);
            }
        }
    }

}//end overlap check

//delete empty segments
vector<unsigned> delList;
for (unsigned i = 0; i < newSegment.size(); ++i) {
    if (newSegment[i]->size() == 0) {                            //delete empty
        delList.push_back(i);
        continue;
    }
}
while (delList.size() > 0) {
    unsigned index = delList.back();
    delete newSegment.at(index);
    newSegment.erase(newSegment.begin() + index);
    delList.pop_back();
}
</code>```

Relevant Segment object class definition and member functions:

```<code>class Segment{

    public:
    Segment();
    ~Segment();

    unsigned size();
    int begin();
    unsigned end();
    std::vector<int> indices;
    double slope;
};

int Segment::begin() {
    if (!is_sorted(indices.begin(),indices.end()))      std::sort(indices.begin(),indices.end());
    if (indices.size() == 0) return -1;
    return indices[0];
}

unsigned Segment::end() {
    if (!is_sorted(indices.begin(),indices.end()))    std::sort(indices.begin(),indices.end());
    return indices.back();
}

unsigned Segment::size() {
    unsigned indSize = indices.size();
    if (indSize == 1) {
        if (indices[0] == -1) return 0;
    }
    return indSize;
}
</code>```

Ideas:

Since I don't care about the order of the Segment objects, they could be in an orderless container?

In my algorithm, I find overlap by looking at the first and last indices of each segment. I do an std::is_sorted (and then maybe a std::sort) when I fetch the indices because the list can change when more indices are inserted. Maybe I could put the indices in a std::set rather than std::vector to save the explicit sort-checking/sorting?

I'm pretty sure that by editing the indices as I go, this makes it order-dependent. Perhaps, I could break the code into the following organization using the concept of an undirected graph to make it order-independent:

edge discovery (without modifying indices)

join clusters of connected nodes (Segment objects that overlap) using a graph traversal

delete empty Segment objects

Questions

Are either of the ideas above worthwhile or negligible to performance?

How else can I optimize it?

How (if not the above) can I make the algorithm order-independent?

答:
I came to identical algorithm than @BartVanIngenSchenau in this comment
Basically sort the set of segments based on the min element of each segment. Then two adjacent element overlap if and only if Segment[i].max >= Segment[i+1].min

But I would like to add that sorting looks unnecessary at all and only keeping the max and the min element. Just update them when merging segments.
(segment1+segment2).min = min(segment1.min,segment2.min) and (segment1+segment2).max = max(segment1.max,segment2.max) Moreover if the segment are sorted by min element you have (Segment[i]+Segment[i+1]).min = segment[i].min (but this last thing could be premature optimization.) I noted + the merge of two segments.

For cache locality, the best for merging might be to have a layout simimar to the following layout

```<code>ptr_to_2nd_segment
n_elt_of_1st_segment,
min_elt_of_1st_segment,
[
[other_elts_of_1st_segment,]
max_elt_of_1st_segment,]

ptr_to_3rd_segment
n_elt_of_2nd_segment,
min_elt_of_2nd_segment,
[
[other_elts_of_2nd_segment,]
max_elt_of_2nd_segment,]

...
</code>```

merging two elements in this configuration would be quite simple, it would be
just a matter of updating ptr to next element, adding the number of elements,shifting the second segment elements and swapping the max elements if necessary. That would let some junk after each merge (8 bytes on 32 bits architecture and 16 bytes on 64 bits architecture). Knowing if you can support such junk is application dependent (moreover, you could doing a kind of garbage collection between two iteration of the algorithm.)

For parallelizing, once the set of segments are sorted by min element, you can divide in n part the set of segments and doing the merge independently. Then only merge at the border of each parts. But as @MikeNakis says in this comment as merging is quite memory bound, they might not be well parallelize

Body:
I came to identical algorithm than @BartVanIngenSchenau in this comment
Basically sort the set of segments based on the min element of each segment. Then two adjacent element overlap if and only if Segment[i].max >= Segment[i+1].min

But I would like to add that sorting looks unnecessary at all and only keeping the max and the min element. Just update them when merging segments.
(segment1+segment2).min = min(segment1.min,segment2.min) and (segment1+segment2).max = max(segment1.max,segment2.max) Moreover if the segment are sorted by min element you have (Segment[i]+Segment[i+1]).min = segment[i].min (but this last thing could be premature optimization.) I noted + the merge of two segments.

For cache locality, the best for merging might be to have a layout simimar to the following layout

ptr_to_2nd_segment
n_elt_of_1st_segment,
min_elt_of_1st_segment,
[
[other_elts_of_1st_segment,]
max_elt_of_1st_segment,]

ptr_to_3rd_segment
n_elt_of_2nd_segment,
min_elt_of_2nd_segment,
[
[other_elts_of_2nd_segment,]
max_elt_of_2nd_segment,]

...

merging two elements in this configuration would be quite simple, it would be
just a matter of updating ptr to next element, adding the number of elements,shifting the second segment elements and swapping the max elements if necessary. That would let some junk after each merge (8 bytes on 32 bits architecture and 16 bytes on 64 bits architecture). Knowing if you can support such junk is application dependent (moreover, you could doing a kind of garbage collection between two iteration of the algorithm.)

For parallelizing, once the set of segments are sorted by min element, you can divide in n part the set of segments and doing the merge independently. Then only merge at the border of each parts. But as @MikeNakis says in this comment as merging is quite memory bound, they might not be well parallelize


问:
A better way than O(n^2) for traversing a dictionary of dictionaries.
I have a Dictionary of Dictionaries that I need to traverse to find two records with various matching parameters. I have two foreach loops to do this which is O(n^2). I am looking for inspiration to find a better way of doing this by using the keys to improve lookup.

Simple example below.

edit: Each record contains many values that I would want to try and match. Below I'm looking for a BUY and a SELL transaction in the records. I would also want to maybe match for the same customer and same location, which are keys in the record dictionary. It is possible that the Dictionary only has "BUY" Transaction values. The record dictionary also contains different value types, like double and int.

<"uniqueRecordIdABC", <"Transaction", "BUY">, <"Location", "Store1">,
<"Client", "Bob">>

<"uniqueRecordIdDEF", <"Transaction", "SELL">, <"Location", "Store2">, <"Client", "Bob">>

What I've thought about doing is making the uniqueRecordKey something that I could parse, improving the lookup. IE: 1:BUY:Store1:Bob, 2:SELL:Store2:Bob, but I'm not sure if there is any real benefit to that either.

Example:

```<code>Dictionary<string, Dictionary<string, object>> records

foreach (var item in records)
{
    Dictionary<string, object> record = item.Value;
    string transaction1 = Convert.ToString(record["Transaction"]);
    string name1 = Convert.ToString(record["Client"]);
    string location1 = Convert.ToString(record["Location"]);

    foreach (var item2 in records)
    {
        Dictionary<string, object> record2 = item2.Value;
        string transaction2 = Convert.ToString(record["Transaction"]);
        string name2 = Convert.ToString(record["Client"]);
        string location2 = Convert.ToString(record["Location"]);

        if ((transaction1 == "BUY" && transaction2 == "SELL" || transaction1 == "SELL" && transaction2 == "BUY") &&  name1 == name2 && location1 == location2)
        {
        }
    }
}
</code>```

答:
```<code>{"id1": {"Transaction": "BUY",  "Location": "Store1", "Client": "Bob"}}
{"id2", {"Transaction": "SELL", "Location": "Store2", "Client": "Bob"}}
</code>```

I would also want to maybe match for the same customer and same location, which are keys in the record dictionary.

With this data structure, you will indeed have to iterate over all of it to be able to find the corresponding items. You might be able to improve it somewhat by building a second structure as you iterate over it first so that instead of O(n2) you get something more like O(n log n). But that's going to be about as good as you'll get with this structure.

What you need to do is to effectively index it on other portions of data and work off of those.

```<code>{"Client": "Bob", "Buys": [ "id1" ], "Sells": [ "id2" ] }
</code>```

And, now you can look that up in a hash table or dictionary (whatever your language calls them) in O(1) by pulling up just Bob.  Then you can do whatever you want with the Buys and Sells lists.

Similarly, you would do similar things with the Stores. But you need to build the corresponding data structure that matches the queries you want to do against it.

You may wish to consider that if you are getting to the point of wanting to be able to run these queries against the data, you might need to move to the "next level" of storing the data and put it in a relational database.  This gives you code that is designed to run these queries really fast and frees you up from worrying about "oh, now I need to build this other structure to be able to do the query for "who are all the customers at some store?" in a reasonable time".

Body:
{"id1": {"Transaction": "BUY",  "Location": "Store1", "Client": "Bob"}}
{"id2", {"Transaction": "SELL", "Location": "Store2", "Client": "Bob"}}

I would also want to maybe match for the same customer and same location, which are keys in the record dictionary.

With this data structure, you will indeed have to iterate over all of it to be able to find the corresponding items. You might be able to improve it somewhat by building a second structure as you iterate over it first so that instead of O(n2) you get something more like O(n log n). But that's going to be about as good as you'll get with this structure.

What you need to do is to effectively index it on other portions of data and work off of those.

{"Client": "Bob", "Buys": [ "id1" ], "Sells": [ "id2" ] }

And, now you can look that up in a hash table or dictionary (whatever your language calls them) in O(1) by pulling up just Bob.  Then you can do whatever you want with the Buys and Sells lists.

Similarly, you would do similar things with the Stores. But you need to build the corresponding data structure that matches the queries you want to do against it.

You may wish to consider that if you are getting to the point of wanting to be able to run these queries against the data, you might need to move to the "next level" of storing the data and put it in a relational database.  This gives you code that is designed to run these queries really fast and frees you up from worrying about "oh, now I need to build this other structure to be able to do the query for "who are all the customers at some store?" in a reasonable time".


答:
One way is to split them into two separate lists (one for buys and one for sells), sort them by name and location, and then do a simple merge.

For example:

```<code>var buyList = records.Where(Convert.ToString(records["Transaction"]) == "BUY")
    .OrderBy(Convert.ToString(records["Client"]))
    .ThenBy(Convert.ToString(records["Location"]));
var sellList = records.Where(Convert.ToString(records["Transaction"]) == "SELL")
    .OrderBy(Convert.ToString(records["Client"]))
    .ThenBy(Convert.ToString(records["Location"]));
</code>```

Now you can do a standard merge algorithm, stepping through the two lists in tandem. See my article Merging sorted sequences for the basic idea.

That turns your O(N^2) into something like m log m + n log n + 3N, where m and n are the number of buys and sells, respectively, and N is the total number of transactions. It does, however, require O(N) extra space for the temporary lists.

Title: A better way than O(n^2) for traversing a dictionary of dictionaries.

Body:
I have a Dictionary of Dictionaries that I need to traverse to find two records with various matching parameters. I have two foreach loops to do this which is O(n^2). I am looking for inspiration to find a better way of doing this by using the keys to improve lookup.

Simple example below.

edit: Each record contains many values that I would want to try and match. Below I'm looking for a BUY and a SELL transaction in the records. I would also want to maybe match for the same customer and same location, which are keys in the record dictionary. It is possible that the Dictionary only has "BUY" Transaction values. The record dictionary also contains different value types, like double and int.

<"uniqueRecordIdABC", <"Transaction", "BUY">, <"Location", "Store1">,
<"Client", "Bob">>

<"uniqueRecordIdDEF", <"Transaction", "SELL">, <"Location", "Store2">, <"Client", "Bob">>

What I've thought about doing is making the uniqueRecordKey something that I could parse, improving the lookup. IE: 1:BUY:Store1:Bob, 2:SELL:Store2:Bob, but I'm not sure if there is any real benefit to that either.

Example:

```<code>Dictionary<string, Dictionary<string, object>> records

foreach (var item in records)
{
    Dictionary<string, object> record = item.Value;
    string transaction1 = Convert.ToString(record["Transaction"]);
    string name1 = Convert.ToString(record["Client"]);
    string location1 = Convert.ToString(record["Location"]);

    foreach (var item2 in records)
    {
        Dictionary<string, object> record2 = item2.Value;
        string transaction2 = Convert.ToString(record["Transaction"]);
        string name2 = Convert.ToString(record["Client"]);
        string location2 = Convert.ToString(record["Location"]);

        if ((transaction1 == "BUY" && transaction2 == "SELL" || transaction1 == "SELL" && transaction2 == "BUY") &&  name1 == name2 && location1 == location2)
        {
        }
    }
}
</code>```

Body:
One way is to split them into two separate lists (one for buys and one for sells), sort them by name and location, and then do a simple merge.

For example:

var buyList = records.Where(Convert.ToString(records["Transaction"]) == "BUY")
    .OrderBy(Convert.ToString(records["Client"]))
    .ThenBy(Convert.ToString(records["Location"]));
var sellList = records.Where(Convert.ToString(records["Transaction"]) == "SELL")
    .OrderBy(Convert.ToString(records["Client"]))
    .ThenBy(Convert.ToString(records["Location"]));

Now you can do a standard merge algorithm, stepping through the two lists in tandem. See my article Merging sorted sequences for the basic idea.

That turns your O(N^2) into something like m log m + n log n + 3N, where m and n are the number of buys and sells, respectively, and N is the total number of transactions. It does, however, require O(N) extra space for the temporary lists.