问:
How to correctly draw a UML class diagram with fully qualified association?
Given the following code I have to draw the corresponding class diagram:

```<code>public class Shop
{
    List<Client> clients;
    Storage store;
    User chief;
    Set<Invoice> invoices;
}

public class Invoice
{
    Map<Product, Row> rows;
    Client client;
}

public class Client{}
public class Product{}

public class Storage
{
    Map<Integer, Product> products;
}

public class Row
{
    Product p;
    double qty;
}
</code>```

On draw.io I produced the following design:

Focus of my question is on
- Relation between Invoice and row:
Is it correct to draw the qualified association like so? On draw.io I found no option to depict this particular case. I built it by dragging Product class to be adjacent to Invoice.

Relation between Storage and Product.
Is it correct? Or should I represent it also like a qualified association using class Integer as qualifier?

Do you see any error on relation arrows or cardinality?

答:
I think you need to model Product as a distinct class to make it clear that a Storage may have Products that are not yet included in any Invoice.

You could model Row as an association class for the Invoice-Product association:

Otherwise your diagram seems ok. The structure of Storage seems a bit funny though. If it should keep record of the amount of items, then it probably should have a Map<Product, Integer> instead of Map<Integer, Product>.


问:
Is the use of NoSQL Databases impractical for large datasets where you need to search by content?
I've been learning about NoSQL Databases for a week now.

I really understand the advantages of NoSQL Databases and the many use cases they are great for.

But often people write their articles as if NoSQL could replace Relational Databases. And there is the point I can't get my head around:

NoSQL Databases are (often) key-value stores.

Of course it is possible to store everything into a key-value store (by encoding the data in JSON, XML, whatever), but the problem I see is that you need to get some amount of data that matches a specific criterion, in many use cases. In a NoSQL database you have only one criterion you can search for effectively - the key. Relational Databases are optimized to search for any value in the data row effectively.

So NoSQL Databases are not really a choice for persisting data that need to be searched by their content. Or have I misunderstood something?

An example:

You need to store user data for a webshop.

In a relational database you store every user as an row in the users table, with an ID, the name, his country, etc.

In a NoSQL Database you would store each user with his ID as key and all his data (encoded in JSON, etc.) as value.

So if you need to get all users from a specific country (for some reason the marketing guys need to know something about them), it's easy to do so in the Relational Database, but not very effective in the NoSQL Database, because you have to get every user, parse all the data and filter.

I don't say it's impossible, but it gets a lot more tricky and I guess not that effective if you want to search in the data of NoSQL entries.

You could create a key for each country that stores the keys of every user who lives in this country, and get the users of a specific country by getting all the keys which are deposited in the key for this country. But I think this techique makes a complex dataset even more complex - it's harder to implement and not as effective as querying an SQL Database. So I think it's not a way you would use in production. Or is it?

I'm not really sure if I misunderstood something or overlooked some concepts or best practices to handle such use cases. Maybe you could correct my statements and answer my questions.

答:
NoSQL databases have very little to do with “No SQL”.

They are about admitting that you can’t have a database at scale that is always consistent and supports complex transactions and has durability.

In a normal relational database all indexes are automatically kept updated within the scope of a transaction, so can be used for any query.

In a NoSQL database the programmer is responsible for maintaining a lot of the indexes and it is assumed that indexes will always be out of date.

For example:

An index of people by tax number may contain some people that never complete the process of registration for tax.

Therefore code that uses the index has to be able to cope with incomplete registration for tax

Another option is to have times when a person that is registered for tax is not in the index.  (So your design has to cope with not having consistent data and decide how the data will not be consistent.)

As a real would example, Amazon would rather show me the out of date description of a book than delay the display of the web page by waiting for 106 computers to confirm that the correct lock has been taken out.

Therefore.....

If a single normal relational database can hold all your data and process each transaction quickly enough that locking does not stop your system from doing useful work, a relational database is the best option.

But as soon as you have to start thinking about using more than one relational database, or splitting up transactions to avoid locking errors, you are going down the road of having to cope with the sort of issues you get when using “NoSQL” databases.

As “NoSQL” databases do not hide these issues, they may become the best option when you scale up a system.   But remember that Stackoverflow  still uses an relational database for storing all its data, with limited use of NoSQL in the caching layer – so you have to be VERY big before you are forced to use NoSQL to store your data.

ContentLicense: CC BY-SA 3.0


问:
Alternative to Anemic domain objects (Simple example provided)
I want to model (TV)Events and Reminders and I’m wondering what’s ‘the best’ way to model this.

The requirements are roughly

When an Event has no Reminder, a Reminder can be created

When an Event has a Reminder

the Reminder can be deleted

an icon is shown on the Event

A separate Screen exists presenting all Reminders

Reminders are stored in the backend and have multiple properties

Obviously, our real domain is larger and also contains Channels, Recordings, ...

Basically, we need functions to

create a Reminder

delete a Reminder

get the list of all Reminders

check if an Event has a Reminder

This seems a relatively simple problem but I'm struggling with it. Below, I’ve collected a number of possible options and I would greatly appreciate your feedback.

Option 1

Event creates Reminders

Event API

```<code>Reminder createReminder() //adds the Reminder to the backend
boolean  hasReminder()
</code>```

Reminder API

```<code>void deleteReminder() //removes the Reminder from the backend
static List<Reminder> getAllReminders()
</code>```

But

deleting and creating a Reminder are symmetric functions and hence I would expect them on a single API (now both Event and Reminder have an interface to the backend)

I'm not a big fan of the static function on Reminder. It seems to indicate that a higher-order object should exist

Option 2

Reminder API

```<code>Reminder createReminder(Event event) //adds the Reminder to the backend
void deleteReminder() //removes the Reminder from the backend
boolean hasReminder(Event event)
static List<Reminder> getAllReminders()
</code>```

Advantage is that the Event API doesn't change when adding Reminder functionality (=> good wrt extendibility I guess).
But

creating a Reminder for a Event (and checking whether an event has a reminder) seems to be more a function on Event so I would expect them on the Event API

Option 3

Event API

```<code>Reminder createReminder() //adds the Reminder to the backend
void deleteReminder() //removes the Reminder from the backend
boolean hasReminder()
static List<Reminder> getAllReminders()
</code>```

But

the getAllReminders() seems more a function on Reminder

Option 4

Create a ReminderManager/ReminderService (singleton) with the following API

```<code>Reminder createReminder(Event) //adds the Reminder to the backend
void deleteReminder(Reminder) //removes the Reminder from the backend
boolean hasReminder(Event event)
List<Reminder> getAllReminders()
</code>```

This is my preferred option but

This results in anemic Event/Reminder objects (just getters and setters but no logic). There seems to be discussion whether this is an anti-pattern or not

答:
Basically if you look at your requirements posted above:

create a Reminder

delete a Reminder

get the list of all Reminders

check if an Event has a Reminder

These are classic plain CRUD. Even the keywords match almost exactly Create, Read (/find/get/check), Update, Delete.

As such, you have no complicated domain or business logic where a rich domain model would be an advantage. That's why you are struggling to find the correct places for your API methods.

See here for similar opinions:

https://stackoverflow.com/questions/23314330/rich-vs-anemic-domain-model

http://codebetter.com/davelaribee/2007/09/24/domain-model-overuse/

Anemic vs rich domain model

I'm all for rich domain models, but only where they make sense. They start making sense when you have to implement many or complicated business rules that operate on your domain, and you find yourself duplicating and scattering business logic all over your services. When a new requirement needs changes in 3 services, and maybe you forgot a change in the fourth, then it's time to start thinking about using a rich domain model and consolidating all the business logic in the domain model objects.

See here a nice talk about how to refactor an anemic domain model app to a rich domain model one. Jimmy Bogart even starts the talk by mentioning that it is often difficult to know from the beginning when a rich domain model would be appropriate (since most applications start out being rather simple). So it makes sense to only start refactoring towards a rich domain model once the complexity becomes apparent.

My recommendation

Just use an EventService, ReminderService and so on for most of the methods, and only put those on the domain objects which clearly belong to one of them. I'll try to give concrete examples below.

It is not fully clear whether you want to model your domain on the front end or back end, but from your text I assume it's front end (correct me if I'm wrong and I'll adapt the answer). In that case you should be separating your concerns cleanly, e.g. via a MVP (or MVC, MVVM, ...) architecture.

Assuming you have that, here is how all the parts would fit together:

View

Has obviously no domain or service logic in it. It handles purely presentational concerns (e.g. which icon to show depending on the state of the model).

Presenter / Controller

Handles communication between View and Model, and the "glue" code to get it all working. Here the controller could call ReminderService.getAllReminders() and then populate the ViewModel with the list.

Similarly you have EventService.getAllEvents().

Note the ViewModel and domain model are usually separated, but in simple cases they could be the same thing, especially if it is a CRUD application where every property of the domain model is directly represented in the View; then it would make sense to just pass the domain model through to the View as its ViewModel.

Model

Once you have your ViewModels (which could delegate to the domain model or be the same thing), you can call the other methods directly on the model objects:

```<code>class Event
    Reminder createReminder()
    void deleteReminder()
    boolean hasReminder()
</code>```

Backend

As long as your business logic remains this simple and CRUD-like, you can just use Services that delegate to the persistence layer.

Summary

So basically my suggestion is like your Option 3, but don't be scared to have Service objects if you really have methods that don't fit into a model object. That does not make your domain model automatically into an anemic one. And even if you at the moment have almost no logic in your domain model, that might be ok if you really just have no complex business logic to take care of.

Body:
Basically if you look at your requirements posted above:

create a Reminder

delete a Reminder

get the list of all Reminders

check if an Event has a Reminder

These are classic plain CRUD. Even the keywords match almost exactly Create, Read (/find/get/check), Update, Delete.

As such, you have no complicated domain or business logic where a rich domain model would be an advantage. That's why you are struggling to find the correct places for your API methods.

See here for similar opinions:

https://stackoverflow.com/questions/23314330/rich-vs-anemic-domain-model

http://codebetter.com/davelaribee/2007/09/24/domain-model-overuse/

Anemic vs rich domain model

I'm all for rich domain models, but only where they make sense. They start making sense when you have to implement many or complicated business rules that operate on your domain, and you find yourself duplicating and scattering business logic all over your services. When a new requirement needs changes in 3 services, and maybe you forgot a change in the fourth, then it's time to start thinking about using a rich domain model and consolidating all the business logic in the domain model objects.

See here a nice talk about how to refactor an anemic domain model app to a rich domain model one. Jimmy Bogart even starts the talk by mentioning that it is often difficult to know from the beginning when a rich domain model would be appropriate (since most applications start out being rather simple). So it makes sense to only start refactoring towards a rich domain model once the complexity becomes apparent.

My recommendation

Just use an EventService, ReminderService and so on for most of the methods, and only put those on the domain objects which clearly belong to one of them. I'll try to give concrete examples below.

It is not fully clear whether you want to model your domain on the front end or back end, but from your text I assume it's front end (correct me if I'm wrong and I'll adapt the answer). In that case you should be separating your concerns cleanly, e.g. via a MVP (or MVC, MVVM, ...) architecture.

Assuming you have that, here is how all the parts would fit together:

View

Has obviously no domain or service logic in it. It handles purely presentational concerns (e.g. which icon to show depending on the state of the model).

Presenter / Controller

Handles communication between View and Model, and the "glue" code to get it all working. Here the controller could call ReminderService.getAllReminders() and then populate the ViewModel with the list.

Similarly you have EventService.getAllEvents().

Note the ViewModel and domain model are usually separated, but in simple cases they could be the same thing, especially if it is a CRUD application where every property of the domain model is directly represented in the View; then it would make sense to just pass the domain model through to the View as its ViewModel.

Model

Once you have your ViewModels (which could delegate to the domain model or be the same thing), you can call the other methods directly on the model objects:

class Event
    Reminder createReminder()
    void deleteReminder()
    boolean hasReminder()

Backend

As long as your business logic remains this simple and CRUD-like, you can just use Services that delegate to the persistence layer.

Summary

So basically my suggestion is like your Option 3, but don't be scared to have Service objects if you really have methods that don't fit into a model object. That does not make your domain model automatically into an anemic one. And even if you at the moment have almost no logic in your domain model, that might be ok if you really just have no complex business logic to take care of.


问:
Git branching strategy for long-running unreleased code
At our team, in addition to individual units of work (Stories), we have longer-running themes of work (Epics). Multiple stories make an epic.

Traditionally we've had feature branches for each Story, and merged those straight to master when they pass QA. However, we'd like to start holding back on release of completed stories in an Epic until the Epic is deemed "feature complete". We'd only release these features to production when the entire Epic is closed. Furthermore, we have a nightly build server - we'd like all closed Stories (including those that are part of incomplete Epics) to be deployed to this nightly server automatically.

Are there any suggestions on how to manage our repo to achieve this? I've considered introducing "epic branches", where we'd merging closed stories to the related epic branch instead of direct to master, but my concerns are:

I worry about the merge conflicts that may arise if epic branches are kept open for long

Nightly builds would require merging all epic branches into a "nightly build" branch. Again, merge conflicts could arise, and this is to be done automatically

答:
Simple suggestion: don't do that.

git branches are not for long-running forks of the code, as discussed here and here. Branches are best treated as transient things used to organize commits by an individual developer on a day-to-day level. So if they have a name that corresponds to something a project manager (let alone end user) might care about you are doing something wrong.

Recommended practice is to use continuous integration with feature toggles or branch-by-abstraction to ensure that:

all code is integrated at all times (at least every day, preferably more often)

what gets deployed is under explicit control.

ContentLicense: CC BY-SA 4.0


答:
It seems to me you are missing a User object. Obviously there will be millions of reminders, but you're only going to be interested in the ones for a particular User.

Hence

```<code>User.AddReminder(Reminder reminder)
User.DeleteReminder(string reminderId)
User.Reminders
</code>```

Also, as you point out the reminder will want to be able to provide the user with a link to the event

```<code>Reminder.Event
</code>```

or possibly :

```<code>Reminder.EventId
</code>```

depending on whether you have a list of events loaded elsewhere

Title: Alternative to Anemic domain objects (Simple example provided)

Body:
I want to model (TV)Events and Reminders and I’m wondering what’s ‘the best’ way to model this.

The requirements are roughly

When an Event has no Reminder, a Reminder can be created

When an Event has a Reminder

the Reminder can be deleted

an icon is shown on the Event

A separate Screen exists presenting all Reminders

Reminders are stored in the backend and have multiple properties

Obviously, our real domain is larger and also contains Channels, Recordings, ...

Basically, we need functions to

create a Reminder

delete a Reminder

get the list of all Reminders

check if an Event has a Reminder

This seems a relatively simple problem but I'm struggling with it. Below, I’ve collected a number of possible options and I would greatly appreciate your feedback.

Option 1

Event creates Reminders

Event API

```<code>Reminder createReminder() //adds the Reminder to the backend
boolean  hasReminder()
</code>```

Reminder API

```<code>void deleteReminder() //removes the Reminder from the backend
static List<Reminder> getAllReminders()
</code>```

But

deleting and creating a Reminder are symmetric functions and hence I would expect them on a single API (now both Event and Reminder have an interface to the backend)

I'm not a big fan of the static function on Reminder. It seems to indicate that a higher-order object should exist

Option 2

Reminder API

```<code>Reminder createReminder(Event event) //adds the Reminder to the backend
void deleteReminder() //removes the Reminder from the backend
boolean hasReminder(Event event)
static List<Reminder> getAllReminders()
</code>```

Advantage is that the Event API doesn't change when adding Reminder functionality (=> good wrt extendibility I guess).
But

creating a Reminder for a Event (and checking whether an event has a reminder) seems to be more a function on Event so I would expect them on the Event API

Option 3

Event API

```<code>Reminder createReminder() //adds the Reminder to the backend
void deleteReminder() //removes the Reminder from the backend
boolean hasReminder()
static List<Reminder> getAllReminders()
</code>```

But

the getAllReminders() seems more a function on Reminder

Option 4

Create a ReminderManager/ReminderService (singleton) with the following API

```<code>Reminder createReminder(Event) //adds the Reminder to the backend
void deleteReminder(Reminder) //removes the Reminder from the backend
boolean hasReminder(Event event)
List<Reminder> getAllReminders()
</code>```

This is my preferred option but

This results in anemic Event/Reminder objects (just getters and setters but no logic). There seems to be discussion whether this is an anti-pattern or not

Body:
It seems to me you are missing a User object. Obviously there will be millions of reminders, but you're only going to be interested in the ones for a particular User.

Hence

User.AddReminder(Reminder reminder)
User.DeleteReminder(string reminderId)
User.Reminders

Also, as you point out the reminder will want to be able to provide the user with a link to the event

Reminder.Event

or possibly :

Reminder.EventId

depending on whether you have a list of events loaded elsewhere


问:
When to use "is a" or "has a"?
In my node.js application, I have a queue class which has push and pop methods and a data property. I have an Event class which handles an event and pushes it on to the queue.

If I think object oriented, is the relationship between queue and event better modeled as "is a" (inheritance) or "has a" (composition)?

First approach:

```<code>var util = require('util'),
    array = [];

function Q(source){
    this.data = source;
}

Q.prototype.push = function(x){
    this.data.push(x);
};

Q.prototype.show = function(){
    console.log(this.data);
};

function Event(y){
    Q.call(this, y);
}

util.inherits(Event,Q);

Event.prototype.trigger = function(bb){
 //some logic
 this.push(bb);
};

var x = new Event(array);
x.trigger('hi');
x.show();
</code>```

Second approach :

```<code>var array = [];
function Q(source){
    this.data = source;
}

Q.prototype.push = function(x){
    this.data.push(x);
};

Q.prototype.show = function(){
    console.log(this.data);
};

function Event(y){
    this.arr = new Q(y);
}

Event.prototype.trigger = function(bb){
    //some logic
    this.arr.push(bb);
};

var x = new Event(array);
x.trigger('hi');
x.show();
</code>```

答:
Conceptually, inheritance (is-a) is a specialization of composition (has-a). (from Reg Braithwaite) Both accomplish the same thing (which is why you can ask a question like this), but inheritance lacks the flexibility of composition. Inheritance makes your code rigid.

From a practical view, this doesn't matter as much in JavaScript since JavaScript isn't limited to single inheritance. What we're calling inheritance is actually some prototype patching and function delegation. There's nothing stopping us from creating a mixin from several "types". This has more in common with Go's type composition than Java or C#'s inheritance model. It doesn't make your code as rigid.

Still, it does seem strange to say an Event is-a Queue. Is it really? It seems more likely that an Event is a model of some action in your app and it uses (has-a) a Queue to manage its workflow. If an Event is truly a Queue, I should be able to use it anywhere I use a Queue without a second thought:

```<code>var q = new Event();
q.push("hi");
q.pop();
</code>```

This doesn't seem right to me. It's a stretch. This is a perfect place to avoid inheritance in favor of composition.

See also: Liskov substitution principle

Title: When to use "is a" or "has a"?

Body:
Conceptually, inheritance (is-a) is a specialization of composition (has-a). (from Reg Braithwaite) Both accomplish the same thing (which is why you can ask a question like this), but inheritance lacks the flexibility of composition. Inheritance makes your code rigid.

From a practical view, this doesn't matter as much in JavaScript since JavaScript isn't limited to single inheritance. What we're calling inheritance is actually some prototype patching and function delegation. There's nothing stopping us from creating a mixin from several "types". This has more in common with Go's type composition than Java or C#'s inheritance model. It doesn't make your code as rigid.

Still, it does seem strange to say an Event is-a Queue. Is it really? It seems more likely that an Event is a model of some action in your app and it uses (has-a) a Queue to manage its workflow. If an Event is truly a Queue, I should be able to use it anywhere I use a Queue without a second thought:

var q = new Event();
q.push("hi");
q.pop();

This doesn't seem right to me. It's a stretch. This is a perfect place to avoid inheritance in favor of composition.

See also: Liskov substitution principle


答:
I think this is a pretty common problem and boils down to choosing which features to include in a release after the features have been coded rather than before.

eg.

I have features A, B and C for v2 of my product. B and C are related, I don't want to release B unless C is also finished.

I have three devs all working at the same time on the features.

I Have a set in stone release date D

B is finished and merged in, A is finished and merged in. C is delayed... what do I do?!

I do not believe there is a technical solution to this problem. You want to release an untested version of the product with only feature A included. Unless you merge and test all possible combinations of features this is always going to be a possibility.

The solution is a more human one. You have missed your release date and must push it back.

Title: Git branching strategy for long-running unreleased code

Body:
At our team, in addition to individual units of work (Stories), we have longer-running themes of work (Epics). Multiple stories make an epic.

Traditionally we've had feature branches for each Story, and merged those straight to master when they pass QA. However, we'd like to start holding back on release of completed stories in an Epic until the Epic is deemed "feature complete". We'd only release these features to production when the entire Epic is closed. Furthermore, we have a nightly build server - we'd like all closed Stories (including those that are part of incomplete Epics) to be deployed to this nightly server automatically.

Are there any suggestions on how to manage our repo to achieve this? I've considered introducing "epic branches", where we'd merging closed stories to the related epic branch instead of direct to master, but my concerns are:

I worry about the merge conflicts that may arise if epic branches are kept open for long

Nightly builds would require merging all epic branches into a "nightly build" branch. Again, merge conflicts could arise, and this is to be done automatically


问:
Was .NET's IObserver<T> intended for subscribing to multiple IObservables?
There are IObservable and IObserver interfaces in .NET (also here and here).  Interestingly, the concrete implementation of the IObserver does not hold a direct reference to the IObservable.  It doesn't know who it's subscribed to.  It can only invoke the unsubscriber.  "Please pull the pin to unsubscribe."

edit: The unsubscriber implements the IDisposable. I think, this scheme was employed to prevent the lapsed listener problem.

Two things are not entirely clear to me, though.

Does the inner Unsubscriber class provide the subscribe-and-forget behavior?  Who (and when exactly) calls IDisposable.Dispose() on the Unsubscriber?  Garbage collector (GC) is not deterministic.

[Disclaimer:  overall, I've spent more time with C and C++ than with C# .]

What should happen if I want to subscribe an observer K to an observable L1 and the observer is already subscribed to some other observable L2?

```<code>K.Subscribe(L1);
K.Subscribe(L2);
K.Unsubscribe();
L1.PublishObservation(1003);
L2.PublishObservation(1004);
</code>```

When I ran this test code against MSDN's example, the observer remained subscribed to L1.  This would be peculiar in real development.  Potentially, there are 3 avenues to improve this:

If the observer already has an unsubscriber instance (i.e. it’s already subscribed), then it quietly unsubscribes from the original provider before subscribing to a new one.  This approach hides the fact that it’s no longer subscribed to the original provider, which may become a surprise later.

If the observer already has an unsubscriber instance, then is throws an exception.  A well-behaved calling code has to unsubscribe the observer explicitly.

Observer subscribes to multiple providers.  This is the most intriguing option, but can this be implemented with IObservable and IObserver?  Let’s see.  It is possible for the observer to keep a list of unsubscriber objects: one for each source.  Unfortunately, IObserver.OnComplete() does not provide a reference back to the provider who have sent it.  So, the IObserver implementation with multiple providers would not be able to determine which one to unsubscribe from.

Was .NET's IObserver intended for subscribing to multiple IObservables?

Does the textbook definition of the observer pattern require that one observer has to be able to subscribe to multiple providers? Or is it optional and implementation-dependent?

答:
I know this is way late to the party, but...

The interfaces IObservable<T> and IObserver<T> are not part of Rx...they're core types...but Rx makes extensive use of them.

You are free to have as many (or as few) observers as you like. If you anticipate multiple observers, it's the observable's responsibility to route OnNext() calls to the appropriate observers for each observed event. The observable might need a list or a dictionary as you suggest.

There are good cases for allowing only one - and good cases for allowing many. For example, in an CQRS/ES implementation, you might enforce a single command handler per command type on a command bus, while you might notify several read-side transforms for a given event type in the event store.

As stated in other answers, there's no Unsubscribe. Disposing of the thing you're given when you Subscribe generally does the dirty work. The observer, or an agent thereof, is responsible for holding onto the token until it no longer wants to receive further notifications. (qestion 1)

So, in your example:

```<code>K.Subscribe(L1);
K.Subscribe(L2);
K.Unsubscribe();
L1.PublishObservation(1003);
L2.PublishObservation(1004);
</code>```

...it would be more like:

```<code>using ( var l1Token = K.Subscribe( L1 ) )
{
  using ( var l2Token = K.Subscribe( L2 );
  {
    L1.PublishObservation( 1003 );
    L2.PublishObservation( 1004 );
  } //--> effectively unsubscribing to L2 here

  L2.PublishObservation( 1005 );
}
</code>```

...where K would hear 1003 and 1004 but not 1005.

To me, this still looks funny because nominally, subscriptions are long-lived things...often for the duration of the program. They're not dissimilar in this respect to normal .Net events.

In a lot of examples I've seen, the Dispose of the token does work to remove the observer from the observable's list of observers. I prefer that the token not carry so much knowledge around...and so I have generalized my subscription tokens to just call a passed-in lambda (with identifying information captured at subscribe-time:

```<code>public class SubscriptionToken<T>: IDisposable
{
  private readonly Action unsubscribe;

  private SubscriptionToken( ) { }
  public SubscriptionToken( Action unsubscribe )
  {
    this.unsubscribe = unsubscribe;
  }

  public void Dispose( )
  {
    unsubscribe( );
  }
}
</code>```

...and the the observable can install the unsubscribe behavior during subscription:

```<code>IDisposable Subscribe<T>( IObserver<T> observer )
{
  var subscriberId = Guid.NewGuid( );
  subscribers.Add( subscriberId, observer );

  return new SubscriptionToken<T>
  (
    ( ) =>
    subscribers.Remove( subscriberId );
  );
}
</code>```

If your observer is catching events from multiple observables, you might want to ensure that there's some kind of correlation information in the events themselves...like .Net events do with the sender. It's up to you whether that matters or not. It's not baked in, as you've correctly reasoned. (question 3)

Body:
I know this is way late to the party, but...

The interfaces IObservable<T> and IObserver<T> are not part of Rx...they're core types...but Rx makes extensive use of them.

You are free to have as many (or as few) observers as you like. If you anticipate multiple observers, it's the observable's responsibility to route OnNext() calls to the appropriate observers for each observed event. The observable might need a list or a dictionary as you suggest.

There are good cases for allowing only one - and good cases for allowing many. For example, in an CQRS/ES implementation, you might enforce a single command handler per command type on a command bus, while you might notify several read-side transforms for a given event type in the event store.

As stated in other answers, there's no Unsubscribe. Disposing of the thing you're given when you Subscribe generally does the dirty work. The observer, or an agent thereof, is responsible for holding onto the token until it no longer wants to receive further notifications. (qestion 1)

So, in your example:

K.Subscribe(L1);
K.Subscribe(L2);
K.Unsubscribe();
L1.PublishObservation(1003);
L2.PublishObservation(1004);

...it would be more like:

using ( var l1Token = K.Subscribe( L1 ) )
{
  using ( var l2Token = K.Subscribe( L2 );
  {
    L1.PublishObservation( 1003 );
    L2.PublishObservation( 1004 );
  } //--> effectively unsubscribing to L2 here

  L2.PublishObservation( 1005 );
}

...where K would hear 1003 and 1004 but not 1005.

To me, this still looks funny because nominally, subscriptions are long-lived things...often for the duration of the program. They're not dissimilar in this respect to normal .Net events.

In a lot of examples I've seen, the Dispose of the token does work to remove the observer from the observable's list of observers. I prefer that the token not carry so much knowledge around...and so I have generalized my subscription tokens to just call a passed-in lambda (with identifying information captured at subscribe-time:

public class SubscriptionToken<T>: IDisposable
{
  private readonly Action unsubscribe;

  private SubscriptionToken( ) { }
  public SubscriptionToken( Action unsubscribe )
  {
    this.unsubscribe = unsubscribe;
  }

  public void Dispose( )
  {
    unsubscribe( );
  }
}

...and the the observable can install the unsubscribe behavior during subscription:

IDisposable Subscribe<T>( IObserver<T> observer )
{
  var subscriberId = Guid.NewGuid( );
  subscribers.Add( subscriberId, observer );

  return new SubscriptionToken<T>
  (
    ( ) =>
    subscribers.Remove( subscriberId );
  );
}

If your observer is catching events from multiple observables, you might want to ensure that there's some kind of correlation information in the events themselves...like .Net events do with the sender. It's up to you whether that matters or not. It's not baked in, as you've correctly reasoned. (question 3)


问:
The best practice for passing formatted string to methods
Though it might be trivial for someone, I find it a little inconvenient when someone formats the string while passing it as a parameter to a method. For e.g.

```<code>AddMessage( string.Format("{0} (" + Constants.Message1 + ")",
    Path.GetFileNameWithoutExtension(document.FileName)),
    string.Format("{0}" + FileExtensionPdf,
    Path.GetFileNameWithoutExtension(document.FileName)));
</code>```

I have taken a simple example here, but it could become a little messy sometimes. I prefer to not do this and instead format my string before I pass them to the method. For me, this reduces readability.

I would like to know if there is a standard practice which goes against the above style. Since I am doing a code review, I am not sure if I should put it as a comment.

答:
I would probably format your example code something like this:

```<code>var fileName = Path.GetFileNameWithoutExtension(document.FileName);
AddMessage(
    foo: string.Format("{0} ({1})", fileName, Constants.Message1),
    bar: string.Format("{0}{1}", fileName, FileExtensionPdf));
</code>```

I think it's fine to format your input directly in the call as long as you do it in a readable way. Here I also use named arguments since it's two string arguments and I want to communicate clearly and avoid the stupid mistake of swapping those arguments.

Using a temporary varible for the file name with no extension is both an optimization of code and readability.

Body:
I would probably format your example code something like this:

var fileName = Path.GetFileNameWithoutExtension(document.FileName);
AddMessage(
    foo: string.Format("{0} ({1})", fileName, Constants.Message1),
    bar: string.Format("{0}{1}", fileName, FileExtensionPdf));

I think it's fine to format your input directly in the call as long as you do it in a readable way. Here I also use named arguments since it's two string arguments and I want to communicate clearly and avoid the stupid mistake of swapping those arguments.

Using a temporary varible for the file name with no extension is both an optimization of code and readability.


答:
I agree expanding it out makes it more readable and maybe easier to debug. not sure I would raise it as a problem though.

```<code>const string msgFormat1 = "{0} ({1})";
const string msgFormat2 = "{0}.{1}";

string fileName = Path.GetFileNameWithoutExtension(document.FileName);

string msg1 = String.Format(
    msgFormat1,
    Constants.Message1,
    fileName
);

string msg2  = string.Format(
    msgFormat2,
    fileName,
    FileExtensionPdf,
);

AddMessage(msg1, msg2);
</code>```

edit : stole filename optimization from other answer

Title: The best practice for passing formatted string to methods

Body:
Though it might be trivial for someone, I find it a little inconvenient when someone formats the string while passing it as a parameter to a method. For e.g.

```<code>AddMessage( string.Format("{0} (" + Constants.Message1 + ")",
    Path.GetFileNameWithoutExtension(document.FileName)),
    string.Format("{0}" + FileExtensionPdf,
    Path.GetFileNameWithoutExtension(document.FileName)));
</code>```

I have taken a simple example here, but it could become a little messy sometimes. I prefer to not do this and instead format my string before I pass them to the method. For me, this reduces readability.

I would like to know if there is a standard practice which goes against the above style. Since I am doing a code review, I am not sure if I should put it as a comment.

Body:
I agree expanding it out makes it more readable and maybe easier to debug. not sure I would raise it as a problem though.

const string msgFormat1 = "{0} ({1})";
const string msgFormat2 = "{0}.{1}";

string fileName = Path.GetFileNameWithoutExtension(document.FileName);

string msg1 = String.Format(
    msgFormat1,
    Constants.Message1,
    fileName
);

string msg2  = string.Format(
    msgFormat2,
    fileName,
    FileExtensionPdf,
);

AddMessage(msg1, msg2);

edit : stole filename optimization from other answer


答:
I would simplify Torbjørn's answer with string interpolation:</p>

```<code>var fileName = Path.GetFileNameWithoutExtension(document.FileName);
AddMessage($"{fileName} ({Constants.Message1})", $"{fileName}{FileExtensionPdf}");
</code>```

Body:
I would simplify Torbjørn's answer with string interpolation:

var fileName = Path.GetFileNameWithoutExtension(document.FileName);
AddMessage($"{fileName} ({Constants.Message1})", $"{fileName}{FileExtensionPdf}");


问:
Is it a bad idea to put externally dependent logic in ORM classes?
Case in point in Entity Framework, but this is a design question which has applicability to any ORM.

In the current application we have a couple of ORM data classes which do stuff not directly related to the function of that class.

One example is the Document class, which is a database representation of document stored on the network drive. It has a constructor which actually makes a physical copy of the document:

public Document(string filePath, int categoryId, User currentUser)
{
    FileInfo info = new FileInfo(filePath);
    this.Name = info.Name;
    this.Size = info.Length.ToString();

    this.CategoryId = categoryId;
    this.User = currentUser;
    this. CreatedOn = DateTime.Now;

    targetPath = ConfigurationManager.AppSettings["CampaignFolder"];
    FileHelper.CopyFile(filePath, targetPath + "\" + this.Name);
}
```

<p>You can see how this would be convenient, especially if you're potentially loading files from lots of places in the code and you want them stored in a central location.</p>

<p>Another example is the Category class, which is related to the above. The class itself has a function that has to go back to the repository to do some additional work - so we pass one in:</p>

<pre class="lang-cs prettyprint-override"><code>public List<Document> SearchDocuments(string description, IRepository rep)
{
    if (this.Documents.Any(dc => dc.Description == description))
    {
        return this.Documents.(dc => dc.Description == description).ToList();
    }

    using (IRepository r = rep.Renew())
    {
        return r.GetDocuments(d => d.CategoryId == this.CategoryId
                        && dc.Description == description).ToList();
    }
}
</code>```

Again, you can see how this is convenient - it uses properties inherent to the object, and it's a useful place to put this function if it's called from a lot of different places.

It's also worth noting that this latter function, at least, doesn't break testability.

However, I can't help the sense that this is wrong somehow. It feels like a violation of single responsibility - these things are just for carrying data and perhaps some computed properties. But on the other hand, putting functions like this inside them removes the need for an annoying proliferation of helper classes.

Is this a bad idea? Or am I worrying over nothing?

答:
I think you are correct in your concerns.

In both cases I would separate the repository functions from the object.

The document object seems particularly bad in that the logic takes place in the constructor

ie

```<code>IDocumentRepository.Save(Document doc);
IDocumentRepository.Search(string description)
</code>```

This helps you achieve a number of things:

1: No dependency of the Object on the repository implementation

2: The responsibilities involved in persisting the object are encapsulated in their own repository object rather than the Domain object

Body:
I think you are correct in your concerns.

In both cases I would separate the repository functions from the object.

The document object seems particularly bad in that the logic takes place in the constructor

ie

IDocumentRepository.Save(Document doc);
IDocumentRepository.Search(string description)

This helps you achieve a number of things:

1: No dependency of the Object on the repository implementation

2: The responsibilities involved in persisting the object are encapsulated in their own repository object rather than the Domain object


问:
What is the correct name for this data object?
I need to understand the proper name for an object that has cropped up in two projects now.    Here is the conventional representation for the MVC pattern:

However there is another "Model" that is normally present in MVC, which passes the data between the controller and the view (and back):

What is the second model object called?   I have heard it referred to as a "Data Transfer Object," a "Value Object," and a "Model Object."

This object is typically necessary because the data being presented in a "View" is almost never in the same form as the data being stored in the data store.   Four or five (or more) DAOs may be pulled together in the service or controller to populate this object, and it may be used to update more than one DAO on the way back to the data store.

So, what is the "proper" name for this second model object?

(Image from Creative Commons, Shane Brinkman Davis)

答:
Meh.

Use whatever term you and your team are comfortable with, as long as you're consistent.

For what it's worth, when I was reading the question as soon as I saw

OTHER "MODEL" OBJECT

I thought "Data transfer object".


问:
How have you found, refined and maintained your coding style?
Recently, I've been switching between several projects and development environments. The expectations for coding style in each is different.

Now, my question is three part, the first, just of curiosity:

How did you define and find your coding style?

How do you keep augmenting and improving it?

How do you maintain it? (From mental notes, keeping a document, using a tool like StyleCop etc.)

答:
How did you define and find your
coding style?

I dont think there was a time where i said: "Ok this is going to be my style". Do focus on specific environment or language. Your style should reflect the way you face a certain problem.

How do you keep augmenting and
improving it?
Reading developers blogs could be useful to see what other are working on, looking for sofware widely used (if its so good, maybe you could use some of their solutions), etc.

How do you maintain it? (From mental
notes, keeping a document, using a
tool like StyleCop etc.)
This question rise another one: Could you loose your style? I think its a part of you so you cant, dont you?

ContentLicense: CC BY-SA 2.5


问:
Why is it called network "topology"? Why not network "graph"?
I want to understand why we use the term "network topology" as opposed to "network graph", or another term, to talk about the structure of networks. I'm working on a network design for a project, and want to make sure I don't use any terms that I don't truly understand.

Wikipedia defines network topology as "the arrangement of the various elements (links, nodes, etc.) of a computer network." This strikes me as interesting, because when I hear the words link and node, I immediately think of graph theory and the objects it is concerned with.

Topology, according to Wikipedia again, is "concerned with the properties of space that are preserved under continuous deformations..." And when you look at the basic examples of topological objects, you see coffee cups and Möbius strips, as opposed to the discrete vertices and edges you see with graph theory.

So why do we refer to networks as having a "topology"?

答:
Topology is the study of fundamental properties that exist no matter the arrangement of elements (for example the ratio of points, edges and faces in a polygon that does not change as you add or reduce points).

This term fits networks well because what you are looking for with network topology is the different arrangements of the network to perform the same function, with the goal being to produce the simplest configuration that you can to perform the task (thus eliminating waste)

A graph has a much more limited definition in mathematics and is not really about discovering the fundamental properties of arrangements.


答:
Yes, it is not good to put externally dependent logic in ORM classes.

Ideally, an ORM's sole purpose is to provide a map from the database to the objects used by the code (ie- Object Relational Mapping)

When you muddy the responsibility of an object's purpose you're breaking the ability to swap out components from the system without breaking the other parts.

If something changes about how the files are stored you now have to go inside the entity as well as wherever the files are accessed.  Two places to make changes instead of one place.

To keep the desired functionality, I would recommend setting up a service which can be aware of the Repository, Files & ORM.

Title: Is it a bad idea to put externally dependent logic in ORM classes?

Body:
Case in point in Entity Framework, but this is a design question which has applicability to any ORM.

In the current application we have a couple of ORM data classes which do stuff not directly related to the function of that class.

One example is the Document class, which is a database representation of document stored on the network drive. It has a constructor which actually makes a physical copy of the document:

public Document(string filePath, int categoryId, User currentUser)
{
    FileInfo info = new FileInfo(filePath);
    this.Name = info.Name;
    this.Size = info.Length.ToString();

    this.CategoryId = categoryId;
    this.User = currentUser;
    this. CreatedOn = DateTime.Now;

    targetPath = ConfigurationManager.AppSettings["CampaignFolder"];
    FileHelper.CopyFile(filePath, targetPath + "\" + this.Name);
}
```

<p>You can see how this would be convenient, especially if you're potentially loading files from lots of places in the code and you want them stored in a central location.</p>

<p>Another example is the Category class, which is related to the above. The class itself has a function that has to go back to the repository to do some additional work - so we pass one in:</p>

<pre class="lang-cs prettyprint-override"><code>public List<Document> SearchDocuments(string description, IRepository rep)
{
    if (this.Documents.Any(dc => dc.Description == description))
    {
        return this.Documents.(dc => dc.Description == description).ToList();
    }

    using (IRepository r = rep.Renew())
    {
        return r.GetDocuments(d => d.CategoryId == this.CategoryId
                        && dc.Description == description).ToList();
    }
}
</code>```

Again, you can see how this is convenient - it uses properties inherent to the object, and it's a useful place to put this function if it's called from a lot of different places.

It's also worth noting that this latter function, at least, doesn't break testability.

However, I can't help the sense that this is wrong somehow. It feels like a violation of single responsibility - these things are just for carrying data and perhaps some computed properties. But on the other hand, putting functions like this inside them removes the need for an annoying proliferation of helper classes.

Is this a bad idea? Or am I worrying over nothing?


问:
Should constant values be in SHOUT_CASE when there is language support for them?
Referring primarily to here, it suggests that values which are constant in JavaScript (using the keyword const) should be named in SHOUT_CASE. I'm of the opinion though that mutability is much more important (and rare) than immutability, at least in JavaScript, and that having so many variables put in SHOUT_CASE would actually harm readability, rather than aid it, and dilute the meaningfulness of the convention itself.

Now, I understand that SHOUT_CASE for constants is useful in languages that do not have inherent support for constant values built into the runtime - for example, ES5 javascript, where you had var and nothing else. But with language-level support for const values, is there much use for this convention any more?

At runtime, any identifier created using the keyword const cannot be re-used or re-assigned to. This isn't strictly const correctness in the C/C++ sense, but for primitives it is fine. For objects, you'd have to use Object.freeze to get const-correctness. JavaScript is far from the only language to do this, of course. Fields are commonly readonly (C#) or final (Java) [citation needed].

What benefits would having things labelled in SHOUT_CASE present in a language that already has const support built into the syntax?

答: The main benefit of using SHOUT_CASE for constants is to easily know when reading code when a particular value is not expected to change without having to look for the definition, or worse, having to search for every reference to that variable to see if its value changes.</p>


答:
ViewModel

If its responsibility is to hold model data in a format convenient for the view, then I would call it a ViewModel.

Title: What is the correct name for this data object?

Body:
I need to understand the proper name for an object that has cropped up in two projects now.    Here is the conventional representation for the MVC pattern:

However there is another "Model" that is normally present in MVC, which passes the data between the controller and the view (and back):

What is the second model object called?   I have heard it referred to as a "Data Transfer Object," a "Value Object," and a "Model Object."

This object is typically necessary because the data being presented in a "View" is almost never in the same form as the data being stored in the data store.   Four or five (or more) DAOs may be pulled together in the service or controller to populate this object, and it may be used to update more than one DAO on the way back to the data store.

So, what is the "proper" name for this second model object?

(Image from Creative Commons, Shane Brinkman Davis)


问:
Is this Red-Black tree insertion pseudocode from Introduction to Algorithms (CLRS) correct?
For the Red-black tree insertion fixup the book distinguishes between 6 cases, 3 of which are symmetric.
The cases are (z is the node being inserted):

Case 1: z's uncle is red

Case 2: z's uncle is black and z is a right child

Case 3: z's uncle is black and z is a left child

Case 2 is a subset of case 3, as we can transform Case 2 into 3 with a left rotation.

However in the book's pseudocode which you can see here or here they write as follows:

```<code>if uncle.color == red:
  # Handle case
else if z == z.p.right:
  # Handle case 2
  # Handle case 3
</code>```

Shouldn't this be:

```<code>if uncle.color == red:
  # Handle case
else:
  if z == z.p.right:
    # Handle case 2
  # Handle case 3
</code>```

Am I missing something? Does the book use else if in a different way than say Python does? The C++ implementation provided here uses the second version as I expected.

答:
The indentation in the code is important:

```<code>if uncle.color == red:
     # Handle case
else if z == z.p.right:
          # Handle case 2
     # Handle case 3
</code>```

The syntax is a bit quirky, because they squished the if to appear on the same line as the else, but case 2 is indented further inward compared to the remaining case 3, indicating that they do not belong to the same group.

This is what I think the author intended:

```<code>if (uncle.color == red)
{
   # Handle case
}
else
{
    if (z == z.p.right)
    {
         # Handle case 2
    }
    # Handle case 3
}
</code>```

Body:
The indentation in the code is important:

if uncle.color == red:
     # Handle case
else if z == z.p.right:
          # Handle case 2
     # Handle case 3

The syntax is a bit quirky, because they squished the if to appear on the same line as the else, but case 2 is indented further inward compared to the remaining case 3, indicating that they do not belong to the same group.

This is what I think the author intended:

if (uncle.color == red)
{
   # Handle case
}
else
{
    if (z == z.p.right)
    {
         # Handle case 2
    }
    # Handle case 3
}


问:
Should I bother learning about small or niche languages?
If you browse the code golf questions on StackExchange, you notice a ton of non-standard but real world (Eg not brain-f*ck) languages like F#, Scala, R, J and Clojure. Visiting their websites, some of the languages look interesting solving problems in whatever language your already using.

However there is coding in spare time, and coding for money. The closest thing we have to the truth on who uses a language is the TIOBE Index, which lists none of the above languages in the top 10-15. Which makes me wonder if I'll ever use them.

Should I even bother learning some of the small niche languages? It doesn't seem I would be making money, and some will probably fail anyway.

答: The reason to study a niche language is rarely the expectation that you'll use it directly (for money or otherwise). It's usually to learn some new aspect or style of programming. Doing so is likely to make you a better (and yes, probably more valuable) programmer, even if you never use that language to produce "production" code.</p>


问:
Anonymous namespaces make code untestable
Here is a typical C++ code:

foo.hpp

```<code>#pragma once

class Foo {
public:
  void f();
  void g();
  ...
};
</code>```

foo.cpp

```<code>#include "foo.hpp"

namespace {
    const int kUpperX = 111;
    const int kAlternativeX = 222;

    bool match(int x) {
      return x < kUpperX || x == kAlternativeX;
    }
} // namespace

void Foo::f() {
  ...
  if (match(x)) return;
  ...
</code>```

It looks like a decent idiomatic C++ code - a class, a helper function match which is used by the methods of Foo, some constants for that helper function.

And then I want to write tests.

It would be perfectly logical to write a separate unit test for match, because it's quite non-trivial.

But it resides in an anonymous namespace.

Of course I can write a test which would call Foo::f(). However it won't be a good test if Foo is heavy and complicated, such test won't isolate the testee from other unrelated factors.

So I have to move match and everything else out of the anonymous namespace.

Question: what's the point of putting functions and constants into the anonymous namespace, if it makes them unusable in tests?

答:
The function in your example looks quite complex, and it may be better to move it to the header, for the purpose of unit testing.

what's the point of putting functions and constants into the anonymous namespace, if it makes them unusable in tests?

To make them isolated from rest of the world. And it is not only functions and constants that you can put in the anonymous namespace - it is also for types.

However, if it makes your unit tests very complex, then you are doing it wrong. In such case the function doesn't belong there. Then it is time for a little refactoring to make the testing simpler.

So, in anonymous namespace should go only very simple functions, sometimes constants and types (including typedefs) used in that translation unit.


答:
I'm probably thinking about this differently than most, but to me the complex amalgum of all the different DAOs is the model.  As in, that is your Business Model of the data.  I'd then draw a separate little "DataStore" entity (with, perhaps, a "*" to indicate multiple) with the classic cylinder "disk" graphic, and hang it off Model.

Alternatively, I'd suggest you call it "Business Model".  @MetaFight " View Model" is O.K. too.


答:
This is a tricky problem but one that many people face. I prefer using the Gitflow setup as a starting point.

Development -> New stuff being worked on

Master -> Finished stuff needing testing
Production -> Stuff that has been published to production.

At minor (shorter) features I create a branch from development do the work there then merger the branch back to development.

At major (long term) features I create a branch from development, create smaller branches from that branch, then merge back to the first branch. Once the major feature is complete then back into development branch it goes.

At regular intervals (depends on project) I merge development back into master and a testing cycle begins. If any fixes come up in testing they are done in the master branch (sub branch then merge in). And development can continue on the master branch during testing.

At any time master should be merged into development, and development should be merged to any of it's long term sub branches.

master should always (in theory) be ready for production. Development should always (in theory) be ready for production. The only reason there is a difference it to provide a solid set of features for testers to test.

When ready, a commit in master that is tested is merged in to production and deployment in production happens from that branch. HOTFIXs that need to be done in an emergency can then take place on Production branch without having to merge in master (which may have many un-tested changes).

My normal Tree looks like

```<code> LongTerm -> Development -> Master -> Production
 LongTerm <- Development      |            |
     |       Development -> Master         |
 LongTerm <- Development -> Master         |
             Development <- Master         |
                            Master -> Production
</code>```

It is my general rule that no single change should take more then a few hours. If it does then it needs to be made into smaller changes. If it's a huge feature (like a UI re-write) then that goes in long term so that normal development can continue at the same time. LongTerm branches are normally only local branches while Development, Master, and Production are remote branches. Any sub branches are also local only. This keeps the repository clean for others, without loosing the usefulness of git on a long term feature set.

I would like to note, however, that the existence of a long term branch is a rare thing. Normally, all my work is in development. Only when I have a feature (set) that is going to take so long that I need to be able to work on normal dev stuff too, do I use the LongTerm branch. If it's just a set of changes that should be together then I just don't merge to master till there all done.

Body:
This is a tricky problem but one that many people face. I prefer using the Gitflow setup as a starting point.

Development -> New stuff being worked on

Master -> Finished stuff needing testing
Production -> Stuff that has been published to production.

At minor (shorter) features I create a branch from development do the work there then merger the branch back to development.

At major (long term) features I create a branch from development, create smaller branches from that branch, then merge back to the first branch. Once the major feature is complete then back into development branch it goes.

At regular intervals (depends on project) I merge development back into master and a testing cycle begins. If any fixes come up in testing they are done in the master branch (sub branch then merge in). And development can continue on the master branch during testing.

At any time master should be merged into development, and development should be merged to any of it's long term sub branches.

master should always (in theory) be ready for production. Development should always (in theory) be ready for production. The only reason there is a difference it to provide a solid set of features for testers to test.

When ready, a commit in master that is tested is merged in to production and deployment in production happens from that branch. HOTFIXs that need to be done in an emergency can then take place on Production branch without having to merge in master (which may have many un-tested changes).

My normal Tree looks like

 LongTerm -> Development -> Master -> Production
 LongTerm <- Development      |            |
     |       Development -> Master         |
 LongTerm <- Development -> Master         |
             Development <- Master         |
                            Master -> Production

It is my general rule that no single change should take more then a few hours. If it does then it needs to be made into smaller changes. If it's a huge feature (like a UI re-write) then that goes in long term so that normal development can continue at the same time. LongTerm branches are normally only local branches while Development, Master, and Production are remote branches. Any sub branches are also local only. This keeps the repository clean for others, without loosing the usefulness of git on a long term feature set.

I would like to note, however, that the existence of a long term branch is a rare thing. Normally, all my work is in development. Only when I have a feature (set) that is going to take so long that I need to be able to work on normal dev stuff too, do I use the LongTerm branch. If it's just a set of changes that should be together then I just don't merge to master till there all done.


答:
There are many answers already, but I just wanted to add my summary.

Clearly NoSQL concept covers a variety of different approaches in organizing data on-disk, in-memory and exposing it via a query language (some are even SQL-like!). In my view the strength comes from this variety of systems so you can choose the best tool for the job. But still hopefully you can cover a dozen different needs with just a few different solutions, you wouldn't want to manage a dozen different systems.

Relational databases can get you very far and are a proven technology, but just like the database you might want to choose the programming language based on each project's needs (but taking team's experience into account as well).

Title: Is the use of NoSQL Databases impractical for large datasets where you need to search by content?

Body:
I've been learning about NoSQL Databases for a week now.

I really understand the advantages of NoSQL Databases and the many use cases they are great for.

But often people write their articles as if NoSQL could replace Relational Databases. And there is the point I can't get my head around:

NoSQL Databases are (often) key-value stores.

Of course it is possible to store everything into a key-value store (by encoding the data in JSON, XML, whatever), but the problem I see is that you need to get some amount of data that matches a specific criterion, in many use cases. In a NoSQL database you have only one criterion you can search for effectively - the key. Relational Databases are optimized to search for any value in the data row effectively.

So NoSQL Databases are not really a choice for persisting data that need to be searched by their content. Or have I misunderstood something?

An example:

You need to store user data for a webshop.

In a relational database you store every user as an row in the users table, with an ID, the name, his country, etc.

In a NoSQL Database you would store each user with his ID as key and all his data (encoded in JSON, etc.) as value.

So if you need to get all users from a specific country (for some reason the marketing guys need to know something about them), it's easy to do so in the Relational Database, but not very effective in the NoSQL Database, because you have to get every user, parse all the data and filter.

I don't say it's impossible, but it gets a lot more tricky and I guess not that effective if you want to search in the data of NoSQL entries.

You could create a key for each country that stores the keys of every user who lives in this country, and get the users of a specific country by getting all the keys which are deposited in the key for this country. But I think this techique makes a complex dataset even more complex - it's harder to implement and not as effective as querying an SQL Database. So I think it's not a way you would use in production. Or is it?

I'm not really sure if I misunderstood something or overlooked some concepts or best practices to handle such use cases. Maybe you could correct my statements and answer my questions.


问:
How unit test service method that use repository method
For service methods that call repository methods to interact with database how could I unit test these service methods?

For example,

public function updateSlideshow($data){
    // do some logic and method calls (I can test those methods,
    // but for this method that call repository ...)

    $r = $this->blockRepo->update($data, $config, $slides);
}
```

How can I check that this method work correctly or at least send right data to update method?

And what about a scenario that method first fetch data from repository and do logic on it?

答:
Don't unit test them, at least at first. Use an integration test which brings up an empty database with your DDL loaded, runs this method with some inputs, and asserts on the result data or result behavior.

Having that integration test in place will be a good stepping stone for creating a test double. Code your db-interacting code against an interface which your db class implements. You can then make a test double implementation that uses a Map locally to provide the same interface. That double can be passed along to other pieces of code which depend on database functionality. The integration test you wrote for the full database version can be used to cross-check that the test double exposes correct behavior.


问:
Suggestions for structuring complex json structures?
I can't find many tips for how to design complex json structures beyond the obvious tips of not trying to nest too deeply, using defined data types, etc.

For example, if I have a location that needs to have security scanning done on all of its segments and devices within the segments, there are many options of how I could do this.

```<code>{
    "site": "Site 1",
    "segments": [
        {
            "name": "Segment 1",
            "devices": [
                {
                    "name": "Device 1",
                    "scans": [
                        {
                            "type": "discovery",
                            "date": "2016-01-12",
                            "phase": "10",
                            "remediate": "0"
                        },
                        {} ...
                    ]
                },
                {} ...
            ]
        },
        {} ...
    ]
}
</code>```

For this example, a few questions come to mind:

Is it okay to use the property "name" twice, since they are on different levels? I've read that it's better to keep the property names short for parsers. Therefore, should you use it twice? Or change them to "seg_name" and "dev_name", for example?

You can see a clear pattern for "segments", "devices", and "scans" where they are each an array of objects.

I could change it to something like this:

```<code>{
    "site": "Site 1",
    "segments": {
        "Segment 1": {
            "Device 1": {
                "discovery": {
                    "date": "2016-01-12",
                    "phase": "10",
                    "remediate": "0"
                },
                "exploit": {} ...
            },
            "Device 2": {} ...
        },
        "Segment 2": {} ...
    }
}
</code>```

The issue I can see popping up with this format is that if you wanted to have a property for all of the segments, you would have to put it at the root level, instead of inside the "segments" property, since the property name could possibly conflict with a segment name. However, it is less nested, which is a plus.

I'm wondering if there are some guidelines of which situations are best suited for a certain format?

If it's really dependent on what language you are using it for, I would be sending the data between JavaScript and PHP.

答:
I'm no expert on JS or PHP so there might be some caveats I'm not aware of, but these are some ideas that come to my mind when I see this.

First off, I think your first idea is great. To answer the points you are raising:

Is it okay to use the property "name" twice, since they are on different levels? I've read that it's better to keep the property names short for parsers. Therefore, should you use it twice? Or change them to "seg_name" and "dev_name", for example?

If I have a type MyType and want to store its name, I'd really expect it to be MyType.Name, not MyType.MyTypeName. Generally, a property should not be concerned with what its parent is, that's the parent's responsibility.

In JSON, all the key-value pairs should be scoped so that there is a difference between json["key1"].Name and json["key1"].Elements[0].Name as those are two separate entities living in different nodes. In case some parser doesn't respect this, it's probably rigged far beyond of what is acceptable json anyway.

If only reasoning would be parser speed, I don't think that adding a few characters to a string would make that much of a difference on the other hand.

You can see a clear pattern for "segments", "devices", and "scans" where they are each an array of objects.

The correct way to model a 1:N relationship (i.e. one segment has N devices) is using a collection, an array of objects in case of JSON, so you were originally on the right track.

If I wanted to go through all the devices on a given segment, I'd rather do it in a simple array accessing loop than checking if device1 is defined on the segment, then device2 is defined on the segment, ...

Concerning the deep nesting, the issue with that is most presumably human-readability. This can be mitigated by splitting the json into subparts, children nodes in the current code becoming the new roots.

To achieve that, it might be a good idea to think about how you query and send the data instead of formatting it differently (or even making it poorly structured). Consider this communication scenario:

Client queries available segments

Server replies with a list of available segmentIds

Client queries a segment by segmentId

Server replies with the segment data which in turn contains deviceIds

Client queries a device by segmentId and deviceId

...

This is obviously the extreme opposite of what you have right now, a very heavy client-server ping-pong which would be really inefficient in real world.

It's up to you to make the decision of how each payload should look, considering both number of requests to acquire sensible amount of data and the size of data in each response.

But this really feels to me more of an networking architecture problem, not really connected to whether you serialize to json, xml or binary.

If you are really concerned with the width due to nesting, there is no globally accepted standard. There was 80 characters width "limit" in the early days due to terminal screen size. Apart from strict hardware limits, I don't think it's necessary to stick to some number, maybe around 120-150 could be a nice guideline these days.

However, left to your values in JSON is meaningless whitespace so if you press your decrease indent-shortcut a few times, nothing bad happens. Given that your JSON will be handled by computers most of the time anyway, I think you can drop the readability requirement altogether in face of a good design.


问:
How useful are function points?
How useful is it to measure function points?

We use function points at my new job.  I've heard of function points but haven't had any training or experience... but I don't have much confidence in things that cannot be explained succinctly.

答:
Personally, I have never found an explicit answer to the question "What is a Function Point?"  Without such, I'm REALLY hesitant about any estimating methodology that claims to do anything with Function Points.

The single most important part of a serious software estimation methodology is "periodic recalibration to actuals", which means you make your estimate, you write it down, and then, when the project is over, you compare your actual results to your estimate, and, if necessary, revise your estimating process.  INCLUDED IN THAT is comparing your the INPUTS to your estimating process with the ACTUAL INPUTS.

If, for example, you estimate Source Lines of Code (SLOC), and go from there, you have to compare your actual delivered SLOC with your estimated SLOC, and see whether, how far, and where and why you went astray.  An estimator that predicts man-hours perfectly, given an accurate and precise SLOC estimate in, is not going to do you any good if your SLOC estimates are worthless.  Garbage in, garbage out.  (The same thing applies to Function Points.)

If your SLOC (or Function Point) actuals match your initial estimates, then you can look at your cost actuals against your estimated costs, and adjust your estimator parameters to improve your results.  General Dynamics/Fort Worth Division did this exercise, in detail, in the early 1980s, for F-16C/D software development, and then for several years would routinely bet the company bottom line on those estimates.  GD/FW was GD's cash cow for quite a while, keeping the rest of the firm afloat, so they must have been doing something right.

And note that requirements and feature creep is THE ENEMY of software estimation.

(This is a later edit.)  Bernd's last point deserves an answer.  He asks what should be done about projects that come in early, and don't expend all their allocated man-hours.

This is just as much an estimating error as the (far more common) schedule overruns.  The fact of the matter is this: if all of your projects are overrunning their schedule, your estimating folks are not doing their job.

If your estimating folks are doing everything right, and your managers are doing everything right, then you are going to have some projects come in early, along with the ones that come in late.  Estimates are probabilities.  Shade your estimator to eliminate schedule underruns, and you BY DEFINITION increase the probability of schedule overruns.  If your management demands schedules and estimates with zero possibility of underrun, then you are going to be delivering schedules that WILL be overrun, guaranteed, and then you will start seeing demands for Death Marches, and then you start seeing resignations, and your overruns get much, much worse, as you try to recruit replacements (and the word gets out that your company is a sweatshop).

Title: How useful are function points?


问:
Where to put configuration constants?
Considering a small embedded C project, how to decide if certain constants belong to

a global configuration file

the header of the "module == compilation unit"

on top of the the actual C file

or inside the code?

I am talking about constants that can often change, and need to be conveniently located for the end user, as well as for the developer. Several examples include ENABLE_GLOBAL_ERROR_CHECKING, USART_BAUD_RATE and TEMPERATURE_SETPOINT.

答:
If the user should be able to change the values, putting them in the code as constants is obviously not an option. A text file with key-value pairs seems appropriate (concidering it is for a small project).

In general you should ask yourself if you want to tie your settings to a group of users, the machine, the program file or the individual user. You may want to combine them too, having user settings override machine- or group settings.

Or you may accept a settings file path as an argument to your program so you can keep multiple configurations that may be activated on a per run basis.

Title: Where to put configuration constants?


问:
Justification for bidirectional relationship
I typically try and avoid bidirectional relationships at all costs.  Recently I've been trying to follow a more domain centric design philosophy and I'm looking for advice in the best way to solve a specific problem.

I am implementing a basic 2d grid.  There are 3 basic classes, Item, Tile (has a list of Items), and World (has a 2d array of Tiles).

I am struggling with where to put the move() method which moves an item from one tile to a neighboring tile.  My initial inclination would be to place the move method in the Item class since it is the item that is actually moving.

However, that would create a circular dependency.  In the past I always worked with dumb objects in which case the move() method was in a higher layer (some kind of WorldManager or MoveManager) which knows about both tiles and items. I'm interested in what proposals others might have that can avoid the circular dependency while maintaining the domain-centric philosophy.

答:
For DDD, most important thing to start with is the domain knowledge. If, all you do with your 'basic 2d grid', is moving items from one tile to another, then why do you need to put a list of items in a tile? For what use case?

If I was you, I would be looking for aggregate root here. Probably, 'world' could be the one here where you could put the move method. All depends on the domain and its use cases.

A relevant exercise could be found in Effective Aggregate Design by Vaughn Vernon


答:
I am struggling with where to put the move() method which moves an item from one tile to a neighboring tile. My initial inclination would be to place the move method in the Item class since it is the item that is actually moving.

Which class has the responsibility of maintaining the invariant?

For instance, if there's a rule that you can only move items to neighboring tiles, then the move method should be implemented on which ever object knows which tiles are neighbors.

Caution: one of the difficulties of DDD and "simple" problems: the business rule is actually "do whatever the human operator tells you", and there isn't actually an invariant to be implemented in the model.

Title: Justification for bidirectional relationship

Body:
I typically try and avoid bidirectional relationships at all costs.  Recently I've been trying to follow a more domain centric design philosophy and I'm looking for advice in the best way to solve a specific problem.

I am implementing a basic 2d grid.  There are 3 basic classes, Item, Tile (has a list of Items), and World (has a 2d array of Tiles).

I am struggling with where to put the move() method which moves an item from one tile to a neighboring tile.  My initial inclination would be to place the move method in the Item class since it is the item that is actually moving.

However, that would create a circular dependency.  In the past I always worked with dumb objects in which case the move() method was in a higher layer (some kind of WorldManager or MoveManager) which knows about both tiles and items. I'm interested in what proposals others might have that can avoid the circular dependency while maintaining the domain-centric philosophy.


问:
Is there a standard way or standard alternative to packing a struct in c?
When programming in C I have found it invaluable to pack structs using GCCs __attribute__((__packed__)) attribute so I can easily convert a structured chunk of volatile memory to an array of bytes to be transmitted over a bus, saved to storage or applied to a block of registers. Packed structs guarantee that when treated as an array of bytes it will not contain any padding, which is both wasteful, a possible security risk and possibly incompatible when with interfacing hardware.

Is there no standard for packing structs that works in all C compilers? If not then I am an outlier in thinking this is a critical feature for systems programming? Did early users of the C language not find a need for packing structs or is there some kind of alternative?

答:
In a struct, what matters is the offset of each member from the address of each struct instance. Not so much is the matter of how tightly things are packed.

An array, however, matters in how it is "packed". The rule in C is that each array element is exactly N bytes from the previous, where N is the number of bytes used to store that type.

But with a struct, there is no such need for uniformity.

Here's one example of a weird packing scheme:

Freescale (who make automotive microcontrollers) make a micro that has a Time Processing Unit co-processor (google for eTPU or TPU). It has two native data sizes, 8 bits and 24 bits, and only deals with integers.

This struct:

```<code>struct a
{
  U24 elementA;
  U24 elementB;
};
</code>```

will see each U24 stored its own 32 bit block, but only in the highest address area.

This:

```<code>struct b
{
  U24 elementA;
  U24 elementB;
  U8  elementC;
};
</code>```

will have two U24s stored in adjacent 32 bit blocks, and the U8 will be stored in the "hole" in front of the first U24, elementA.

But you can tell the compiler to pack everything into its own 32 bit block, if you want; it's more expensive on RAM but uses less instructions for accesses.

"packing" doesn't mean "pack tightly" - it just means some scheme for arranging elements of a struct wrt the offset.

There is no generic scheme, it is compiler+architecture dependent.

Body:
In a struct, what matters is the offset of each member from the address of each struct instance. Not so much is the matter of how tightly things are packed.

An array, however, matters in how it is "packed". The rule in C is that each array element is exactly N bytes from the previous, where N is the number of bytes used to store that type.

But with a struct, there is no such need for uniformity.

Here's one example of a weird packing scheme:

Freescale (who make automotive microcontrollers) make a micro that has a Time Processing Unit co-processor (google for eTPU or TPU). It has two native data sizes, 8 bits and 24 bits, and only deals with integers.

This struct:

struct a
{
  U24 elementA;
  U24 elementB;
};

will see each U24 stored its own 32 bit block, but only in the highest address area.

This:

struct b
{
  U24 elementA;
  U24 elementB;
  U8  elementC;
};

will have two U24s stored in adjacent 32 bit blocks, and the U8 will be stored in the "hole" in front of the first U24, elementA.

But you can tell the compiler to pack everything into its own 32 bit block, if you want; it's more expensive on RAM but uses less instructions for accesses.

"packing" doesn't mean "pack tightly" - it just means some scheme for arranging elements of a struct wrt the offset.

There is no generic scheme, it is compiler+architecture dependent.


问:
Do any Java libraries support batch sql query processing and proceeds even if any duplicate records exists in the batch?
Is batch processing possible in jdbi with the below condition?

If one insert query in the batch fails because of violating some constraints ( Primary key, foreign key violation.. etc) will it resume processing next set of insert queries in the batch?

答:
Unfortunately for JDBI, you will have to deal with poor documentation and - I guess - trial and error. Specifically for Batch processing,

It fails to clearly document when a commit is being executed: not (at the end or through auto commit), equal to the batch size, or some other customizable parameter. As it does the batch iteration for you, it is a very important fact.

It does not document the method signature that is tagged with the SqlBatch annotation very well. Is the return type only void, or can it return an array that will provide me result status?

Looks like an interesting and promising API. But for me using it, I will be stuck with too many questions.


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
I'd like to see some native way to set open_basedir in virtual hosts based on domain name automatically, without having to configure one directive per host (similar to Jason Greene patch, but native).

Please, application-wide globals! App global variables would be available to all php scripts, once initialized.

Some way to release session for other threads, without closing them:

```
session_start();
$_SESSION['favcolor'] = 'white';
session_flush(); // session is now unblocked so other threads can use it
// huge loop ...
$_SESSION['taste'] = 'sweet'; // session blocks automatically again
session_close();
```

Maybe some on-disk cache would be nice, so we can precompile php scripts manually for faster execution. Similar to memory caches, but with files on disk and manual generation (probably using some new file extension).

Also, something similar to <?php =$variable ?> as shortcut to <?php echo $variable; ?> would be nice (as in asp tags, but with short/asp tags disabled).

Body:
I'd like to see some native way to set open_basedir in virtual hosts based on domain name automatically, without having to configure one directive per host (similar to Jason Greene patch, but native).

Please, application-wide globals! App global variables would be available to all php scripts, once initialized.

Some way to release session for other threads, without closing them:

session_start();
$_SESSION['favcolor'] = 'white';
session_flush(); // session is now unblocked so other threads can use it
// huge loop ...
$_SESSION['taste'] = 'sweet'; // session blocks automatically again
session_close();

Maybe some on-disk cache would be nice, so we can precompile php scripts manually for faster execution. Similar to memory caches, but with files on disk and manual generation (probably using some new file extension).

Also, something similar to <?php =$variable ?> as shortcut to <?php echo $variable; ?> would be nice (as in asp tags, but with short/asp tags disabled).

OwnerDisplayName: Bacco


答:
For embedded programming, it is usually preferable to have the constants at the top of the source file. This is to ensure readability and ease to change the value quickly without having to delve into the code and modify them.

```<code>#include <thisLibrary.h>
#include <thisOtherLibrary.h>

#define USART_BAUD_RATE 10000
#define SOME_OTHER_VALUE 1234
</code>```

For other purposes, use files like XML and JSON to save the data. Of course, special libraries will be required to read these into your program.

Title: Where to put configuration constants?

Body:
Considering a small embedded C project, how to decide if certain constants belong to

a global configuration file

the header of the "module == compilation unit"

on top of the the actual C file

or inside the code?

I am talking about constants that can often change, and need to be conveniently located for the end user, as well as for the developer. Several examples include ENABLE_GLOBAL_ERROR_CHECKING, USART_BAUD_RATE and TEMPERATURE_SETPOINT.

Body:
For embedded programming, it is usually preferable to have the constants at the top of the source file. This is to ensure readability and ease to change the value quickly without having to delve into the code and modify them.

#include <thisLibrary.h>
#include <thisOtherLibrary.h>

#define USART_BAUD_RATE 10000
#define SOME_OTHER_VALUE 1234

For other purposes, use files like XML and JSON to save the data. Of course, special libraries will be required to read these into your program.


问:
What would be a good approach to generate a tree of folders?
Say I have an array of strings, like this:

var folders = new[]
{
    "Foo",
    "Bar",
    "Foo\Bar"
    "Foo\Bar\Baz"
};
```

<p>And that I have an object that represents a folder - something like this:</p>

<pre class="lang-cs prettyprint-override"><code>class Folder
{
    private readonly string _name;
    private readonly IEnumerable<Folder> _folders;

    public Folder(string name, IEnumerable<Folder> folders)
    {
        _name = name;
        _folders = folders;
    }

    public string Name { get { return _name; } }
    public IEnumerable<Folder> Folders { get { return _folders; } }
}
</code>```

What would be a good way to end up with an object structure like this?

```<code>- Folder {Name:Foo}
  - Folder {Name:Bar}
    - Folder {Name:Baz}
- Folder {Name:Bar}
</code>```

I'm thinking this in terms of splitting the strings on the delimiter and then grouping... and I'm thinking this wrong, I simply don't have an approach to get there, it's not going anywhere. I get the gut-feeling that I need to involve recursion somehow, but I don't see where to fit that in, I'm stuck.

The example code above is C#, but I don't need actual code, just some pseudo-code, or a line of thought, a little clue.

...I hope it's in-scope?

答:
Let's assume you have an additional method GetOrCreate(name) that returns a folder for a given name, or creates it if no such folder exist, and that you have a root folder that contains your whole hierarchy. Then given a list of strings path, we can easily implement an iterative solution:

```<code>Folder current = root;
for (name in path)
  current = current.GetOrCreate(name);
</code>```

Alternatively you could define a recursive method MakePath(path):

```<code>public void MakePath(names) {
  return if path is empty;
  GetOrCreate(path.First).MakePath(path.Rest);
}
</code>```

The interesting question is how GetOrCreate might work. Your problem is that you are using an IEnumerable<Folder>, where you really want an associative data structure (map, dictionary, hash table, whatever that's called in your language). This allows easy membership test, and enforces uniqueness – no two folders with the same parent can share the same name.

The root folder would be another problem in your current design, since it doesn't have any obvious name (well, in Windows land that would be kind of like the drive letters, but that might be useless in your application). Instead, the name of childs might be a property of the parent folder, not of the child folders. The name is implicit as the key in the hash table rather than an explicit object property. This avoids data duplication, but makes it hard to answer questions like “given this folder, what is its name?”. Of course, it's already difficult to answer “given this folder, what is its full path?”, unless each folder has easy access to its name and its parent.

Body:
Let's assume you have an additional method GetOrCreate(name) that returns a folder for a given name, or creates it if no such folder exist, and that you have a root folder that contains your whole hierarchy. Then given a list of strings path, we can easily implement an iterative solution:

Folder current = root;
for (name in path)
  current = current.GetOrCreate(name);

Alternatively you could define a recursive method MakePath(path):

public void MakePath(names) {
  return if path is empty;
  GetOrCreate(path.First).MakePath(path.Rest);
}

The interesting question is how GetOrCreate might work. Your problem is that you are using an IEnumerable<Folder>, where you really want an associative data structure (map, dictionary, hash table, whatever that's called in your language). This allows easy membership test, and enforces uniqueness – no two folders with the same parent can share the same name.

The root folder would be another problem in your current design, since it doesn't have any obvious name (well, in Windows land that would be kind of like the drive letters, but that might be useless in your application). Instead, the name of childs might be a property of the parent folder, not of the child folders. The name is implicit as the key in the hash table rather than an explicit object property. This avoids data duplication, but makes it hard to answer questions like “given this folder, what is its name?”. Of course, it's already difficult to answer “given this folder, what is its full path?”, unless each folder has easy access to its name and its parent.


答:
The following algorithm should do almost what you've asked for.

```
paths : List<String>    <i>;; your list of paths</i>
tree : Folder = <b>NEW</b> Folder("")
<b>FOREACH</b> path <b>IN</b> paths <b>DO</b>
    node : Folder = tree
    <b>FOREACH</b> component <b>IN</b> split(path, "/") <b>DO</b>
        next : Folder = node.getChild(component)
        <b>IF</b> next <b>IS</b> <b>NULL</b> <b>THEN</b>
            next := <b>NEW</b> Folder(component)
            node.addChild(next)
        <b>FI</b>
        node := next
    <b>DONE</b>
<b>DONE</b>
```

I'm saying almost because it will create a directory tree under a common root node labeled with the empty string (like / in POSIX file systems).  If you don't want this but rather have a forest of directory trees, you'd have to write a small data structure to hold the forest's trees. Or you go ahead and use the common root and after you've built the tree, extract its child nodes (the trees) into a list.

The code example assumes a method Folder::getChild that will either return a reference to a child with that name if it exists or else the NULL pointer. Folder::addChild is of course supposed to add another child Folder.

Title: What would be a good approach to generate a tree of folders?

Body:
Say I have an array of strings, like this:

var folders = new[]
{
    "Foo",
    "Bar",
    "Foo\Bar"
    "Foo\Bar\Baz"
};
```

<p>And that I have an object that represents a folder - something like this:</p>

<pre class="lang-cs prettyprint-override"><code>class Folder
{
    private readonly string _name;
    private readonly IEnumerable<Folder> _folders;

    public Folder(string name, IEnumerable<Folder> folders)
    {
        _name = name;
        _folders = folders;
    }

    public string Name { get { return _name; } }
    public IEnumerable<Folder> Folders { get { return _folders; } }
}
</code>```

What would be a good way to end up with an object structure like this?

```<code>- Folder {Name:Foo}
  - Folder {Name:Bar}
    - Folder {Name:Baz}
- Folder {Name:Bar}
</code>```

I'm thinking this in terms of splitting the strings on the delimiter and then grouping... and I'm thinking this wrong, I simply don't have an approach to get there, it's not going anywhere. I get the gut-feeling that I need to involve recursion somehow, but I don't see where to fit that in, I'm stuck.

The example code above is C#, but I don't need actual code, just some pseudo-code, or a line of thought, a little clue.

...I hope it's in-scope?

Body:
The following algorithm should do almost what you've asked for.

paths : List<String>    ;; your list of paths
tree : Folder = NEW Folder("")
FOREACH path IN paths DO
    node : Folder = tree
    FOREACH component IN split(path, "/") DO
        next : Folder = node.getChild(component)
        IF next IS NULL THEN
            next := NEW Folder(component)
            node.addChild(next)
        FI
        node := next
    DONE
DONE

I'm saying almost because it will create a directory tree under a common root node labeled with the empty string (like / in POSIX file systems).  If you don't want this but rather have a forest of directory trees, you'd have to write a small data structure to hold the forest's trees. Or you go ahead and use the common root and after you've built the tree, extract its child nodes (the trees) into a list.

The code example assumes a method Folder::getChild that will either return a reference to a child with that name if it exists or else the NULL pointer. Folder::addChild is of course supposed to add another child Folder.