答:
For terminology in Domain Driven Design, start from "the blue book" -- Domain Driven Design by Eric Evans.

AGGREGATE
  A cluster of associated objects that are treated as a unit for the purpose of data changes.  External references are restricted to one member of the aggregate, designated as the root.  A set of consistency rules applies within the aggregate's boundaries.

That last sentence, I think you can turn around -- the boundaries of the aggregate are defined by the consistency rules.

It's definitely the case that an aggregate has state.  Each time the domain model changes, an aggregate is taken from one consistent state to another.  The data that we persist is used to reconstruct this state.  So in that sense, it is a real thing.

But the aggregate itself doesn't necessarily have a word in the ubiquitous language.  It's a derived concept.

Broadly, we could put the entire domain model under a single aggregate, that enforces all of the consistency rules.  We don't, because it that design doesn't scale: we can't change the domain model two different ways at the same time, even when the changes we are making don't share any consistency rules.  It's a poor way to model a business that can do more than one thing at a time.

Instead, we decompose the consistency rules into sets, subject to the constraint that two rules that reference the same data must be part of the same set.  (In doing this, we are also working with the ubiquitous language and the domain experts to determine if we are correctly describing the consistency rules).

To update the model, we identify the aggregate responsible for a piece of data and propose the change.  If the aggregate verifies all of its local consistency rules, we know that the change is globally valid, and we can apply the change.  This restores our ability to do more than one thing at a time - changes to data in different aggregates can't possibly conflict with each other, by construction.

Best practices suggest that most aggregates should contain only the root entity.  So you can conflate the aggregate with the entity without too much risk.  But my guess it there won't usually be anything in the ubiquitous language to hang on the cluster when it includes more than one entity; so you end up with the ShoppingCart aggregate maintaining the consistency rules for the ShoppingCart entity and the CartItems entity collection and....

Partial loading of an aggregate is broken when trying to apply a change -- how could a well designed aggregate possible validate all of its consistency rules with a subset of the data?  It's certainly the case that, if you have a requirement where this makes sense, your modeling is broken somewhere.

But if you are doing a read, loading only some of the data guarded by the aggregate can make sense.  Command Query Responsibility Separation (CQRS) takes this a step further; once the model has verified that the data satisfies the consistency rules, you can completely rearrange that data into whatever read only form makes your life easiest.  Put another way, if you aren't concerned with data changes, you don't need to worry about the aggregate boundary at all.

Title: Confusion about the meaning of the word aggregate in domain driven design

Body:
In a discussion about domain driven design I have learned the different people seem to think of different things when using the word aggregate. The main difficulty is that some people use the word aggregate for what other people call aggregate type.

It is quite difficult to have a discussion if people assume different meaning for the same words. For this reason I set out trying to clarify on what most people and the literature agrees too. If you give an answer to this question I would be very happy if you could provide a reference to literature.

For one person an aggregate is the boundary that groups a collection of entities. It is more a conceptional clustering boundary.

For another person an aggregate is a collection of entities transfered from a database repository (having transitional consistency). So an aggregate is something real and not just a concept. If I for example load two users from a database then I have loaded two aggregates of the same aggregate type.

Another person that also thinks that a collection of entities that are transactional consent but thinks that if you load data of a given aggregate type you can also load it partially (with some data just null for example) and still call the whole thing one aggregate while others would see this as two aggregates (with eventual consistency, meaning the consistency is given after both aggregates are saved).

To find the true meaning of the word aggregate myself I have had a look at the definition of Martin Fowler. Here an aggregate is something real and there can be two aggregates of the same aggregate type. But when reading something like this article from Vaughn Vernon I get the impression that he calls aggregate what according to the 'Martin Folwer like interpreted understanding' should be called aggregate type.


问:
Why does inner class have to specify Outer.this.remove(int)?
Why does an inner class sometimes have to explicitly specify the outer class instance in order to call an outer class method for which there is no matching method in the inner class?

Example:

```<code>import java.util.Iterator;

public class Outer {
    void remove(int index) {}

    private class Inner implements Iterator {
        @Override
        public boolean hasNext() {
            return false;
        }

        @Override
        public Object next() {
            return null;
        }

        @Override
        public void remove() {
            remove(0); // error: remove() in Inner cannot be applied to (int)
            Outer.this.remove(0); // ok
        }
    }
}
</code>```

My original, failed attempt at an example shows that this disambiguation is not generally required:

```<code>public class Outer {
  private Object field;

  void method() {}

  private class Inner {
    void innerMethod() {
      if(field == null) {
        method(); // ok
        Outer.this.method(); // ok
      }
    }
  }
}
</code>```

答: The entire premise of the question is wrong. If you remove the Outer.this it will compile as normal. You don't have to qualify method access if there is no ambiguity. The question you linked asked specifically about what to do if both the inner and outer class have a method with the same signature and how to decide which method to call (it then gives the inner by default, outer by explicit qualification)

ContentLicense: CC BY-SA 3.0


问:
Anemic domain models and domain services injection
The anemic domain model is described as an anti-pattern in domain driven design by Martin Fowler. To have business logic on the domain models often domain services are used. But injecting domain services into domain models is considered harmful by Vaughn Vernon (see "Implementing Domain-Driven Design, Page 387).

In my opinion those opinions are contradictory, is this true? How can both points be considered?

Is it really rich domain model with domain services injected vs. anemic domain model and normal domain services?

答:
It's not contradictory. Both proponents would like you to put your actual code in the domain object itself.

ie.

```<code>public class Order
{
    private string status = "not bought";
    public void Buy()
    {
        this.status = "bought";
    }
}
</code>```

vs ADM

```<code>public class Order
{
    public string Status = "not bought";
}

public class BuyingService
{
    public Order Buy(Order order)
    {
         Order o = new Order();
         o.status = "bought";
         return o;
    }
}
</code>```

vs injected services

```<code>public class Order
{
    public Order(IBuyingService bs)
    {
        _bs = bs;
    }
    private IbuyingService _bs;
    private string status = "not bought";
    public void Buy()
    {
        this.status = _bs.Buy();
    }
}

public class BuyingService : IBuyingService
{
    public string Buy()
    {
         return = "bought";
    }
}
</code>```

Frankly though each approach has pluses and minuses. The one you choose is largely a matter of personal preference

Body:
It's not contradictory. Both proponents would like you to put your actual code in the domain object itself.

ie.

public class Order
{
    private string status = "not bought";
    public void Buy()
    {
        this.status = "bought";
    }
}

vs ADM

public class Order
{
    public string Status = "not bought";
}

public class BuyingService
{
    public Order Buy(Order order)
    {
         Order o = new Order();
         o.status = "bought";
         return o;
    }
}

vs injected services

public class Order
{
    public Order(IBuyingService bs)
    {
        _bs = bs;
    }
    private IbuyingService _bs;
    private string status = "not bought";
    public void Buy()
    {
        this.status = _bs.Buy();
    }
}

public class BuyingService : IBuyingService
{
    public string Buy()
    {
         return = "bought";
    }
}

Frankly though each approach has pluses and minuses. The one you choose is largely a matter of personal preference


问:
How to refer to ByRef and ByVal in a dropdown label?
The MSDN page on ByRef and ByVal keywords isn't very helpful; unless I somehow skipped it, they're simply being referred to as "keywords" everywhere.

One of the main contributors of the Rubberduck project is working on a very cool Encapsulate Field refactoring, and the UI is coming along pretty nicely.. except I have a problem with the label above the dropdown for ByRef/ByVal, which says "Accessibility":

I don't like "Accessibility" because I'm using it elsewhere for Public/Private/Friend access modifiers where it feels more accurate.

I don't want to use "Modifier" because IMO it's just a short for "access modifier".

I'd like that label to be accurate, but my vocabulary is apparently lacking and I don't know what to call these keywords.

What should this label say, to be accurate? What's the word I'm looking for? What "family of keywords" do ByRef/ByVal belong to?

答:
The most exact and formal term for this would be "Aliasing semantics".

When ByRef is used, the name inside the function is an alias for the caller's variable -- all changes to either one are immediately visible to the other.  With ByVal, the name inside the function is a distinct copy of the caller's variable (of course, both the caller's and function's copy may refer to the same object, but they are distinct in that reassigning the parameter inside the function does not reassign the caller's variable).

The options would be

Alias (ByRef)

Copy (ByVal)

Some platforms add a third possibility, where aliasing the caller's variable is done but it is not allowed for more than one parameter to alias overlapping objects.  (The idea behind C restrict keyword, one also finds this in IDL, where the attribute keyword is unique).  .NET doesn't have a good way to encode this knowledge.


问:
Confusion about the meaning of the word aggregate in domain driven design
In a discussion about domain driven design I have learned the different people seem to think of different things when using the word aggregate. The main difficulty is that some people use the word aggregate for what other people call aggregate type.

It is quite difficult to have a discussion if people assume different meaning for the same words. For this reason I set out trying to clarify on what most people and the literature agrees too. If you give an answer to this question I would be very happy if you could provide a reference to literature.

For one person an aggregate is the boundary that groups a collection of entities. It is more a conceptional clustering boundary.

For another person an aggregate is a collection of entities transfered from a database repository (having transitional consistency). So an aggregate is something real and not just a concept. If I for example load two users from a database then I have loaded two aggregates of the same aggregate type.

Another person that also thinks that a collection of entities that are transactional consent but thinks that if you load data of a given aggregate type you can also load it partially (with some data just null for example) and still call the whole thing one aggregate while others would see this as two aggregates (with eventual consistency, meaning the consistency is given after both aggregates are saved).

To find the true meaning of the word aggregate myself I have had a look at the definition of Martin Fowler. Here an aggregate is something real and there can be two aggregates of the same aggregate type. But when reading something like this article from Vaughn Vernon I get the impression that he calls aggregate what according to the 'Martin Folwer like interpreted understanding' should be called aggregate type.

答:
It looks to me like Vaughn is struggling with the practical problems of monolithic aggregate roots in 'line of business' style software.

Where as Martin likes monolithic OOP software, which works well when you can fit your whole process into memory.

I don't think there is a contradiction between the two though. You have to choose where you split your domain objects into contexts and aggregates in DDD. On one hand you want to have aggregate roots which encompass an entire real life process, on the other you have practical difficulties if these get too big, so you may have to split them out a bit smaller and join them up with domain events or other trickery


问:
Should development teams switch projects at the end of every deadline (sprint)?
At my current position, it's common for teams to completely switch projects and hand-off their tasks to another team even if there is no valid reason, such as the other team having more experience with the project.

The argument to this is that it keeps teams well aware of the entire ecosystem and adds redundancy. For instance, if someone goes on vacation there are now more candidates available to tackle the project.

Is this an acceptable approach to software development? To make the question less vague, I have certain specific questions:

What are the correct situations where it is acceptable for to teams alternate projects?

What are the pros and cons of having a specialized team devoted to one area?

What are the pros and cons of having all team members learn different parts of the system?

I'm of the opinion that this is incorrect, because that means that there is less quality work and more downtime while team members relearn their respective projects. Thoughts?

答:
I don't want to call you naïve, but there is no should in software development. If you consult and travel as much as I have, you've seen a lot -- some of it absolutely mind-boggling. I wouldn't be surprised to stumble on a development shop where participants defend their ideas by fighting each other with sharp sticks, wearing diapers.

Regarding particulars,

Pros for switching:

A more well-rounded developer

Interchangeability

Wide-area view

Increased engagement because devs don't get bored

Pros for specialization:

Deep knowledge

Faster development in the specialized area

For cons, just flip the pros around.

Regarding quality, I've seen high quality code from both approaches. That's more a result of your team's dedication to quality than it is a side-effect of specialization.


问:
Why would you document a return type using scaladoc?
The following is snippet of an example from page 240 of the book Programming Scala (Wampler & Payne, 2009; O'Reilly Media):

```<code>/** @return Parser[Money] */
def deductItem = deductKind ~> deductAmount
</code>```

Is there any reason to do this instead of just specifying the return type with an actual type annotation, as below?

```<code>def deductItem: Parser[Money] = deductKind ~> deductAmount
</code>```

答:
Sometimes in Scala, you break from the normal syntax to make something that looks like a DSL.  Parser combinators are one of those areas.  Putting the type annotation would break the DSL illusion of looking grammar-like.  Some development teams care about that more than others.  Some development teams care about the type annotation more.

I would prefer to omit the comment too.  However, when explaining it to others, such as in a textbook, it's occasionally useful to show the type.

Note that this is definitely a special case.  Your type checker works best for you when you put explicit return type annotations for all your functions, and that's the recommended practice in most cases.  Of course, if you're like me and tend to forget exactly how parser combinators work when you don't use them for a while, you can "cheat" by putting in the types at first, then remove them later to make it look pretty.


问:
Customer Authentication in a website
Just to be clear, by authentication I don't mean user-authentication, but I want to make sure that my app is running on the customer's server and in a defined time-span.

Some of our customers use our web apps in their Intranet and on their own servers, on the other hand some of them use Hosting services and they don't own any server machine.

With that said, I'm looking for ways to make sure about customer's Identity. I don't want them to be able to xcopy the app, also I'd like to have some kind of time-expiration limit.

In traditional desktop apps we could use USB security tokens, but their not usable with hosting providers.

It seems that we have to make a central authentication server. I'm a little confused about possible options, so any suggestion about where to start is welcome.

答:
After much research, I opt to use Portable Licensing. It's very easy to use, and yet provides the basic and secure infrastructure you need to build your licensing system.

With Portable Licensing you need to:

Create a key pair based on a passphrase.

Generate licenses with your private key and store necessary information into it.

Distribute public key and license key to the customer.

You app will verify license's signature with the public key and then you can be sure that licensing information are intact and valid.

Title: Customer Authentication in a website


问:
BigData: time-based word count

What we are trying to do:

We're trying to build a system that will count the number of unique entries for a certain timeframe. It's working ok until the data grows up or the timeframe increase, then we get some OOM Exception or the response it's just too slow.

To simplify it's more or less the classic word-count but with timeframes.

```<code># timestamp - userId - count
111111 - 12345 - 1
222222 - 67890 - 1
333333 - 67890 - 1
444444 - 12345 - 1
555555 - 12345 - 1
</code>```

If the user asks for the "top" beetween (100000,400000) the answer should be "67890 - 2", otherwise if he asks for the "top" between (100000,600000) the answer should be "12345 - 3".

We are in the order of millions of entries (from 1 to 10, more or less).

What we did:

Right now we are storing the data on MongoDB, divided by hours.
Getting the documents (that are quite big) it's pretty slow, about a minute to get 168 documents for a week. We tried Redis to speed up the things a bit but we're still out of our target.

What I tried:

To experiment a bit I wrote a text file with a couple of millions of entries (around 50mb) and I've tried simply to read and count from it, filtering by the timestamp. It's seems to be "incredibly" faster, around 2s to go through all the entries.

The drawback is that, also for small timeframes we should analyze all the file. To solve this we can think to split the files daily.

I've also tried Spark but for such small things seems overkilling and slower.

Anyway, it seems strange to me that the fastest way to do this is to read a text file! Is there any design,framework that I am missing?

Disclaimer: I'm not sure if I've exposed the problem clearly enough or if it suited for this site, but I'm losing sleep since 3 weeks struggling with this and this seems to be one of my last shots.

答:
"Is there any design,framework that I am missing?"

Use a relational database.

Document and object databases (MongoDB among them) are great when your data is "chunky". That is, they excel if you intend to fetch data in a particular shape -- grab an entire order with its line items, grab a user with their preferences, grab a class with its students (or a student with their classes).

Key/value stores are screaming fast when you always fetch by key.

Trouble is, you're not using either of these strategies. The shape of your data depends completely on what a user asks for. There's no shortcut to the data; it's simply not available. Given that, you should crush your text file performance with a relational database. If you don't, you're doing something wrong. Make sure you understand indexes and partitioning. (That's where a text file falls apart. Don't use a text file as a database, please.) If you don't, hire someone who does.

As I'm typing this, I realize I may be leading you astray. Specifically, it's entirely possible to be successful with MongoDB. You mention that you're storing word counts by hour. That must not be an efficient assumption given the amount of time and memory it takes to complete a query. With the right expertise, you could create an effective MongoDB model. If you don't have the expertise, get it.

Until then...

Use a relational database.

Title: BigData: time-based word count


问:
Altering the contents of a Collection outside the scope of an instance method?
Is it best practices to never alter the contents of a Collection that is passed as a parameter?

I want orgSet to only have words. But, sometimes there are one char strings (like question marks, commas, etc.) that I want to remove from the set of words. These are not the full methods, but it makes my point:

```<code> public static Set<String> removeSyntax_Foo(Set<String> orgSet) {
        Set<String> tmpSet = new HashSet();
        for(String s : orgSet) {
            if(s.length()!=1) { tmpSet.add(s); }
            if(Character.UnicodeBlock.of(s.charAt(0)) == Character.UnicodeBlock.GENERAL_PUNCTUATION) { continue; }
            tmpSet.add(s);
        }
        return tmpSet;
    }

    public static void removeSyntax_Bar(Set<String> orgSet) {
        Set<String> tmpSet = new HashSet();
        tmpSet.addAll(orgSet);
        orgSet.clear();

        for(String s : tmpSet) {
            if(s.length()!=1) { orgSet.add(s); }
            if(Character.UnicodeBlock.of(s.charAt(0)) == Character.UnicodeBlock.GENERAL_PUNCTUATION) { continue; }
            orgSet.add(s);
        }
    }
</code>```

removeSyntax_Foo() has the potential for a careless memory leak. I actually have a list of static methods I use to clean-up my Set of words. If each of those methods creates a new collection... But, I feel this is the correct solution to use.

removeSyntax_Bar() jumbles the contents of the invoker's Set which might be a huge surprise to the invoker. You are not suppose to do that, right?

Is removeSyntax_Foo() or removeSyntax_Bar() best practices?

答:
The answer is mostly six of one, half a dozen of the other.

For my simple need of cleansing html mark-up, numbers, syntax, etc. out of a tokenized doc, removeSyntax_bar() makes sense; those are simple utility methods. But, for interface design intended for public consumption, removeSyntax_foo() is what you're suppose to do.


问:
Why shouldn't I use the repository pattern with Entity Framework?
During a job interview, I was asked to explain why the repository pattern isn't a good pattern to work with ORMs like Entity Framework. Why is this the case?</p>

答:
Its due to Migrations:It is not possible to get migrations to work , as the connection string resides in the web.config. But, the DbContext resides in the Repository layer . IDbContextFactory  needs to have configuration string to the database .But There is no way that migrations gets the connection string from web.config.

There are work around but I have not found a clean solution for this yet!

OwnerDisplayName: StringBuilder


答: The _Foo() variant, treating the input as read-only, is more thread-safe.  For example, a parallel thread could do something else with origSet (again, in a read-only manner) while your code is trimming punctuation.  The _Foo() variant will cause fewer surprises and probably less bugs.  And, it is more flexible for future requirements.  For example, somebody adds a requirement to create a set of the punctuation.  Possible with the _Bar() version, but much easier with_Foo()

Title: Altering the contents of a Collection outside the scope of an instance method?

Body:
Is it best practices to never alter the contents of a Collection that is passed as a parameter?

I want orgSet to only have words. But, sometimes there are one char strings (like question marks, commas, etc.) that I want to remove from the set of words. These are not the full methods, but it makes my point:

```<code> public static Set<String> removeSyntax_Foo(Set<String> orgSet) {
        Set<String> tmpSet = new HashSet();
        for(String s : orgSet) {
            if(s.length()!=1) { tmpSet.add(s); }
            if(Character.UnicodeBlock.of(s.charAt(0)) == Character.UnicodeBlock.GENERAL_PUNCTUATION) { continue; }
            tmpSet.add(s);
        }
        return tmpSet;
    }

    public static void removeSyntax_Bar(Set<String> orgSet) {
        Set<String> tmpSet = new HashSet();
        tmpSet.addAll(orgSet);
        orgSet.clear();

        for(String s : tmpSet) {
            if(s.length()!=1) { orgSet.add(s); }
            if(Character.UnicodeBlock.of(s.charAt(0)) == Character.UnicodeBlock.GENERAL_PUNCTUATION) { continue; }
            orgSet.add(s);
        }
    }
</code>```

removeSyntax_Foo() has the potential for a careless memory leak. I actually have a list of static methods I use to clean-up my Set of words. If each of those methods creates a new collection... But, I feel this is the correct solution to use.

removeSyntax_Bar() jumbles the contents of the invoker's Set which might be a huge surprise to the invoker. You are not suppose to do that, right?

Is removeSyntax_Foo() or removeSyntax_Bar() best practices?


问:
Writing R packages to replace .R scripts?
In our company we have a handful of R users who have collectively written some ~30 .R scripts over the last year.  The scripts are mostly 100 lines or less, defining useful and reusable functions.

Currently everyone's .Rprofile contains some code that sources all of the files in a shared 'Common R Scripts' directory on startup.

How would we benefit from writing R packages to replace these scripts:

Now?

In a year's time, when we have ~60 scripts?

答:
The introduction to the R Packages book explains the benefits pretty well:

In R, the fundamental unit of shareable code is the package. A package bundles together code, data, documentation, and tests, and is easy to share with others. As of January 2015, there were over 6,000 packages available on the Comprehensive R Archive Network, or CRAN, the public clearing house for R packages. This huge variety of packages is one of the reasons that R is so successful: the chances are that someone has already solved a problem that you’re working on, and you can benefit from their work by downloading their package.

Why write a package? One compelling reason is that you have code that you want to share with others. Bundling your code into a package makes it easy for other people to use it, because like you, they already know how to use packages. If your code is in a package, any R user can easily download it, install it and learn how to use it.

But packages are useful even if you never share your code. As Hilary Parker says in her introduction to packages: “Seriously, it doesn’t have to be about sharing your code (although that is an added benefit!). It is about saving yourself time.” Organising code in a package makes your life easier because packages come with conventions. For example, you put R code in R/, you put tests in tests/ and you put data in data/. These conventions are helpful because:

They save you time — you don’t need to think about the best way to organise a project, you can just follow a template.

Standardised conventions lead to standardised tools — if you buy into R’s package conventions, you get many tools for free.

It’s even possible to use packages to structure your data analyses, as Robert M Flight discusses in a series of blog posts.


答:
I think your question is not really specific to R, the same issue often arises when a group of teammates has some code to share amongst them, written in whatever programming language they use. With a growing amount of code, they reach the point where they have to consider if they just keep sharing it by loosely throwing it together into a common folder, or if they are going to use a more rigid standard packaging or library mechanism of the language (at least, for parts of the code base).

The answer to this question is: "it depends". Using standard packaging mechanisms has several benefits concerning

they provide a standard for versioning and dependency management

they provide standard for documentation and API description

you shift dependencies from the "per function" level to the "package level", which reduces the number of dependencies heavily and makes them more manageable

the mechanism may provide other standards like how to structure the code, the tests, the documentation, etc.

Ideally, this should make it easier for the team to reuse the code.

On the other hand, you never get this for free. When you start building packages, you need to introduce a maintainer for each package, someone who is collecting the source code for the package (and if necessary, makes some editorial changes), who decides what goes in there or what not, who assigns a version number to the package, and who knows the technical side of the package mechanism in-depth. The package code will probably need to fulfill a higher formal level of quality than unpackaged code (for example, additional docs and tests).

So, if you want to know if your team already reached the point where the benefits outweigh the extra effort, you cannot simply decide this by comparing "30" vs. "60" scripts. It depends on factors how many people are involved in your team in writing and providing scripts, how many reuse them, how often do changes occur, do people in your team have problems finding existing code for reuse, problems to understand how to reuse a specific function, problems on resolving dependencies, and so on?

So if your team does not have any problems with the current approach, don't do anything for now. If, however, you see at least some of the problems, but are unsure if packaging will solve them, I suggest to simply try it out. Put some of the current code, most heavily reused code into a package, publish it in your team and see if the benefits are worth the overhead for your team.

Title: Writing R packages to replace .R scripts?

Body:
In our company we have a handful of R users who have collectively written some ~30 .R scripts over the last year.  The scripts are mostly 100 lines or less, defining useful and reusable functions.

Currently everyone's .Rprofile contains some code that sources all of the files in a shared 'Common R Scripts' directory on startup.

How would we benefit from writing R packages to replace these scripts:

Now?

In a year's time, when we have ~60 scripts?


问:
When should interface be owned by client?
In Agile Software Development: Principles, Patterns, and Practices, Uncle Bob talks about client owning the service interface.

My questions are :

Should client always own the interface or only when the client changes less often i.e. at higher level of abstraction than classes which implement the interface?

Is there any scenario where the client should own the interface although it is at lower level of abstraction than the implementing classes.

Edit: Client owning the interface means, it will specify the interface and not the implementers of the interface. Implementers of the interface own the interface in the case of utility libraries.

答:
First, lets clarify what we mean when we say "interface is owned by client". It means that interface is defined by what client of the interface needs and not by what implementer provides. If we were to create a modules of the trio of client, interface and implementer, then first module would be client and interface and second would be implementer, with second module depending on the first one. This goes nicely along Dependency Inversion principles and Interface segregation principles.

That said, I believe, that "interface is owned by client" is the default position in good design. The question should be "Does it make sense for interface to be defined by implementer". For myself, the question is no. There are multiple reasons for that.

First, lets look at GoF design patterns :

Here, it is quite obvious, that every interface is not defined by the implementer, but by the client. Every pattern allows for arbitrary number and types of implementers. But if client changes, so does the interface. That means the interface and client are more closely conceptually related than interface and implementer.

Second is already mentioned Interface Segregation principle. That says "Client shouldn't depend on interface it doesn't need." This can be paraphrased as "Interface is defined by what client needs." This is quite clear.

Third is the very logic behind interface being defined by implementer. If interface is defined by implementer, it becomes very easy to leak that specific implementer's API. That will make it hard to provide different implementations for the interface. It is quite common sight to see just single implementer for an interface if that interface is defined by that implementer. What is then point in that?

To sum it up : In good, modular and understandable design interfaces (and other abstraction) are first and foremost defined by needs of the clients and are thus part of them. It is a code smell if interface is defined by what implementer provides.


问:
What is the conceptual difference between finally and a destructor?
First, I am well aware of Why is there no 'finally' construct in C++? but a lengthy-growing comment discussion on another question seems to warrant a separate question.

Apart from the issue that finally in C# and Java can basically exist only once (== 1) per scope and a single scope can have multiple (== n) C++ destructors, I think that they are essentially the same thing. (With some technical differences.)

However, another user argued:

... I was trying to say that a dtor is inherently a tool for (Release sematics) and
finally is inherently a tool for (Commit semantics). If you don't see why: consider
why it's legitimate to throw exceptions on top of each other in
finally blocks, and why the same is not for destructors. (In some
sense, it's a data vs. control thing. Destructors are for releasing
data, finally is for releasing control. They are different; it's
unfortunate that C++ ties them together.)

Can someone clear this up?

答:
Transaction (try)

Error Output/Response (catch)

External Error (throw)

Programmer Error (assert)

Rollback (closest thing might be scope guards in languages that support them natively)

Releasing Resources (destructors)

Misc Transaction-Independent Control Flow (finally)

Can't come up with a better description for finally than misc transaction-independent control flow. It doesn't necessarily map so directly to any high-level concept in the context of a transaction and error recovery mindset, especially in a theoretical language that has both destructors and finally.

What's most inherently lacking to me is a language feature that directly represents the concept of rolling back external side effects. Scope guards in languages like D are the closest thing I can think of that comes close to representing that concept. From a control flow standpoint, a rollback in a particular function's scope would need to distinguish an exceptional path from a regular one, while simultaneously automating the rollback implicitly of any side effects caused by the function should the transaction fail, but not when the transaction succeeds. That's easy enough to do with destructors if we, say, set a boolean to value like succeeded to true at the end of our try block to prevent the rollback logic in a destructor. But it's a rather roundabout way to do this.

While that might seem like it wouldn't save so much, side effect reversal is one of the hardest things to get right (ex: what makes it so difficult to write an exception-safe generic container).


问:
Object with Customized Properties and Methods
A project I am working on currently models Order information. Right now, there is one class with a bunch of properties and functions that all of orders have in common. In addition, some of our users have customized properties and/or functions on top of the base order. Some of those customized properties are shared between multiple users and some are unique to a given user. The class has nearly 50 different properties, but a given user might only be using 20 or so of those properties.

I'd like to redesign it so that the base properties/functions are separate from the customized properties/functions, but I don't know how to approach this. I thought about inheriting the base class, but a user might have 3 or 4 different customized properties. There is no clear inheritance among the customized properties. I looked into the decorator pattern, but the interface is changing, so that doesn't seem to fit.

Is there any way to accomplish this without having the monolithic class?

Examples:

```<code>Base Properties - OrderID, OrderDate, AccountId, etc.
Customized Properties - BackOrdered, PONumber, ContactPerson
Base Functions - PlaceOrder, CancelOrder
Customized Functions - AddContact, DiscountPriceByPercent
</code>```

So, some users might only have the base, one user might have the base + BackOrdered, and another user might have base + BackOrdered + PONumber.

This problem isn't unique to orders, I have the same problem with other objects in the project. I'm looking more for an architecture/pattern to solve the general case than for a way to handle orders.

答:
If all of the custom properties are known at compile time, but they can be combined in different ways and you don't want to produce large hierarchy of classes, then tou can use Mixed pattern, which implementation will depend on the programming language you use. Code example on Java:

```<code>interface Mixed {
    <M, I extends M> void extend(Class<M> iface, I impl);
    <M> M as(Class<M> iface);
}
class MyObject implements Mixed {
     String getP1();
     LocalDate getP2();
}
class CustomFeature1 {
      String getA1();
      String getB1();
}
class CustomFeature2 {
      String getA2();
      String getB2();
}

// O will have properties P1,P2,A1,A2,B1 and B2
MyObject o = new MyObject();
o.extend(CustomFeature1.class, new CustomFeature1());
o.extend(customFeature2.class, new CustomFeature2());
o.as(CustomFeature1.class).getCustomPropertyA1();
</code>```

If custom properties are defined at runtime, probably, it's time to think about runtime data structures defined by a metamodel:

```<code>interface Property {
    String getName();
    Class<?> getValueType();
    Object getValueFor(Object object);
}
interface Model {
     addProperty(String name, Class<?> valueType);
     List<Property> getProperties();
}
interface DynamicObject {
     Model getModel();
     Object getValue(String propertyName);
     void setValue(String propertyName, Object value);
}
class MyObject implements DynamicObject {
     String getP1();
     String getP2();
}

MyObject o = new MyObject();
// add new custom property
o.getModel().addProperty("A1", String.class);
// set custom property value
o.setValue("A1", "Lorem Ipsum");

// Let's list all custom properties and their values
for (Property property : o.getModel().getProperties()) {
     System.out.println(property.getName() + "=" + property.getValueFor(o));
}
</code>```

In both solutions you'll need to implement custom persistence mechanism to store the data in database or to serialize in XML or JSON. You'll need to use reflection for that.

Body:
If all of the custom properties are known at compile time, but they can be combined in different ways and you don't want to produce large hierarchy of classes, then tou can use Mixed pattern, which implementation will depend on the programming language you use. Code example on Java:

interface Mixed {
    <M, I extends M> void extend(Class<M> iface, I impl);
    <M> M as(Class<M> iface);
}
class MyObject implements Mixed {
     String getP1();
     LocalDate getP2();
}
class CustomFeature1 {
      String getA1();
      String getB1();
}
class CustomFeature2 {
      String getA2();
      String getB2();
}

// O will have properties P1,P2,A1,A2,B1 and B2
MyObject o = new MyObject();
o.extend(CustomFeature1.class, new CustomFeature1());
o.extend(customFeature2.class, new CustomFeature2());
o.as(CustomFeature1.class).getCustomPropertyA1();

If custom properties are defined at runtime, probably, it's time to think about runtime data structures defined by a metamodel:

interface Property {
    String getName();
    Class<?> getValueType();
    Object getValueFor(Object object);
}
interface Model {
     addProperty(String name, Class<?> valueType);
     List<Property> getProperties();
}
interface DynamicObject {
     Model getModel();
     Object getValue(String propertyName);
     void setValue(String propertyName, Object value);
}
class MyObject implements DynamicObject {
     String getP1();
     String getP2();
}

MyObject o = new MyObject();
// add new custom property
o.getModel().addProperty("A1", String.class);
// set custom property value
o.setValue("A1", "Lorem Ipsum");

// Let's list all custom properties and their values
for (Property property : o.getModel().getProperties()) {
     System.out.println(property.getName() + "=" + property.getValueFor(o));
}

In both solutions you'll need to implement custom persistence mechanism to store the data in database or to serialize in XML or JSON. You'll need to use reflection for that.


问:
Design Pattern for Library Wrapping Extern Methods
I am working to create a C# library that wraps a  C DLL to integrate with our test system. The C DLL has probably close to 100 functions that can be accessed and all from the same DLL. I don't need all functions wrapped at this time, but I want to ensure I am setup in a direction that makes implementing everything maintainable.

The DLL 'groups' many of its functions under different purposes to help create separation. My plan was to create a class that is the main access point that contains generic functions and then create separate classes that create extension methods for the generic class.

Lets say my 'groups' are:

Generic

Acquisition

Selection

Interaction

Utilities

I would then create my main class

```<code>public class BaseClass
{
    // Generic methods
}
</code>```

Then the other groups would each be their own static extension class:

```<code>public static class AcquisitionClassExtensions
{
    public static int AcquisitionMethod1(this BaseClass b)
    {
        // Access DLL
    }
}
</code>```

And continue for the other groups. This would let me keep the BaseClass as the main object class that the DLL would be interacted with.

The user would still see a huge list of methods when viewing intellisense, but from a project maintainability I can keep things separate. I am sure i would run in to problems if one of the extension methods ends of needing some sort of state tracked, but that is minimal.

Is there a better way i could approach this or am i worrying about nothing?

Clarity Edit:

The generic group or BaseClass contains the basic connection access to the hardware system that the DLL is for, and that would maintain state. The other groups are special operations that can be performed on the hardware. The goal being if a new set of functionality is added it can be added with the extension methods like the other groupings.

答:
I suppose that when you are speaking of adding extension methods, you are thinking of enriching the functionality of the C library.  I would advise against that, because a collection of 100 methods is not an object-oriented interface, and as such it will most probably not be amenable to extension.

Now, the concept of object-oriented programming is not unknown to C programmers; in fact, many, if not most, systems written in C do have some concept of objects, they just do it in their own way which might not be readily recognizable. For example:

<stdio.h> files are, in a sense, an object-oriented construct.  The object in this case is a struct called FILE.

<fcntl.h> files are, in a sense, an object-oriented construct.  The object in this case is hidden behind an int handle.

In the Windows API there is a multitude of objects, also hidden behind various different types of handles, the most famous of which is HWND.

I do not know whether the C library that you are using has any kind of object-oriented notion like the above, but many chances are that it does.  If it does not, then I guess there is nothing special you can do, proceed the way you were planning.  But if it does, then the design pattern that you probably need here is The Wrapper.

So, what you should do, if possible, is detect what object-oriented entities are utilized by your library, and introduce a C# class for each one of them.  If you were creating a wrapper for <fcntl.h>, you would be creating a class File which contains a single member, private readonly int handle and offers a bunch of methods that delegate to the native functions like read(), write(), etc. passing them the int handle contained within the object.

Then, you would enrich those classes with additional functionality, (either by inheritance or by composition,) instead of extending the native-interfacing class.  The best thing to do with the native-interfacing class is to keep it as short as possible, and hidden.  ("internal" to the assembly that contains it.)

For more information, see:

Wikipedia: Wrapper Library

Stackoverflow: What is a wrapper class?


答:
This is an opinion rather than an answer, as I am not and have not been part of the Java development team. But an opinion with JLS references.

I think it is an accident, caused by an unnecessarily over-precise specification. In other words, a de facto bug but de jure intended behavior.

The specification in question is JLS 15.12, Method Invocation Expressions, and in particular JLS 15.12.1, Compile-Time Step 1: Determine Class or Interface to Search:

The first step in processing a method invocation at compile time is to figure out the name of the method to be invoked and which class or interface to search for definitions of methods of that name.

Note that the specification uses the term "name" rather than "signature."

If the Identifier appears in the scope of a visible method declaration with that name (§6.3, §6.4.1), then:
  If there is an enclosing type declaration of which that method is a member, let T be the innermost such type declaration. The class or interface to search is T.

Note the terminology "innermost such type declaration." As I read this, once the declaring type has been selected, then it is the only type that will be searched for methods of the given name.

So, to apply this:

In your original example, you used two different names. The compiler identified that the name was declared in the enclosing class, and there was no need to use disambiguation.

In the linked example, the method signatures are the same. This would require disambiguation even if the spec were different.

In your final example, the method name appears in the inner class, so the compiler looks to that class for resolution. However, since the inner class doesn't define the correct signature, it is unable to resolve the method without disambiguation.

So, there you have behavior. As for reason, unless @BrianGoetz or another  person with personal knowledge decides to answer, we'll all just have to speculate.

Title: Why does inner class have to specify Outer.this.remove(int)?

Body:
Why does an inner class sometimes have to explicitly specify the outer class instance in order to call an outer class method for which there is no matching method in the inner class?

Example:

```<code>import java.util.Iterator;

public class Outer {
    void remove(int index) {}

    private class Inner implements Iterator {
        @Override
        public boolean hasNext() {
            return false;
        }

        @Override
        public Object next() {
            return null;
        }

        @Override
        public void remove() {
            remove(0); // error: remove() in Inner cannot be applied to (int)
            Outer.this.remove(0); // ok
        }
    }
}
</code>```

My original, failed attempt at an example shows that this disambiguation is not generally required:

```<code>public class Outer {
  private Object field;

  void method() {}

  private class Inner {
    void innerMethod() {
      if(field == null) {
        method(); // ok
        Outer.this.method(); // ok
      }
    }
  }
}
</code>```


问:
Single Class to Serve as View Model as well as Container for Submitted Form
I see the following design in the code which is part of the default web application project in visual studio:

A single data model class in constructed and decorated with various data validation annotations. For Example, there's a RegisterViewModel class that looks like this:

```<code>public class RegisterViewModel
{
    [Required]
    [EmailAddress]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 8)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }
}
</code>```

This class then serves two purposes:

It is the 'view model' or the type for the view which consists of the html form with which the user registers. The html details as well as the jquery validation metadata can be automatically extracted from the class's data annotations.

When the user posts his/her form back to the server, the form data is stored in an object of the same type; e.g. in this case the Register action signature looks like this:

public async Task<ActionResult> Register(RegisterViewModel model)

Among other things, this allows for server-side validation to happen using the same data annotations.

Is this a common, acceptable pattern? Is it a design to strive for when building my own forms?

答:
The ViewModel that you show is a model that is intended to be used with a view. As such, it has facilities for helping to display the data and facilities for helping to receive the data.

In very small applications, you could consider using that data structure as your primary data model.

However, in serious applications, you wouldn't model your data that way. Among other things, you should have only one password stored in your repository, and, more importantly, you would store passwords separately from user specific data and it must be encrypted. In other words, the ViewModel is a representation of your underlying business model for the purposes of interacting with the user, and not the same as your business model.


问:
Do reactive extensions and ETL go together?
I don't fully understand reactive extensions, but my inital reading caused me think about the ETL code I have.

Right now its basically a workflow to to perform various operations in a certain sequence based on conditions it find as it progresses.

I can also imagine an event driven way such that only a small amount of imperative logic causes a chain reaction to occur.

Of course I don't need a new type of programming model to make an event driven collaboration like that.

Just the same I am wondering if ETL is a good fit for potentially exploring Rx further.

Is my connection in a valid direction even? If not, could you briefly correct the error in my logic?

答:
They seem very related to me too. We're looking at Rhino ETL (of which that Reactive ETL library mentioned by @shambulator is a re-write), but it feels weird having to work with foreach and yield return all the time.

After having done the initial load from the source to the target database, when doing incremental loads using the same logic, the next step would be using your ETL logic on-the-fly, through queues or events: as new data is entered in your sources (databases, files, queues), it's pushed through the pipeline and inserted in the target database.

Seems an ideal candidate for Reactive programming to me!

Actually, I find it very surprising that the Reactive ETL library isn't at all supported or hardly used (there seems to be no NuGet package), or that there don't seem to be any similar libraries! Did you end up using it eventually (or something similar), and how were your experiences with it?


问:
How many Topics (queues) to practically use in an ESB
In all the Service Bus examples and tutorials I've seen, they cover publishing a single message to a single Topic that is picked up by a single listening Subscriber. Whilst this is good for a simple practical overview, it doesn't really explain how Topics should be used in the real world.

I have a large ecommerce application that spans many subdomains, such as Order, Customer and Product management to name a few, and will be using an ESB to communicate events between these disparate systems. I will be using Pub-Sub via Topics.

Initially I was just using a single Topic per each different message type I was sending, however I could see that this was just going to get unmanageable as the system would just have too many types of messages to send to justify a 1-to-1 Message Type to Topic. e.g. ProductCreate Topic, ProductDelete Topic.

Then I thought that I could use a Topic per aggregate in the system. However because of the multiple bounded contexts in the domain, an aggregate in one system could be different to an aggregate, with the same name, in another system. So this implementation might be quite confusing.

So having a Topic per ubiquitous model seems like a better solution, and this can be based off the Canonical Data Model that is used to transform messages across the service bus. Is this a common approach ? Or is dividing the Topics up per functional concern a better method ?

I can see that there are going to be compromises to whichever implementation I pick, so I'm looking for good tips, historic examples of success and pitfalls to avoid.

答:
We struggled with the very same choice / challenge. Mapping only 1 message type to ASB's topic is just not practical. But making it too generic (e.g. sending strings in message's body, using custom and dynamic serialization everywhere) was not appealing either.

We ended up building a light weight framework on top of ASB. It allows sending and receiving multiple types of messages over the same topic, and all of its subscriptions, while using ASB's native serialization. The trick was to capture the type of the class that is being sent in message's ContentType. Multiple subscription clients (each aware of what type they care about) would be listening on the same topic at the same time. A specific client would only handle messages of its type, and ignore (Abandon) others. Our framework uses reflection behind the scenes to call message handlers - no way around that. But it's abstracted away from the code which relies on it - everything is strongly typed from client's POV. This works both for partitioned and non partitioned topics.

I do not have data yet on how much overhead this approach can introduce, and what it means for high volume messaging systems. We are using ASB from on premise application, where ASB latency is high to begin with. Should know more in a few months after we move to Azure completely.

BTW not 100% sure what you meant by "aggregate" or "canonical data model", but hope this helps.


问:
How to move Python doctest examples into another unit test framework?
Years ago AFAIK the mathematitician and software developer Tim Peters discovered that very often the documentation of APIs tends to get out of date over time during the software live cycle, because the comments documenting the API are often overlooked when features are added or the call signatures of functions or methods change.

To solve this problem he invented the doctest module which introduces somewhat "executable documentation" or "literate testing" (see also: the doctest documentation).

As has already been pointed out elsewhere, putting a huge amount of unit tests into the doc strings of all Python modules, functions, classes and methods would clutter up the API documentation too much.

So I'm looking for an elegant and clever way to move tests cases which used to be doctest examples to some other place where they could still be found by some unit test executing driver.

答:
How to move Python doctest examples into another unit test framework?

Doctests are of the form:

```<code>def testable_func():
    """
    >>> testable_func()
    'foo'
    """
</code>```

And unittests, using the builtin unittest module, are of the form:

```<code>def test_testable_func(self):
    self.assertEquals(testable_func(), 'foo')
</code>```

There's a section in the documentation on reusing old test code that says:

In some cases, the existing tests may have been written using the
  doctest module. If so, doctest provides a DocTestSuite class that can
  automatically build unittest.TestSuite instances from the existing
  doctest-based tests.

But this only runs the doctests as unittests. It does not create a scaffold of pre-written unittest code. If you want to leave your doctests in place, you could use this to run them in conjunction with other unittests.

Keeping the doctests

You can use the preexisting doctests, if you would like to keep them as they are, with the unittest module, (see the documentation), you just need to plop this function where you run your unittests. Of course you'll need to import the module the doctests are in:

```<code>import my_module_with_doctests

def load_tests(loader, tests, ignore):
    tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
    return tests
</code>```

You can omit the my_module_with_doctests argument if the objects or functions with doctests are imported into the test module (this should be cut-and-paste working code, just paste it in the test module):

```<code>def load_tests(loader, tests, ignore):
    tests.addTests(doctest.DocTestSuite())
    return tests
</code>```

Moving the doctests to unittests

But I think, because you're asking about "moving" them, you want to migrate your doctests to be used as unittests.

I would strongly recommend that you do the conversion manually to ensure that your assumptions about the doctests are correct, taking notes about tests you want to add in the future if you think of any, so that you have a one-to-one conversion and can iron out any bugs with minimal changes. You may choose to leave the doctests as helpful documentation on use.

After you are certain you have a successful one-to-one conversion of the tests, then go back to your notes/comments and add further tests.

If you must scaffold:

If you must create a scaffolding (perhaps the time allocated is too small for manual conversion) you can iterate over the objects and/or functions, look at their __doc__ attributes, give them to

```<code>example_list = doctest.DocTestParser().get_examples(a__doc__)
</code>```

And for each example in the list, insert into the assertEquals call each objects' source and want attribute. Such a template might look like this:

```<code>'self.assertEquals({0}, {1})'.format(x.source, x.want)
</code>```

Conclusion:

Going forward, be aware of doctests as a way of providing excellent documentation, but they are no substitute for the scalability of unittests.

ContentLicense: CC BY-SA 4.0

Body:
How to move Python doctest examples into another unit test framework?

Doctests are of the form:

def testable_func():
    """
    >>> testable_func()
    'foo'
    """

And unittests, using the builtin unittest module, are of the form:

def test_testable_func(self):
    self.assertEquals(testable_func(), 'foo')

There's a section in the documentation on reusing old test code that says:

In some cases, the existing tests may have been written using the
  doctest module. If so, doctest provides a DocTestSuite class that can
  automatically build unittest.TestSuite instances from the existing
  doctest-based tests.

But this only runs the doctests as unittests. It does not create a scaffold of pre-written unittest code. If you want to leave your doctests in place, you could use this to run them in conjunction with other unittests.

Keeping the doctests

You can use the preexisting doctests, if you would like to keep them as they are, with the unittest module, (see the documentation), you just need to plop this function where you run your unittests. Of course you'll need to import the module the doctests are in:

import my_module_with_doctests

def load_tests(loader, tests, ignore):
    tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
    return tests

You can omit the my_module_with_doctests argument if the objects or functions with doctests are imported into the test module (this should be cut-and-paste working code, just paste it in the test module):

def load_tests(loader, tests, ignore):
    tests.addTests(doctest.DocTestSuite())
    return tests

Moving the doctests to unittests

But I think, because you're asking about "moving" them, you want to migrate your doctests to be used as unittests.

I would strongly recommend that you do the conversion manually to ensure that your assumptions about the doctests are correct, taking notes about tests you want to add in the future if you think of any, so that you have a one-to-one conversion and can iron out any bugs with minimal changes. You may choose to leave the doctests as helpful documentation on use.

After you are certain you have a successful one-to-one conversion of the tests, then go back to your notes/comments and add further tests.

If you must scaffold:

If you must create a scaffolding (perhaps the time allocated is too small for manual conversion) you can iterate over the objects and/or functions, look at their __doc__ attributes, give them to

example_list = doctest.DocTestParser().get_examples(a__doc__)

And for each example in the list, insert into the assertEquals call each objects' source and want attribute. Such a template might look like this:

'self.assertEquals({0}, {1})'.format(x.source, x.want)

Conclusion:

Going forward, be aware of doctests as a way of providing excellent documentation, but they are no substitute for the scalability of unittests.


问:
Best strategy for reporting progress to the UI - how should the callback happen?
Sometimes the user starts an extended technical operation that takes a while to execute. In these cases, it's usually nice to display some kind of progress bar, along with information about which task is being executed right now.

In order to avoid close-coupling the UI and the logic layers, it's usually best to have the communication occur via some kind of proxy. That is, the back-end should not be manipulating its own UI elements, or even interacting with the intermediary layer directly.

Obviously, there has to be some call-back somewhere to make this work. I've generally implemented it in one of two ways:

Pass a mutable object to the back-end, and have the back-end make changes to it on progress. The object notifies the front-end when a change occurs.

Pass a call-back function of the form void f(ProgressObject) or ProgressObject -> unit that the back-end invokes. In this case, the back-end constructs the ProgressObject and it's completely passive. It must construct a new object every time it wants to report progress, I assume.

What are the drawbacks and advantages of these methods? Is there an agreed-upon best method to use? Are there different circumstances for their use?

Are there completely different techniques of reporting progress that I've overlooked?

答:
This is the difference between a push and pull notification mechanism.

The mutable object (the pull) will need to be repeatably polled by the UI and synchronized if you expect the back-end task to be executed in a background/worker thread.

The callback (the push) will only create work for the UI when something actually changes. Many UI frameworks also have a invokeOnUIThread callable from a worker thread to make a piece of code run on the UI thread so you can actually make the changes without treading in to thread-related hazards. (pun intended)

In general push notifications are preferable because they only make work when work needs to be done.


答: I'm using websockets with AngularJS. When the front end receives a message it displays it in a designated message area which fades to blank after a few seconds. On the back end I just post status messages to a message queue. I only send text, but there's no reason I couldn't send a status object with values like percentage complete or transfer speed.</p>

Title: Best strategy for reporting progress to the UI - how should the callback happen?

Body:
Sometimes the user starts an extended technical operation that takes a while to execute. In these cases, it's usually nice to display some kind of progress bar, along with information about which task is being executed right now.

In order to avoid close-coupling the UI and the logic layers, it's usually best to have the communication occur via some kind of proxy. That is, the back-end should not be manipulating its own UI elements, or even interacting with the intermediary layer directly.

Obviously, there has to be some call-back somewhere to make this work. I've generally implemented it in one of two ways:

Pass a mutable object to the back-end, and have the back-end make changes to it on progress. The object notifies the front-end when a change occurs.

Pass a call-back function of the form void f(ProgressObject) or ProgressObject -> unit that the back-end invokes. In this case, the back-end constructs the ProgressObject and it's completely passive. It must construct a new object every time it wants to report progress, I assume.

What are the drawbacks and advantages of these methods? Is there an agreed-upon best method to use? Are there different circumstances for their use?

Are there completely different techniques of reporting progress that I've overlooked?


问:
Avoiding constructors with many arguments
So I have a factory which creates objects of different classes.
The possible classes are all derived from an abstract ancestor.
The factory has a configuration file (JSON syntax) and decides which class to create, depending on the user's configuration.

To achieve this, the factory uses boost::property_tree for JSON-parsing.
He walks through the ptree and decides which concrete object to create.

However, the product-objects have many fields (attributes).
Depending on the concrete class, the object has about 5-10 attributes, in the future maybe even more.

So I'm not sure how the constructor of the objects should look like.
I can think of two solutions:

1) The product's constructor expects every attribute as a parameter, thus, the constructor will end up with 10+ parameters. This will be ugly and lead to long, unreadable code lines. However, advantage is that the factory can parse the JSON and invoke the constructor with the correct parameters. The product class does not need to know that it has been created due to JSON configuration. It does not need to know there is JSON or configuration involved at all.

2) The product's constructor only expects one argument, the property_tree object. Then it can parse the needed information. If am information in the config is missing or out-of-bounds, each product class can react properly.
The factory does not need to know what arguments are needed by the several products. The factory also does not need to know how to react in case of wrong configuration. And the constructor interface is unified and small.
But, as a disadvantage, the product needs to extract the needed information from the JSON, thus, it knows how it is constructed.

I tend to prefer solution 2).
However, I'm not sure if this is good factory pattern.
It feels somehow wrong letting the product know that it is created with JSON configuration.
On the other side, new products can be introduced very simple.

Any opinions on that?

答:
Option 2 is almost right.

An improved option 2

Create a "front facing" class who's job it is to take that JSON-structure object and pick out the bits and call the factory constructor(s). It takes what the factory makes and gives it to the client.

The factory has absolutely no idea that such a JSON thingy even exists.

The client does not have to know what specific bits the factory needs.

Basically the "front end" is saying to the 2 Bobs: "I deal with the redacted customers so the engineers don't have to! I have people skills!" Poor Tom. If he'd only said "I decouple the client from the construction. This result is a highly cohesive factory"; he might have kept his job.

Too Many Arguments?

Not for the client - front end communication.

Front end - factory? If not 10 parameters then the best you can do is put off unpacking, if not the original JSON thing then some DTO. Is this better than passing the JSON to the factory? Same difference I say.

I would strongly consider passing individual parameters. Stick to the goal of a clean, cohesive factory. Avoid the concerns of @DavidPacker answer.

Mitigating "too many arguments"

Factory or Class constructors

taking only arguments for specific class/object construction.

default parameters

optional parameters

named arguments

Front end argument grouping

Examines, evaluates, validates, sets, etc. argument values guided by the constructor signatures above.


问:
Maintain API vs. using idioms in a port
I'm working on a port from Python to Rust and ran into some code that can't be expressed as naturally in Rust as they can in Python.

One case of this is using default parameters:

```<code>class Foo:
  def __init__(self, a="Hello"):
    self._a = a
</code>```

In Rust, you might implement this using a builder:

```<code>struct FooBuilder {
  a: &'static str,
}

struct Foo {
  _a: &'static str
}

impl FooBuilder {
  fn new() -> FooBuilder {
    FooBuilder {
      a: "Hello",
    }
  }

  fn change_a(self, new_a: &'static str) -> FooBuilder {
    FooBuilder {
      a: new_a,
      ..self
    }
  }

  fn build(self) -> Foo {
    Foo {
      _a: self.a,
    }
  }
}
</code>```

To use the class in Python, it's simply:

```<code>foo = Foo("Hello, World!")
</code>```

However, in Rust, you would need to write something like:

```<code>let foo = FooBuilder::new().change_a("Hello, World!").build();
</code>```

This leads to the question: is it better to maintain an API for a port, or is it better to use idioms of the porting language? Does it depend on how well-known the API is to begin with?

答:
You want your ideas expressed clearly in the language that hosts them. That means using host language idioms.

Take the popular Underscore library: js and lua. The lua port is functionally equivalent for the most part. But when it's appropriate, implementations are slightly different. For example:

```<code>_.toArray()
</code>```

becomes

```<code>_.to_array()
</code>```

This change makes the function name feel more native to Lua programmers.

Likewise, _.each() requires an object, array, or something array-like in JavaScript, but _.each() in Lua can also take an iterator -- a mechanism that wasn't available in JavaScript when the original Underscore library was created.

The Lua author sensibly translated what the original author would have intended if they had written it in Lua. That's the key. Ask yourself about the original intent and then implement that intent in your language of choice -- idioms and all. Depending on the source and target language, this can mean adding, editing, or removing features.

Remember that cross-language users will be rare. Most users will use one language or the other. For them, the differences don't matter. If someone uses both, they're probably sophisticated enough to appreciate your translation. It's no different than translating spoken languages. Some ideas aren't directly translatable. The best translators stick to the intent of the original, not a doomed word-for-word literal translation.

Title: Maintain API vs. using idioms in a port

Body:
You want your ideas expressed clearly in the language that hosts them. That means using host language idioms.

Take the popular Underscore library: js and lua. The lua port is functionally equivalent for the most part. But when it's appropriate, implementations are slightly different. For example:

_.toArray()

becomes

_.to_array()

This change makes the function name feel more native to Lua programmers.

Likewise, _.each() requires an object, array, or something array-like in JavaScript, but _.each() in Lua can also take an iterator -- a mechanism that wasn't available in JavaScript when the original Underscore library was created.

The Lua author sensibly translated what the original author would have intended if they had written it in Lua. That's the key. Ask yourself about the original intent and then implement that intent in your language of choice -- idioms and all. Depending on the source and target language, this can mean adding, editing, or removing features.

Remember that cross-language users will be rare. Most users will use one language or the other. For them, the differences don't matter. If someone uses both, they're probably sophisticated enough to appreciate your translation. It's no different than translating spoken languages. Some ideas aren't directly translatable. The best translators stick to the intent of the original, not a doomed word-for-word literal translation.


问:
Acceptance testing with preloaded data or filling it on the go
We're figuring out whether we should write acceptance tests that revolves around preloaded data on a database file, or programmatically added needed data per test, or filling database while testing other application features.

This is a more detailed, easy use case: you want to acceptance test (or UI-test) adding a Book to the system. But in order to do that, you need to have Category rows in the database already, so you can assign one to the book. As you're writing your test case for adding a book, you:

Use a previously seeded database file that has already categories in it.

cons would be you need to keep that file up with every change in the code, with the latests changes on the system, AND you'd need to fill it while considering additional business logic (i.e. maybe you seeded authors with random parameters; but turns out an author can't be selectable unless it passes x, y and z conditions; and the seeder didn't take that in consideration)

Programmatically add the category in the test.

cons would be you need to keep up with additional business logic, again.

Each tested feature retains data, so you first run acceptance test for adding categories, and then for adding a book.

cons would be your testing tool would need not to isolate tests, or at least run them in a certain order.

Maybe there's a 4th option I haven't considered yet? What's the correct approach for this common task?

答:
We are doing it second way. The best will be to show it by example (python):

```<code>def test_that_we_can_add_book_to_library(self):
    category = Category('Fantasy')
    self.library.add_category(Category('Fantasy'))
    book = Book(Title('Hobbit'), category)
    self.library.add_book(book)
    self.library.has_book(book)
</code>```

What is important here is a fact that library is an object created for tests only. It has behaviours that encapsulates logic (that can change) needed for tests.  Additionaly it makes test more readable.
library.add_category is such behaviour, if anything changes in business logic related to category, then we change it only there.

library.has_book is an assert method that checks if book was added to our storage.

It is really well described in the book "Growing object-oriented software: Guided by tests". Everyone that wants to write good tests should read it imho.

Body:
We are doing it second way. The best will be to show it by example (python):

def test_that_we_can_add_book_to_library(self):
    category = Category('Fantasy')
    self.library.add_category(Category('Fantasy'))
    book = Book(Title('Hobbit'), category)
    self.library.add_book(book)
    self.library.has_book(book)

What is important here is a fact that library is an object created for tests only. It has behaviours that encapsulates logic (that can change) needed for tests.  Additionaly it makes test more readable.
library.add_category is such behaviour, if anything changes in business logic related to category, then we change it only there.

library.has_book is an assert method that checks if book was added to our storage.

It is really well described in the book "Growing object-oriented software: Guided by tests". Everyone that wants to write good tests should read it imho.


答:
The techniques you can use may be very differt.

I try to figure out with different scenario

Request to db

download file

A simple login request to db (mean respond from db with one elemt) don't need a report progress but it alwasy can fire off UI thread in separate task ex. async or backgroundworker, here you just need one callback for result.

But what if you query for see all your inventory with 1mln item?
This query should take several minutes to complete, so in this case you need to implement your perport progress in your business logic in form item / items, then you can update your UI and may be give the option cancel callback.

Same case for file download.
You can always implement here your progress callback in form byte of bytes, and hold all comunication control over http is very commonly pattern.

On my personally approach i implement my business progress logic only to my clients, avoiding to share other object with end-point.


答:
I prefer doing both.

Keep a small predefined database or set of fixtures that can be used for smoke tests. It should have the bare minimum of data -- a single user, a single category, a single book, etc. This lets you write and run at least some basic tests without much extra work.

Then, for more complex tests they should create the data they need on the fly (and clean it up when done!).

Another solution is to start with a bare database, and write tests that populate it with a core set of objects. So the workflow is:

stand up new database

run the setup tests which populate the database with core data

if the setup succeeds, run additional tests which can use this initial setup data, plus create any additional data it needs on the fly.

The advantage to this second approach is that you have a single process that can act both as a smoke test of parts of your UI or API, and act as a setup step that prepares the database for more extensive testing.

Title: Acceptance testing with preloaded data or filling it on the go

Body:
We're figuring out whether we should write acceptance tests that revolves around preloaded data on a database file, or programmatically added needed data per test, or filling database while testing other application features.

This is a more detailed, easy use case: you want to acceptance test (or UI-test) adding a Book to the system. But in order to do that, you need to have Category rows in the database already, so you can assign one to the book. As you're writing your test case for adding a book, you:

Use a previously seeded database file that has already categories in it.

cons would be you need to keep that file up with every change in the code, with the latests changes on the system, AND you'd need to fill it while considering additional business logic (i.e. maybe you seeded authors with random parameters; but turns out an author can't be selectable unless it passes x, y and z conditions; and the seeder didn't take that in consideration)

Programmatically add the category in the test.

cons would be you need to keep up with additional business logic, again.

Each tested feature retains data, so you first run acceptance test for adding categories, and then for adding a book.

cons would be your testing tool would need not to isolate tests, or at least run them in a certain order.

Maybe there's a 4th option I haven't considered yet? What's the correct approach for this common task?


问:
Tables vs. Booleans: Which of the two are more secure for setting admin roles in an app?
I'm currently in the process of setting up roles where there are regular users, admins, and super admins, each of which have special permissions. I deferred to this post on how to do so.

It basically comes down to either setting up a few tables in addition to the User table: Roles (second table), UserRoles (join table) or creating boolean attributes for the User model: admin and super_admin. While I'm capable of doing both what should I keep in mind in keeping my app secure? Is one better than the other? Explain.

I ask this because as the the second answer of the SO post states:

It really depends on what you wish to do with your admin role. The
  first option, I would say is a bit secure as the admin role is a
  unique model in itself.

The second option is straightforward and would help you get going with
  the least effort. However, if your users figure out the boolean
  variable and a way to set it, any user can become an admin and access
  areas you don't want them to.

Before coming to this conclusion I wanted to get a second opinion on the matter.

答:
This decision has nothing to do with security, but your UserRoles idea is more extensible whereas the boolean attributes are simpler.

As with almost everything (and I'm getting more and more tired of having to point this out), there is no blanket rule making one "better" than the other in all cases.

Just pick one. As long as the code you write to interface with the database is isolated, you can easily change it in the future if you find you need to.

For now, you may wish to consider a column level ENUM('normal', 'admin', 'superadmin').


答:
keeping my app secure?

It depends somewhat on your definition of "secure". Does it include being able to go back in time and see who had particular permissions months ago? If so, the join table is ideal. Add validFromDateTime and validToDateTime fields and you have a complete audit history.

But if you just need to know who has what permission right now, the Enum solution suggested by Lightness Races in Orbit looks preferable to booleans (Only because the booleans let one user have multiple roles at the same time - a consideration if this was the Code Review forum). As others have rightly said, there is no inherent security difference between the boolean flag and join table approaches.

Title: Tables vs. Booleans: Which of the two are more secure for setting admin roles in an app?

Body:
I'm currently in the process of setting up roles where there are regular users, admins, and super admins, each of which have special permissions. I deferred to this post on how to do so.

It basically comes down to either setting up a few tables in addition to the User table: Roles (second table), UserRoles (join table) or creating boolean attributes for the User model: admin and super_admin. While I'm capable of doing both what should I keep in mind in keeping my app secure? Is one better than the other? Explain.

I ask this because as the the second answer of the SO post states:

It really depends on what you wish to do with your admin role. The
  first option, I would say is a bit secure as the admin role is a
  unique model in itself.

The second option is straightforward and would help you get going with
  the least effort. However, if your users figure out the boolean
  variable and a way to set it, any user can become an admin and access
  areas you don't want them to.

Before coming to this conclusion I wanted to get a second opinion on the matter.


问:
Command handler executing commands with different dependencies
Well basically, I have an Engine class that recieves a command as string from the input and passes it to a CommandHandler class which executes the apropriate command.

The CommandHandler passes the string to a CommandFactory to get the command and calls the method Execute() of the command, but the problem is that every command depends on different classes to execute properly. For example, one commands need the IOutputWriter to write something, the other needs IBuldingFactory to create a building, etc. I am using a reflection in the CommandFactory class, and I can't pass the dependencies through the constructor using Activator.CreateInstance(), because every command has different dependencies.

My current architecture looks something like this:

```<code>class Engine()
{
    IData data; // application database
    IInputReader inputReader;
    ICommandHandler commandHandler;

    public void Run()
    {
        string command = inputReader.Read();

        commandHandler.Handle(command, data);
    }
}

class CommandHandler()
{
    ICommandFactory commandFactory();

    public void Handle(string command, IData data)
    {
        string executableCommand = commandFactory().createCommand(command);
        executableCommand.Execute(data);
    }
}

class DisplayDataCommand : ICommand
{
    IOutputWriter outputWriter;

    public void Execute(IData data)
    {
        outputWriter.Print(data.ToString());
    }
}

class BuildCommand : ICommand
{
    IBuildingFactory buildingFactory;
    string buildingType;

    public void Execute(IData data)
    {
        var building = buildingFactory.createBuilding(buildingType);

        data.AddBuilding(building);
    }
}
</code>```

I can have different methods in the command handler for each command and call the appropriate method using switch case, but that would violate the Open/Closed principle. So my real question is - How to implement this without violating the Open/Closed principle.

答:
The problem you have is the conversion of the string to the class.

Not much you can do about it, As you will always have to have some factory which knows how to parse string x into object a,b,c somewhere.

But I would move the logic outside the command handler, which should just accept the command objects. And do the conversion as the strings are read into the application, via a repository (your inputReader or IData?) into which you inject your string parsing factories.

If you allow failover, so that when one repo/factory cant handle an input string it moves onto the next, that will give you further seperation of concerns.

If you use a DI or object serialization/deserialization library in yoir repo/factories (unity,json.net) that will hide some of the reflection/switch statements from your code and make it neater.

Also I would allow for the case where a command cannot be handled. This isnt a bad thing, you should expect only to be able to handle the commands your code 'knows' about and for some other program to deal with the others.

Additionaly, are you sure you need both commandHandler AND command.Execute() it seems to me that  you should choose one or the other. If you go with command handlers you cam have one or more per type. The handler has the injected dependancies and the logic from the execute method.

This keeps your handler decoupled, as it only handles a single type of command, you can pull only those types from a queue(IData).

Of course if you keep execute and only pull one type (or set of known types) of object you have the exect same code just arranged differntly, but you can cut out the command handler class, as it just calls execute.

The benefit (if any) of the handler is you can handle the same command type more than one way. Whereas with execute you have to define a new command type with the same data.

example :

```<code>class Engine()
{
    IData data; // application database
    IInputReader inputReader;
    Dictionary<string,ICommandHandler> commandHandlers;
    public void Run()
    {
        //todo use a DI framework to inject these types
        commandHandlers = new Dictionary<string,ICommandHandler>();
        commandHandlers.Add("DisplayData", new DisplayDataCommandHandler(new OutputWriter()) );
        commandHandlers.Add("Build", new BuildDataCommandHandler(new Builder()) );

        foreach(var data in this.data.GetCommands())
        {
            if(commandHandlers.Keys.Contains(data.type))
            {
                var command = inputReader.Read(data.type, data.serializedObject);
                //handle the command
                commandHandlers[data.type].Handle(command);
            }
            else
            {
                //some other program will handle these commands
            }
        }
    }
}

public class InputReaderAndFactory : IInputReader
{
    public ICommand GetCommand(string commandType, string commandJson)
    {
        switch (commandType)
        {
            case "DisplayData" :
                return JsonConvert.DeserializeObject<DisplayDataCommand>(commandJson);
            case "Build" :
                return JsonConvert.DeserializeObject<BuildCommand>(commandJson);
            default :
                return new UnknownCommand(commandJson);
        }
    }
}

class DisplayDataCommandHandler : ICommandHandler
{
    IOutputWriter outputWriter;
    public DisplayDataCommandHandler(IOutputWriter outputWriter)
    {
        this.outputWriter = outputWriter;
    }

    public void Handle(ICommand command)
    {
        var cmd = command as DisplayDataCommand;
        outputWriter.Print(cmd.Data.ToString());
    }
}
class BuildDataCommandHandler : ICommandHandler
{
    IBuilder builder;
    public BuildDataCommandHandler(IBuilder builder)
    {
        this.builder = builder;
    }

    public void Handle(ICommand command)
    {
        var cmd = command as BuildCommand;
        builder.Build(cmd.Data, cmd.MoreData);
    }
}
class DisplayDataCommand : ICommand
{
    public Data Data {get;set;}
}

class BuildCommand : ICommand
{
    public SomeOtherTypeOfData Data {get;set;}

    public MoreData MoreData {get;set;}
}
</code>```

Body:
The problem you have is the conversion of the string to the class.

Not much you can do about it, As you will always have to have some factory which knows how to parse string x into object a,b,c somewhere.

But I would move the logic outside the command handler, which should just accept the command objects. And do the conversion as the strings are read into the application, via a repository (your inputReader or IData?) into which you inject your string parsing factories.

If you allow failover, so that when one repo/factory cant handle an input string it moves onto the next, that will give you further seperation of concerns.

If you use a DI or object serialization/deserialization library in yoir repo/factories (unity,json.net) that will hide some of the reflection/switch statements from your code and make it neater.

Also I would allow for the case where a command cannot be handled. This isnt a bad thing, you should expect only to be able to handle the commands your code 'knows' about and for some other program to deal with the others.

Additionaly, are you sure you need both commandHandler AND command.Execute() it seems to me that  you should choose one or the other. If you go with command handlers you cam have one or more per type. The handler has the injected dependancies and the logic from the execute method.

This keeps your handler decoupled, as it only handles a single type of command, you can pull only those types from a queue(IData).

Of course if you keep execute and only pull one type (or set of known types) of object you have the exect same code just arranged differntly, but you can cut out the command handler class, as it just calls execute.

The benefit (if any) of the handler is you can handle the same command type more than one way. Whereas with execute you have to define a new command type with the same data.

example :

class Engine()
{
    IData data; // application database
    IInputReader inputReader;
    Dictionary<string,ICommandHandler> commandHandlers;
    public void Run()
    {
        //todo use a DI framework to inject these types
        commandHandlers = new Dictionary<string,ICommandHandler>();
        commandHandlers.Add("DisplayData", new DisplayDataCommandHandler(new OutputWriter()) );
        commandHandlers.Add("Build", new BuildDataCommandHandler(new Builder()) );

        foreach(var data in this.data.GetCommands())
        {
            if(commandHandlers.Keys.Contains(data.type))
            {
                var command = inputReader.Read(data.type, data.serializedObject);
                //handle the command
                commandHandlers[data.type].Handle(command);
            }
            else
            {
                //some other program will handle these commands
            }
        }
    }
}

public class InputReaderAndFactory : IInputReader
{
    public ICommand GetCommand(string commandType, string commandJson)
    {
        switch (commandType)
        {
            case "DisplayData" :
                return JsonConvert.DeserializeObject<DisplayDataCommand>(commandJson);
            case "Build" :
                return JsonConvert.DeserializeObject<BuildCommand>(commandJson);
            default :
                return new UnknownCommand(commandJson);
        }
    }
}

class DisplayDataCommandHandler : ICommandHandler
{
    IOutputWriter outputWriter;
    public DisplayDataCommandHandler(IOutputWriter outputWriter)
    {
        this.outputWriter = outputWriter;
    }

    public void Handle(ICommand command)
    {
        var cmd = command as DisplayDataCommand;
        outputWriter.Print(cmd.Data.ToString());
    }
}
class BuildDataCommandHandler : ICommandHandler
{
    IBuilder builder;
    public BuildDataCommandHandler(IBuilder builder)
    {
        this.builder = builder;
    }

    public void Handle(ICommand command)
    {
        var cmd = command as BuildCommand;
        builder.Build(cmd.Data, cmd.MoreData);
    }
}
class DisplayDataCommand : ICommand
{
    public Data Data {get;set;}
}

class BuildCommand : ICommand
{
    public SomeOtherTypeOfData Data {get;set;}

    public MoreData MoreData {get;set;}
}


问:
Workaround for implementing operations on doubly linked or circular data structures in languages with immutable data
I would like to learn how to make graphs and perform some local operations on them in Haskell, but the question is not specific to Haskell, and instead of graphs we may consider doubly linked lists.

Question: What would be an idiomatic or recommended way to implement a doubly linked list (or other doubly linked or circular data structure) and operations on it in a language that mainly supports and advocates for immutable data structures (Haskell, Clojure, etc.)?  In particular, how to use in-place updates, which are formally forbidden by the language?

I can easily imagine that if some local operation is performed on a doubly linked list (if an item is inserted, for example), there may be no need to copy the entire list immediately due to the laziness of the language.  However, since the list is doubly linked, if it is modified in one place, none of the old nodes can be used in the new version of the list, and they would need to be somehow marked, copied, garbage-collected sooner or later.  Obviously these are redundant operations if only the updated copy of the list shall be used, but they would add an "overhead" proportional to the size of the list.

Does this mean that for such tasks immutable data is simply inappropriate, and functional declarative languages without "native" support for mutable data are not as good as imperative ones?  Or, is there some tricky workaround?

P.S. I have found some articles and presentations on this subject in the Internet but had hard time following them, while i think that the answer to this question should not take more than one paragraph and maybe a diagram...  I mean, if there is no "functional" solution to this problem, the answer probably is "use C".  If there is one, then how complicated can it be?

Related questions

"Data structures in functional programming".
My specific question about using in-place updates instead of inefficient alternatives is not discussed there.

"Internal Mutation of Persistent Data Structures".
There the emphasis seems to be on low-level implementation in an unspecified language, while my question is about the right choice of a language (functional or otherwise) and about possible idiomatic solutions in functional languages.

Relevant quotations

Purely functional programming languages allow many algorithms to be expressed very concisely, but there are a few algorithms in which in-place updatable state seems to play a crucial role.  For these algorithms, purely-functional languages, which lack updatable state, appear to be inherently inefficient ([Ponder, McGeer and Ng, 1988]).

-- John Launchbury and Simon Peyton Jones, Lazy functional state threads (1994), also John Launchbury and Simon Peyton Jones, State in Haskell (1995).  These papers introduce ST monadic type constructor in Haskell.

答:
Haskell does not prevent the use of mutable data structures. They are heavily discouraged and made harder to use because of the fact that the parts of code that use them must eventually return an IO action (which must eventually be bound into the IO action that is returned by the main function), but that does not make it impossible to use such structures if you really need them.

I would suggest investigating the use of software transactional memory as a way forward. As well as providing an efficient way to implement mutable structures, it also provides very useful guarantees for thread-safety. See the module description at https://hackage.haskell.org/package/stm and the wiki overview at https://wiki.haskell.org/Software_transactional_memory .