问:
How does a search functionality fit in DDD with CQRS?
In Vaughn Vernon's book Implementing domain driven design and the accompanying sample application I found that he implemented a CQRS approach to the  iddd_collaboration bounded context.

He presents the following classes in the application service layer:

CalendarApplicationService.java

CalendarEntryApplicationService.java

CalendarEntryQueryService.java

CalendarQueryService.java

I'm interested to know if an application will have a search page that feature numerous drop downs and check boxes with a smart text box to match different search patterns; How will you structure all that search logic?

In a command service or a query service?

Taking a look at the CalendarQueryService.java I can see that it has 2 methods for a huge query, but no logic at all to mix and match any search filters for example.

I've heard that the application layer shouldn't have any business logic, so where will I construct my dynamic query? or maybe just clutter everything in the Query service?

答:
In CQRS, queries are not allowed to have any side effects, and thus they cannot change any data. Commands on the other hand must not return any data, but change the state of the application.

With these definitions and your problem domain the question becomes this: What does the search functionality do? If it's purely for finding an order, then it is not changing any application state while doing the search. The resulting view might offer a button or such to perform operations on that found order, and then you transition into the command side of CQRS. On this side what you need to successfully complete the command is retrieved through the domain object and acted upon and then stored back to the data store.

All in all, as the logic of performing a complex search might sound like it's correlated to the business or domain logic, I'd argue that it actually hasn't got anything to do with domain logic. It's just a logical tool to get the info the user needs. Domain logic is the logic that will be applied when you e.g. cancel the order. What does cancelling an order mean is the question that domain logic answers.


问:
"Comments are a code smell"
A coworker of mine believes that any use of in-code comments (ie, not javadoc style method or class comments) is a code smell.  What do you think?

答:
Of honorable mention is the anti-pattern:

It's my impression that sometimes FLOSS license preamples are frequently used in lieu of file documentation. The GPL/BSDL makes a nice filler text, and after that you seldomly see any other comment block.

ContentLicense: CC BY-SA 2.5

Title: "Comments are a code smell"


问:
Open Source code bounties
I have a library for R (open source statistics package) mapped out on paper. I have started coding the different functions but I realize that I don't have the time needed to finish this in a reasonable amount of time. I know I can just throw the code up on a repo and call for others to help fill in the blanks. But I'd like to incentivize things a bit. I'm thinking about putting a bounty on each function of, say, $5-$20. There's no way that $20 would be a fair return on time for a developer to code each function. But my thought is that the cash (or Amazon gift certificates) would be an inventive for people to actually work on the project. And it would allow me to put higher bounties on the functions I am most interested in.

I have a few questions related to this:

Good idea?

I going to make
the development work faster, or
slower? I've read Predictably
Irrational and I'm concerned
that by offering menial pay for
functions I might actually
disincentive developers.

Are
there sites devoted to this type of
activity? Can you recommend one based on personal experience?

Would you recommend a totally different approach? I'm open to ideas!

答:
I remember seeing some sites during the dot com days that were basically exactly what you describe.  People would post small coding tasks they wanted done, a $ amount, and people could register to perform said task - there were some variations on that theme, but that was the basic idea.  Being fresh out of school and looking for some extra moolah I would often poke around and look for a good one to do.  The result?  I never did a single one.  Invariably I'd look at the tasks (that I could do) and do a price/performance in my head and realize it really wasn't worth my time to bother (exactly the point you make in #2).  The other problem was that almost all of them were not compelling problems - there was a reason why they were being farmed out :)

I agree with KevDog that if you have a cool project & some decent PR (getting the word out) that people will come find you and do the work for free.  While I've never gone the mercenary route I've certainly contributed code here & there to OSS projects that strike my fancy.

Title: Open Source code bounties


问:
Git branch model critique: always derive from master
I am currently working on a large project involving at least 3 teams working on separate feature sets in the same codebase versioned on Git. Some features require back-end integration and stabilization and I've heard of features taking months from being ready to going live.

I've seen A successful Git branching model and found it unsuitable for this situation, especially because feature branches must derive only from the development branch.

I assume features should always be in sync with master which represents current production code. The process of taking code from master->release->develop->feature makes keeping features up-to-date more difficult.

Plus, when complex merge conflicts arise on a merge from release to develop, who should solve it? On a large project with distributed teams with non-overlapping responsibilities not a single person is best suited to resolve complex merge conflicts across a whole codebase. No one owns the develop branch, neither a person or a team.

Merging features to and from the development branch also brings to them not-yet-production-ready code from other features while trying to keep them up-to-date with master, making feature branches sort of infect one another in the process. Once I've pulled from development to update my feature with latest production code and be able to call it "finished", I've infected my branch with supposedly finished code from other features that have merged to development. If any features in development are found to be either hard to stabilize or de facto a bad idea, we've compromised the development branch and all its feature branches.

Instead of deriving from the development branch, I found deriving from master and merging into disposable "release-package" branches lead to less headaches.

When merge conflicts arise in master->feature merge, the person doing the merge is the one most suited to resolve them. She knows the code and what it should do, it's her feature.

Features are streamlined into disposable release branches that can be deleted and reformed at any time. If a feature is not ready to go live by the release deadline, we can delete and recreate the package without it.

Development is only done in feature branches. Release branches only receive merges. If features conflict in a meaningful way, we should question if they should be merged into one another or scheduled for sequential release, one after another. In the case we merge two features into one another, the scenario might look too similar to NVIE's branch model, but here we are given a choice to do it or reschedule the features and recreate the release package.

The disposable nature of release branches and the independence of feature branches makes it possible to stage fallback releases.

If all four features don't stabilize until the deadline, only 1 and 2 go live.

Is my proposal a suitable branch model?

PS: I've read this answer about branch models vs quality and CI, and I don't think it applies. This project does have a quality problem. This quality problem will be there tomorrow and the next month, and while this quality problem remains there must be a suitable branch model we can use, one that does not make life harder.

答:
The main problem you are going to face is that when you are combining the feature branches to a release branch, you'll need to solve all the inter-branch conflicts. Merge conflicts are the easier ones, since they pop when you are merging specific branches and you can ask the branch owner to solve them(it's far from ideal though, since the branch is not fresh in the owner's memory). But not all conflicts pop us as merge conflicts - some create compilation errors or runtime bugs, and it's not as trivial to figure which feature branches have caused those.

A possible solution can be to shorten the release cycle - adding more rapid "sub-releases", e.g. twice a week. This will limit the number of feature branches you are merging on each sub-release, which in turn limit the conflict potential. This, of course, comes with it's own problems - a frequent release overhead, where the release master needs to choose which features to merge in each sub-release, and after the sub-release the developers need to merge/rebase their pending feature branches(and resolve conflicts).

At any rate, I think your fear of branching-from-develop is unjustified. You are portraying develop as some big playground where all developers push their unfinished scrabbles of untested code - and it's not true. The feature branches fulfill this role. develop, while it might not need to be as stable and as rigorously tested as master, should still have a certain level of stability - the primary rule is not to push to develop if it'll prevent the other developers from continuing to develop even if they merge/rebase develop to their feature branches.

This essentially means that you don't merge a feature branch to develop unless it passes automated tests(doesn't have to be the full suite - if you have a 10-minute suite that catches most bugs and a 5-hour suite that catches even the rarest of bugs, test the feature branches with the 10-minutes suite), so it should be OK to merge it to develop.

Note that master still needs to pass the 5-hour suite, and you have no guarantee a a merged feature branch won't break the 5-hour suite - but neither does your model provide such guarantee. The point is that even if a merged feature branch does break the 5-hour suite - it's still a branch you want in the next release(otherwise you wouldn't have merged it to develop), and the solution is rarely to exclude the feature from the next release.

Update

To answer the asker's first comment to this answer:

When runtime integration bugs arise, the affected feature-set team will be assigned to correct it. If it is caused by code from features created by any of the other teams, fixes are made into pull requests to the offending feature branch. Pull requests are then reviewed by the team that owns that feature, merged in and then merged into the release package. The team that knows how a feature should work makes the fix, the team who owns the offending code reviews it.

This method of solving bugs has several drawbacks compared to solving them as part of the preparation of a feature branch to be merged into develop:

The feature-set where the bug happens is usually easy in to figure in both methods. The actual changes that invoked the bug are trivial when branching from develop and very tricky when branching from master. The former only gives you a cue about you about who should be assigned to try solving the bug first, which is not as useful as the actual lead you get from the letter. At any rate, branching from develop allows you to have both hints.

The responsibility is backwards. If anything, the owner of the offending code is the one who should fix it, since they know best what they are trying to achieve, and the owner of the feature-set is the one who should review it, because they know best how the different parts of the feature-set should interact with each other.

But the branch-from-develop approach has an even better way to decide who will be the one to start solving the conflict - it's the one who tries to merge last!

Now, that claim might seem a little weird and arbitrary - it looks unfair to "punish" the developer who pushed last for being slow. But I believe they are the best choice for starting to solve the problem:

They are already in the context of the problem. This is the most important reason - being in context is crucial for solving problems, and entering context is hard. But the developer who pushes last is already in context, because that's the task they are working on. They have already build the mental model that can help them solve this problem.

They are available. They don't have something more urgent to do right now, because what they were doing was trying to merge their feature branch, and solving the conflict is required for merging the feature branch.

They don't have to actually solve the conflict entirely by themselves - just to be the first ones to look at it. When examining the problem they can decide some other developers need to be involved. Since they are in context, they are in the best position to tell who these other developers are. Also since they are in context, they can help bringing these other developers quickly into context.

That pull request into the offending feature branch will be a nightmare. The code in the feature branch works, because the other branch it was conflicting with is not part of it. So, you are sending a fix to a problem that's not yet there, that might have to relies on changes that come with the same code that introduced that problem. There is no sane way to do that without merging/rebasing the other branch(or the new release) into the feature branch - but if you do that you are just using branch-from-develop with develop having it's name replaced on each release.

ContentLicense: CC BY-SA 3.0


问:
Containing the GPL inside an external service?
Not asking for legal advice, just educated intuition.

Lets say a programmer creates a program to provide a service, for instance (hypothetically) face recognition. User logs in, uploads pictures and the program informs their friends that a picture of them was uploaded (or whatever).

Now the programmer finds another GPL software that can greatly enhance the performance of their program by preforming some initial CV analysis. Can the programmer place the GPL software on a private RPC server and have their paid software communicate with that server?

Meaning would that require making the new program GPL aslo?

答:
The intention of the GPL is to ensure the maximal possible freedom for the (end-)users of GPLed code. Therefore:

you may freely use GPLed software, even in closed source applications. The GPL does not require that you open-source your code.

when you re-distribute/convey GPLed software, you must use the GPL license so that your users enjoy the same freedom – you may not sublicense it to set different terms.

when you distribute software that depends on GPLed code, you must license your software under the GPL.

So the GPL is only “viral” when you distribute your software. When your GPL-depending software is not distributed, there is no need to issue licenses.

When the software only runs on your servers, you are not conveying the software to your end users, you are merely providing access to that software. This is a valid loophole in the GPL, and the AGPL closes it (by tying the licensing requirements to usage rather than distribution).

So to summarize: you are free to use GPL software in a SaaS context without having to make your code GPLed – as long as you merely provide access to your GPL-dependent software and do not distribute it (e.g. sell your software to clients so they can install it on their own servers, or make your software available in some public package manager). The GPL distribution rules only kick in when you give a copy of the software to another legal entity, e.g. a different company.


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答:
We used this at one company I worked for.

We handed the candidate a piece of paper used for tracking time.  It was a real timesheet  used by one or our divisions.  We asked the candidate to walk us through the design process for creating a better time tracking tool.  No boundaries, didn't say what language etc., just want to see how good the candidate was at "full lifecycle".  It gave us a real insight into how they gathered requirements.  How they structured database tables, what kind of UI they might do.  Communication skills were obviously needed for this task.  It was usually done in a room with several large white boards and lasted as long as 2 hours.

We hired several people using this process and if they did really well on the task they did really well for us.  If they were marginal and we decided to hire them anyway (separate topic) they were marginal programmers.


问:
How does I/O work for large graph databases?
I should preface this by saying that I'm mostly a front end web developer, trained as a musician, but over the past few years I've been getting more and more into computer science.

So one idea I have as a fun toy project to learn about data structures and C programming was to design and implement my own very simple database that would manage an adjacency list of posts. I don't want SQL (maybe I'll do my own query language? I'm just having fun). It should support ACID. It should be capable of storing 1TB let's say.

So with that, I was trying to think of how a database even stores data, without regard to data structures necessarily. I'm working on linux, and I've read that in that world "everything is a file," including hardware (like /dev/*), so I think that that obviously has to apply to a database, too, and it clearly does--whether it's MySQL or PostgreSQL or Neo4j, the database itself is a collection of files you can see in the filesystem.

That said, there would come a point in scale where loading the entire database into primary memory just wouldn't work, so it doesn't make sense to design it with that mindset (I assume). However, reading from secondary memory would be much slower and regardless some portion of the database has to be in primary memory in order for you to be able to do anything with it. I read this post:

Why use a database instead of just saving your data to disk?

And I found it difficult to understand how other databases, like SQLite or Neo4j, read and write from secondary memory and are still very fast (faster, it would seem, than simply writing files to the filesystem as the above question suggests). It seems the key is indexing. But even indexes need to be stored in secondary memory. They are inherently smaller than the database itself, but indexes in a very large database might be prohibitively large, too.

So my question is how is I/O generally done with large databases like the one I described above that would be at least 1TB storing a big adjacency list? If indexing is more or less the answer, how exactly does indexing work--what data structures should be involved?

答:
I think the term you're looking for is Memory-mapped file.
The Neo4j devs occassionally blog about Neo4j internal, the post Neo4j Internals: Persistence and Memory Mapping should be of interest. Haven't read it myself though and I'm not sure how current it is w.r.t. to Neo4j implementation (post is from 2010), but it could be a starting point.</p>


问:
Conceptual question whether to pass data between functions or use a Class
I have a hard time to find an ideal concept / design and would appreciate your thoughts on this.

I have 16 "tissues" that I need to keep track on. Each tissue holds a pressure that need to be calculated depending on the last value.

So I was going through few thoughts how to organise / structure it.

1. Use array of tissues

and and passing the previous value to a function to return the new calculated value.

As an example:

```<code>load_tissue = function(value, tissue) {
  return { pressure: tissue.pressure + value };
}

tissue = { pressure: 1 }

newTissue = load_tissue(2,tissue);
// newTissue = { pressure: 3 }
</code>```

Obviously this is a very simplified function that does nothing except returning an new object with the added value. I would do this for each 16 compartments.

This version works but does not seem to be very intuitive and object oriented.

2. Create a Tissue object

Next version would be to have a Tissue object that holds the data and has a function to calculate. This version sounds very intuitive to me because in real world it is the same.

```<code>Tissue = function() {
  this.pressure = 1;
}

Tissue.prototype.load_tissue(value) {
  this.pressure = this.pressure + value;
}

tissue = new Tissue();
newTissue = tissue.load_tissue(2);

// newTissue.pressure = 3;
</code>```

The problem I have with this is that I can not keep the last state due to referencing.

```<code>tissue = new Tissue();
tissue1 = tissue.load_tissue(2); // tissue1 = 3;
tissue2 = tissue.load_tissue(3); // tissue2 = 6 BUT tissue1 = 6 as well.
</code>```

Although I like that the Tissue object knows it state, in some circumstances I need to be able to "predict" a value without saving it to the object.

Now I am a bit confused what the ideal solution to this is. I was thinking of cloning the object..

The real Tissue() class is a bit more complex and looks like this

```<code>Tissue = function(n2_half_time, he_half_time, n2_A, n2_B, he_A, he_B, p_surface) {

   this.startPN2 = 0.7902;
   this.startPHE = 0.0;

   this.half_time = {
       n2: n2_half_time,
       he: he_half_time
   };

   this.k_decay = {
       n2: Math.LN2 / n2_half_time,
       he: Math.LN2 / he_half_time
   };

   this.A = {
       n2: n2_A,                                                                                he: he_A
   };

   this.B = {
       n2: n2_B,
       he: he_B
   };

   this.pN2;
   this.pHe;
                                                                                this.init(p_surface);
}

Tissue.prototype.init = function(p_surface) {
   var ambient_pressure = (p_surface == false) ? PRESSURE_AMBIENT_SEA_LEVEL : p_surface;
   this.pN2 = this.startPN2 * (ambient_pressure - PRESSURE_WATER_VAPOUR);
   this.pHe = this.startPHE;
}

Tissue.prototype.load_tissue = function(p_abs, gas, rate, time) {
    var kN2 = this.k_decay.n2;
    var p_alv_n2 = (gas.n2 / 100) * (p_abs - PRESSURE_WATER_VAPOUR);
    var R_n2 = (gas.n2 / 100) * rate;

    var kHe = this.k_decay.he;
    var p_alv_he = (gas.he / 100) * (p_abs - PRESSURE_WATER_VAPOUR);
    var R_he = (gas.he / 100) * rate;

    this.pN2 = this.schreiner_equation(p_alv_n2, R_n2, time, kN2, this.pN2);
    this.pHe = this.schreiner_equation(p_alv_he, R_he, time, kHe, this.pHe);
}
</code>```

答:
Your confusion around

```<code>tissue = new Tissue();
tissue1 = tissue.load_tissue(2); // tissue1 = 3;
tissue2 = tissue.load_tissue(3); // tissue2 = 6 BUT tissue1 = 6 as well.
</code>```

derives from confusion value and object-oriented semantics in your tissue abstraction. This is called 'aliasing'.

To find out which one you should use, ask the following question "If two Tissues have the same pressure, are they always the same thing?". If you say YES, then the very first approach (returning a new object when you change the value) is the correct one. If you say NO (i.e. there can be two different tissues that happen to have the same pressure), then your second approach is correct.

If an object-oriented tissue must know the history of its values for later processing, then the object must maintain that list, like the following:

```<code>Tissue = function() {
  this.history = [];
  this.pressure = 1;
}

Tissue.prototype.load_tissue(value) {
  this.history.push(this.pressure);
  this.pressure = this.pressure + value;
}
</code>```

Body:
Your confusion around

tissue = new Tissue();
tissue1 = tissue.load_tissue(2); // tissue1 = 3;
tissue2 = tissue.load_tissue(3); // tissue2 = 6 BUT tissue1 = 6 as well.

derives from confusion value and object-oriented semantics in your tissue abstraction. This is called 'aliasing'.

To find out which one you should use, ask the following question "If two Tissues have the same pressure, are they always the same thing?". If you say YES, then the very first approach (returning a new object when you change the value) is the correct one. If you say NO (i.e. there can be two different tissues that happen to have the same pressure), then your second approach is correct.

If an object-oriented tissue must know the history of its values for later processing, then the object must maintain that list, like the following:

Tissue = function() {
  this.history = [];
  this.pressure = 1;
}

Tissue.prototype.load_tissue(value) {
  this.history.push(this.pressure);
  this.pressure = this.pressure + value;
}


问:
Understanding Abstract Data Types (ADTs)
Just browsing through Code Complete last night and I came across the explanation of abstract data types.

I must have read it 5 times, and the Wikipedia article doesn't help much either.  So what I'm looking for is a simple explanation of exactly what is an Abstract Data Type?  Any solid examples?  In C# or VB?

I understand that String is supposed to be one, why is this? And why isn't Int32 one?  Or is it?

Any pointers are much appreciated.

答:
An Abstract Data Type (ADT) is any type whose internal implementation can change without affecting code that uses it. By "internal implementation", I mean that the interface (API, if you wish) for the ADT remains.

In that sense, the classic "internals-hiding" class implements an ADT, it would be possible to have a parallel implementation with different internal implementation, as long as the API remains unchanged.


答:
An abstract data type is a theoretical concept (a collection of function signatures and rules) to describe the values that a type can have by defining how these values can be constructed and which constructions create the same values. For example, for integers, you can have:

Three signatures:

```<code>zero: INTEGER
successor(INTEGER): INTEGER
predecessor(INTEGER): INTEGER
</code>```

And the following rules:

```<code>successor(predecessor(X)) = X
predecessor(successor(X)) = X
</code>```

You can introduce addition, subtraction and any other operation by providing these rules.

ADTs are vehicle to understand types, similar to a Turing machine is used to understand computation.

There is a relationship between ADTs and data types in programming languages,
more specifically classes in OO languages. But that is a complex relationship, as instances of classes in OO introduce the idea of 'object identity' which is not present in ADTs.

Title: Understanding Abstract Data Types (ADTs)

Body:
Just browsing through Code Complete last night and I came across the explanation of abstract data types.

I must have read it 5 times, and the Wikipedia article doesn't help much either.  So what I'm looking for is a simple explanation of exactly what is an Abstract Data Type?  Any solid examples?  In C# or VB?

I understand that String is supposed to be one, why is this? And why isn't Int32 one?  Or is it?

Any pointers are much appreciated.

Body:
An abstract data type is a theoretical concept (a collection of function signatures and rules) to describe the values that a type can have by defining how these values can be constructed and which constructions create the same values. For example, for integers, you can have:

Three signatures:

zero: INTEGER
successor(INTEGER): INTEGER
predecessor(INTEGER): INTEGER

And the following rules:

successor(predecessor(X)) = X
predecessor(successor(X)) = X

You can introduce addition, subtraction and any other operation by providing these rules.

ADTs are vehicle to understand types, similar to a Turing machine is used to understand computation.

There is a relationship between ADTs and data types in programming languages,
more specifically classes in OO languages. But that is a complex relationship, as instances of classes in OO introduce the idea of 'object identity' which is not present in ADTs.


问:
What are the advantages of build scripts?
For most of my programming career, I've used the "build/compile/run" command in whatever IDE I'm working with to produce a runnable program. This is one button, pretty easy. As I learn more about different languages and frameworks, though, I see more and more talk of "build scripts" (ANT, Maven, Gradle, etc.) to get a project running. My understanding of these is that they are instructions to the compiler/linker/magical-program-maker that specify configuration details - minutiae.

I remember writing makefiles back in school, but I didn't see any special advantage then (we only used them when writing in a Unix terminal, where an IDE with it's handy "build" button wasn't present). Beyond that, I've seen other questions on here that discuss how build scripts can do more than just create your program - they can run unit tests as well as secure resources regardless of the host machine.

I can't shake the feeling that build scripts are important to understand as a developer, but I'd like a meaningful explanation; why should I use/write build scripts?

Responsibilities of Build Script and Build Server discusses the role it plays within a broader scope. I'm looking for specific advantages offered by a build script versus an IDE's "build/run" command or similarly simple methods.

答:
Often you can call the "build" button in an automated way (Visual Studio accepts command line arguments, for example). People write build scripts as soon as they need something that the build button cannot provide.

For example, most IDEs will only let you build one platform at a time. Or only one language at a time. Then there's what you do with the built outputs: can your IDE roll them all up into an install package?


问:
How do binary trees use memory to store its data?
So I know that arrays use a block on contiguous memory addresses to store data to memory, and lists make use of static arrays and when data is appended to the list, if there is no room, a new static array is created elsewhere in memory larger in size so more data can be stored. My question is, how do binary trees use memory to store data? Is each node a memory location which points to two other memory locations elsewhere...not necessarily contiguous locations? Or are they stored in contiguous blocks of memory too like a static array or dynamic list?</p>

答: Implementations differ, but traditionally nodes were allocated as needed and as such were generally thought of as non-contiguous. In practice, if the binary tree were being constructed from a data set (e.g., data read from a file), then the node allocations would usually wind up being contiguous, since they were typically allocated sequentially and not interleaved with other allocations. However, if the tree was built dynamically and node creation was interspersed with other memory-allocating operations, then the nodes were non-contiguous. Note that, depending on the heap management scheme used, even "contiguous" node allocations typically had their size rounded up to the heap block size, so one node wouldn't start exactly where the previous node ended.</p>


问:
Gherkin: What is a reasonable number of scenarios per feature?
I'm keen to get thoughts on a reasonable number of scenarios per feature in Gherkin.

At what point do you start to thing about re-organising the feature to keep the number of scenarios at a manageable level?

答:
'In general if there are more than about five or six scenarios, a story can probably be broken down by grouping similar scenarios together.'

Dan North (http://dannorth.net/whats-in-a-story/)


问:
Unit testing implementation vs behaviour
Is it possible to write a unit test (as opposed to an integration test) in the following scenario:

I have a list of Foo objects, some of which already exist in the database, some don't

I want to iterate over the list, update the ones I already have in the database and add new ones

So, I write a test which has a FooImporter with an importFoos(List<Foo> foos) method. And then I need to mock out my DAO layer, so I mock the FooDAO which gets injected into the FooImporter...and then I'm feeling like I'm testing the implementation not the behaviour! In my test I end up with a bunch of expectations on calls (e.g. I put in an "existing" Foo record, then I mock the behaviour of the FooDAO to return true on the check for duplicate, and then add an expectation for the insert behaviour etc.)

So can I actually unit test this close to the data layer effectively, or should I be integration testing? And if so, can this not be done sensibly in a TDD manner?

(Before this gets flagged as a duplicate, this question is actually about the talk which inspired this question but the answer doesn't really convince me that this solves the coupling of tests to implementation behaviour.)

答:
A unit test should test the job that the tested unit has, no more, no less.

If your method has the job of acessing the database and issuing UPDATE and INSERT commands as required, then that is what you have to test. When your collaborator is a data base, then issuing SQL is not an implementation detail: it is the behaviour of that unit.

Compared to the huge amount of code that you leverage by using a real database with its million LOC, that might seem small, but that impression is misleading.

A unit test should be small. Small tests are easy to get right. Small tests go well with small methods, and small methods are also easy to get right. Trying to do two things at the same time makes your code more than twice as large, and therefore isn't a good trade-off.


问:
How to authenticate against an API?
In a enterprise distributed system, a user of a web portal can sign into one site, be redirected to a federation provider. Once they log in with, for example, a facebook account, that user is federated (single-sign-on) with each service that exists in the enterprise that trusts the same federation provider for authentication.

My question is this; How can API users of the same system benefit from the same luxury (single sign on) ? As far as I understand it, API calls should be stateless, thus each request should require separate authentication.

If each of the distributed API's, when called by a client, need to make a call to the federation provider, get authenticated, pass claims back to the API, then process the clients request, it seems a little network chatty to me.

To clarify, an example scenario for an API client might be :

Create a customer (customer API)

Create a user for that customer (user API)

Place an order (order API)

View billing statement (billing API)

View customer report (report API)

Like I say, it seems a little chatty for each API to talk to the federation provider on each request.

答:
Can't use OAuth2 protocol for that. Having authenticated user once, system issues access token to it. This token will be sent with an each request.

Oauth2 has several flows. They are primarily for end-user, but for server-to-server interaction you can use two-legged OAuth like Google Data API uses now.

Title: How to authenticate against an API?


问:
Why is the factory method design pattern more useful than having classes and calling them individually?
From the "Gang of Four" design patterns, there's the Factory method:

```<code>class Factory(product)
  case product
  when a
    new A
  when b
    new B
  when c
    new C
end

new Factory(a)
</code>```

Why is this more useful than having three classes, a, b, and c and calling them individually?

答:
I would like to think about design patterns in terms of classes being as 'people,' and patterns are ways that people talk to each other.

So, to me the factory pattern is like a hiring agency. You've got someone that will need a variable number of workers. This person may know some info they need in the people they hire, but that's it.

So, when they need a new employee, they call the hiring agency and tell them what they need. Now, to actually hire someone, you need to know a lot of stuff - benefits, eligibility verification, etc. But the person hiring doesn't need to know any of this - the hiring agency handles all of that.

In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.

Courtesy


问:
Frankly, do you prefer Cowboy coding?
Most programmers defending methodologies politically correct like Agile, Waterfall, RUP, etc. Some of them follow the methodology but not all of them. Frankly, if you can choose the methodology, you certainly would go to mainstream "correct" methodologies or you would prefer the "easier" methodology like cowboy programming? Why?

I know it depends. Please, explain when you would use one or another. Please, say what advantages do you see on Cowboy coding.

See about Cowboy coding on Wikipedia

答:
No, never.

I always do requirements analysis, think about architecture, design the details, and then code. Even if I work solo at home for a personal project.

And I would instantly fire a developer in my team if he/she were working in a cowboy style. We are engineers and have a responsibility with the customer and the users.

Title: Frankly, do you prefer Cowboy coding?


问:
Understanding C# Delegates Structure
I've been trying to understand C# delegates using Pro C# 5.

In short, the author describes the motivation for delegates as a structured way of dealing with function pointers and callbacks or two-way communication between objects.

The part I find confusing is the syntax/implementation for this:

On the one hand, an object of delegate type is seen as the handler
or the one responsible for invoking some method or list of methods. To this end, it has
methods such as Invoke() etc.

On the other hand, the delegate type is used as a 'wrapper' with
which to pass around methods.

For example, it seems strange to me that a call to a delegate's GetInvocationList() returns an array of delegates. Shouldn't there be something else with which to wrap methods?

I expected there would be some other construct/type, say, MethodContainer which wraps methods. Then the syntax for adding methods to a delegate would be

```<code>class MyClass{ void Method(string s){} }

MyClass c = new MyClass();
MethodContainer container = new MethodContainer(c.Method);

delegate void MyDelegate(string s);
MyDelegate d = new MyDelegate();

d.Add(container);

d.GetInvocationList(); // returns array of MethodContainer
</code>```

答:
You are right it is a bit confusing.

In the initial .net design, a Delegate was supposed to be a 'method reference' to a single target method, and a MulticastDelegate was supposed to be a container which could contain a variable number of delegates, and invoke them as a batch.

However, before the release of .net 1.0 it was decided to merge the functionality of Delegate and MulticastDelegate, so that every delegate is actually an instance of MulticastDelegate, regardless whether it has one or multiple targets. Apparently it was not possible to clean up the API after this change, so we now have a somewhat confusing API.

For example, a delegate has the Target property which has a reference to the method to invoke. But in case of a delegate with multiple targets, this property just returns a random one of the targets.

The method GetInvocationList() is confusing for the same reason. It is supposed to return an array of all the targets in a delegate. Since there is not a separate type for single-target delegates, it has to return an array of MulticastDelegates, one MulticastDelegate for each target. In the case of a single-target delegate it just returns an array with one element which is the original delegate itself.

Title: Understanding C# Delegates Structure

ContentLicense: CC BY-SA 4.0


问:
Can you program Android Apps in a functional language?
Can you program Android Apps in  a functional language?

I meant is it possible to program for Android in a language that was designed from the ground up to be functional? I'm aware that you can use the functional components of an OO or a procedural language to program in a functional style, I was asking whether it would be applicable to use one of the "functional languages" on Android.

答:
Yes, you can build Android apps in most (all?) of the languages that can compile down to byte code (JRuby, Scala, Clojure, ...), but the performance is not what you are used to on the Java VM. Dalvik is a different beast, and the various implementations have had to do quite a bit of changes to come up with a decent speed.

Clojure is now quite performant on Android (after 5 years), but is still suffering from the same slow startup times as the other scripted languages (like JRuby). Lean Clojure is doing something about this, though.

A commenter mentioned F#, and that is actually a viable option, but a costly one if you are a single developer. The reason being that this usually means developing using Tamarin Studio, a great, but proprietary IDE that compiles .NET apps into native versions for Android and iOS.


问:
JS Asynchronous Load Pattern
This is a specific problem but I believe the pattern here may be general enough to be useful to the audience here.

I'm working on an offline JS application. In my JS application, I would like to run programmatically generated reports. No problem. I can render to canvas and then convert to pdf (oh the wonders of JS libraries these days). But there's one nagging problem: image rendering.

I do not know (and in some cases, cannot know) the images necessary to load until the report is being generated. I have access to the images encoded in Base 64, so they are not remote and are more or less guaranteed to load. However, loading an image is not guaranteed to be synchronous - even for an already in-memory string. Additionally, it is not possible to say "I'll just draw the picture once loaded" because painting order matters. Right now I'm resorting to pre-loading my whole image library (yuck!), but about the only other method I can see to make this work is a refactor to have a "gather resources" pre-step per report instance and some very not fun callback work. I can't load resources upfront (other than my current method) because resources aren't known at startup time, which seems to partially rule out the usual AMD approach.

Sigh - I wish in-memory resources loaded synchronously. So do I just need to buckle down and make the refactor or is there a better way?

答:
Regular html image tags hard coded on the page, but do not give them an src attribute.

after everything on the page is loaded, use jquery and add an src attribute to each image tag you want, and it will automatically go out and grab that image.

write some code to figure out what image you want based on what has loaded, then

```<code>$(document).ready(function () {
 $('#somethingunique').attr('src', 'urlOfTheDesiredImage');
});
</code>```

Title: JS Asynchronous Load Pattern

Body:
Regular html image tags hard coded on the page, but do not give them an src attribute.

after everything on the page is loaded, use jquery and add an src attribute to each image tag you want, and it will automatically go out and grab that image.

write some code to figure out what image you want based on what has loaded, then

$(document).ready(function () {
 $('#somethingunique').attr('src', 'urlOfTheDesiredImage');
});


问:
How to use DataMapper pattern methods, when loading data from database?
How do I use DataMapper Pattern?  I can use it as a glorified Database Access Object, aka TableGateway (loading a single class from a single database table), or I can use it more to drive business concerns (i.e. load complex objects from many DB tables).  Or mix both?

Example

Suppose that in my business application I have a Product and a Motor entities.  Sometimes I need just one and sometimes just the other.  But sometimes I need a structure where a motor belongs to a product.  (Product owns the Motor), and I need to load both, and I can create and use a single function of my DataMapper to do that.

Business-Oriented Naming/Structure

$products = new ProductDataMapper();

//This is the business-relevant construct, loading a complex object
$product = $products->getProductWithMotor(1, 2);//ids

echo $product->getName();  //"Product with id 1"
echo $product->getMotor()->getName();  //"Motor with id 2"
```

<p><strong><code>TableGateway</code> Naming/Structure</strong></p>

```$products = new ProductDataMapper();
//just loading an object by id, no specific business meaning
$product = $products->findById(1);

$motors = new MotorDataMapper();
//just loading an object by id
$motor = $motors->getMotor(2);

//business-relevant line (Product owns the Motor)
//that was hidden away inside the getProductWithMotor above,
//now inside some business layer
$product->setMotor($motor);

echo $product->getName();  //"Product with id 1"
echo $product->getMotor()->getName();  //"Motor with id 2"
```

Question

My question deals with "What was/is the intent of use of DataMapper pattern?"

Is there intent to use as a business layer (namely load business-relevant objects with DataMapper functions creating complex business-relevant objects), or is it purely intended to do simple Create/Update/Delete/Insert functions and is to disconnect itself from creating business-relevant-objects, leaving that to some business functionality layer?

答:
Since a data mapper should have a single responsibility, it should only map the results of the query to an object or object(s) and return that back to the caller.

In your case we have:

Product

Motor

So, I think one would definately have mappers for those objects defined.

I beleive your choices for mapping product and motors are:

Composition.  Products, can have a list or array or motors, so it could be handled via composition.  You could return back a list of motors back and then simply add those motors to the product outside the mapper.

Another object called ProductMotor.  The mapper maps to an object called ProductMotor and returns back an object of that type.

Either option could be acceptable depending on system usage and layout.

Based on your comments below a query with a join could return the motor and product information on one data record, some psuedo code:

```<code>Public Product MapProduct(IRecord record)
{
    var product = new Product();
    product.Name = record["name"].ToString();
    //And so forth...
    product.Motor = MapMotor(record);
    return product;
}

Public Motor MapMotor(IRecord record)
{
    var motor= new Motor();
    motor.Name = record["name"].ToString();
    //And so forth...
    return motor;
}
</code>```

Body:
Since a data mapper should have a single responsibility, it should only map the results of the query to an object or object(s) and return that back to the caller.

In your case we have:

Product

Motor

So, I think one would definately have mappers for those objects defined.

I beleive your choices for mapping product and motors are:

Composition.  Products, can have a list or array or motors, so it could be handled via composition.  You could return back a list of motors back and then simply add those motors to the product outside the mapper.

Another object called ProductMotor.  The mapper maps to an object called ProductMotor and returns back an object of that type.

Either option could be acceptable depending on system usage and layout.

Based on your comments below a query with a join could return the motor and product information on one data record, some psuedo code:

Public Product MapProduct(IRecord record)
{
    var product = new Product();
    product.Name = record["name"].ToString();
    //And so forth...
    product.Motor = MapMotor(record);
    return product;
}

Public Motor MapMotor(IRecord record)
{
    var motor= new Motor();
    motor.Name = record["name"].ToString();
    //And so forth...
    return motor;
}


问:
User and role modeling
I'm working with a system in ASP.NET MVC, with Entity Framework for ORM. The application has a requirements to allow users to have different types of roles, and authorization rules will be different for each role (.e.g. user with role A will be able to see some pages, role B will see some different pages)

In most of the systems that I work with before, this user and role relation will be modeled as:

```<code>public class User
{
    //Omitted properties
    public List<Role> Roles { get; set; }
}

public class Role
{
    //Omitted properties
}
</code>```

However in this system, there are some other requirements that require user to have different properties based on different roles, .e.g. role A user will have property A + B, role B user will have property C + D. Each user, regardless of which role it has, is still be identified by a common id (Active Directory user id). And there might be a situation where an user has more than one role

I'm wondering what's the best way to model this relation. I think of some ways but haven't found one that is good enough:

Approach 1: Each user has a profile that contains properties that are different from role to role:

```<code>public class User
{
    //Omitted properties
    public List<Role> Roles { get; set; }
    public List<UserProfile> Profile { get; set; }
}

public abstract class UserProfile
{
    //Common properties
}

public class RoleAUserProfile : UserProfile
{
    //Omitted properties
}

public class RoleBUserProfile : UserProfile
{
    //Omitted properties
}

public class Role
{
    //Omitted properties
}
</code>```

Problems: difficult to model with EF code first fluent api. I setup with table splitting approach but always have problem with abstract UserProfile and key. Also list of user profiles in User is not clear. When I want to get data for a specific role, need to loop through the list, check one by one

Approach 2: Different user class for different type of role:

```<code>public class User
{
    //Omitted properties
    public List<Role> Roles { get; set; }
}

public class RoleAUser : User
{
    //Omitted properties
}

public class RoleBUser : User
{
    //Omitted properties
}

public class Role
{
    //Omitted properties
}
</code>```

Problems: cannot handle case one user multiple roles. Also the inheritance relationship seems awkward to me

Approach 3: Put everything in one User class:

```<code>public class User
{
    //Omitted properties

    //Role A properties

    //Role B properties

    public List<Role> Roles { get; set; }
}

public class Role
{
    //Omitted properties
}
</code>```

Problems: difficult to maintain when number of properties for each role is large, difficult to use (need to know what properties belong to which roles to use correctly)

Approach 4: Similar to approach 1 but instead of creating new UserProfile, put data directly into different role class itself. Seem awkward to me

Any suggestion to how to model this situation? Maybe I over-complicate things but I haven't found any satisfying solution yet.

答:
What are those role-dependent attributes? That's strange for users to have different sets of attributes, since they can change roles in a blink. What will you do with the attributes from role A when user no longer has the role? Delete them? What if tomorrow that user will change his role back to A?

So, one approach is to maintain a single overly-bloated user profile with all possible user data. Unused data is null.

The second approach I see is to create Role objects for each users separately and store role-dependent attributes in those Role objects. As for database storage, you can put them into pivot table of User-To-Role relation.

Is that suitable for you?

Title: User and role modeling


问:
When to use single-line if statements?
When reviewing code, I prefer to read if statements that explicitly demonstrate that a fork in code execution may occur:

```<code>if ( isFoo(baz) ) {
    runBar();
}
</code>```

When scanning hundreds of lines of the nonindented version, it is not obvious that a conditional may or may not occur:

```<code>boom += 1;
baz = getBaz(boom);
if (isFoo(baz)) runBar();
boing = boom + baz;
</code>```

So when is it considered all right to single-line if statements? I'm willing to put up with it if the conditional is on a die(), return, or exception, because in those cases at least the current method ends.

```<code>if (isFoo(baz)) die("No more foo!");
</code>```

Are there any other "good" uses for single-line if statements? How strictly should the practice be avoided? Note that I am explicitly asking about the lack of an indented line to indicate that a condition may or may not occur, I am not asking about the use of braces. Although I would appreciate all opinions in the comments, answers should address objective reasoning, such as maintainability or extensibility of code.

This is not a dupe of Single statement if block - braces or no because this question does not ask about braces. This is not a dupe of Single Line Statements & Good Practices because that question does not address the crux of this question: the ability to determine that some lines of code may or may not be run, thus leading to divergent code paths.

答:
I would propose an alternative answer. I prefer single liners when the condition inside is really a single line and is relatively isolated from the rest of the conditions.

One great example is:

```<code>public void DoSomething(int something) {
     // Notice how easily we can state in one line that we should exit the method if our int is 0.
     if(something == 0) return;

     CallAnotherMethodHere(something);
}
</code>```

A bad example(in my opinion) would be what @gbjbaanb mentioned:

```<code>if (a) do_a();
if (b) do_b();
if (c) do_c();
</code>```

To me, this is a switch statement and should be written as such:

```<code>switch(something) {
    case "a":
        do_something_to_a();
        break;
    case "b":
        do_something_to_b();
        break;
    case "c":
        do_something_to_c();
        break;
    default:
        break;
}
</code>```

Much more readable IMHO and more efficient as variable needs to be evaluated only once VS running through all the if statements although gains are negligible.

Title: When to use single-line if statements?

Body:
I would propose an alternative answer. I prefer single liners when the condition inside is really a single line and is relatively isolated from the rest of the conditions.

One great example is:

public void DoSomething(int something) {
     // Notice how easily we can state in one line that we should exit the method if our int is 0.
     if(something == 0) return;

     CallAnotherMethodHere(something);
}

A bad example(in my opinion) would be what @gbjbaanb mentioned:

if (a) do_a();
if (b) do_b();
if (c) do_c();

To me, this is a switch statement and should be written as such:

switch(something) {
    case "a":
        do_something_to_a();
        break;
    case "b":
        do_something_to_b();
        break;
    case "c":
        do_something_to_c();
        break;
    default:
        break;
}

Much more readable IMHO and more efficient as variable needs to be evaluated only once VS running through all the if statements although gains are negligible.


问:
Approaches for storing and analysing large amounts of time-based data
I've been asked to develop a "telemetry" application that records data generated by a hardware device, which I read every 100ms.

There are approx 250 data points (32-bit values), but only a subset of these (say 30-50) will be returned by each 100ms read, so it will take several reads before I've got all 250 data points. Out of the data point values read, only a small number are likely to have changed since those same data points were last read - some change every 100ms, others perhaps every few seconds, while others very infrequently (or even never).

The main requirements for the system are:-

The ability to plot one or more data points over time, at 100ms resolution

The ability to view the values of all 250 data points at a particular point in time

The application needs to store the last 60 hours worth of data

I'm looking for some thoughts on how best to tackle this, particularly how to store the data in a way that supports the required reporting. So far I'm veering towards this idea:-

I maintain a "dictionary" of all 250 data points, updating the values after each read. Every 100ms I would write all 250 values to my data store. It's easy to implement and easy to query the data to satisfy the requirements. The downside is that it's not a particularly efficient use of storage (but hey - disk space is cheap nowadays).

Alternatively, ever 100ms, I could store only values that have changed since they were last read, however this becomes more difficult to implement, especially when it comes to querying. E.g. for requirement #2, I would have to construct a "snapshot" by traversing back through the data from the required point in time, looking for each data point's last stored value.

Now I've written all this out I think I've answered my own question. The "write everything" approach seems to be a no-brainer. However I've had no experience of this kind of mass data storage and analysis so I would be interested to hear what others think.

答:
I would write everything, and then have a scheduled job to erase unchanged values and only have the points where data changes.

Like so:

```<code>Before:    After:
A B C D    A B C D
0 0 0 0    0 0 0 0
0 0 1 0    0 0 1 0
1 1 2 2    1 1 2 2
2 2 2 2    2 2 2 2
2 2 2 2    2 3 2 2
2 2 2 2
2 3 2 2
</code>```

Body:
I would write everything, and then have a scheduled job to erase unchanged values and only have the points where data changes.

Like so:

Before:    After:
A B C D    A B C D
0 0 0 0    0 0 0 0
0 0 1 0    0 0 1 0
1 1 2 2    1 1 2 2
2 2 2 2    2 2 2 2
2 2 2 2    2 3 2 2
2 2 2 2
2 3 2 2


问:
Good idea to include test logs in software repository?
I have written a software in python with unit tests and system tests together with an other developer. The software is version controlled with git. Before we merge branches, we ensure that the branches pass the tests, so conflicts after merge is only related to merge.

Is it a good idea to version control the test logs as well in software repository?

edit:

Specifically, the test logs are the output of the test executions; list of all the tests and if they passed or failed.

The tests are all automated, so no user interaction is needed to execute the tests.

答: No, not a good idea. Source Control is named that way because it contains source, not the compiled result, or test output in your example. Test logs are temporary files that are used only to debug tests, and thus should not be present in the source control.</p>


问:
How Add/Create* commands should be handled in CQRS + Event Sourcing architecture
I want to implement my first application using CQRS pattern along with Event Sourcing. I am wondering how creation of aggregate roots should be handled properly. Let's say someone sends CreateItem command. How it should be handled? Where the event ItemCreated should be stored? As first event of a new Item? Or should I have some kind of ItemList entity that aggregates all items and its event list consists only of ItemCreated events?

Udi Dahan suggests not to create aggregate roots and always use instead some kind of fetch method. But how I can fetch something that is new and certainly does not have any ID assigned. I understand the idea behind and it is pretty reasonable to think that a new object is an object that has its state composed of zero events replied on it. But how should I use it? Should I have a distinct method in my Repository like getNewItem() or make my get(id) method accepting Optional<ItemId> instead?

Edit: After some time of digging I found really interesting implementation of the aforementioned patterns using actors. The author instead of creating the aggregate, retrieves it from some kind of repository with newly created UUID. The drawback of this approach is he allows for a temporary inconsistency state. I am also wondering how I can implement delete method with such approach. Simply add Deleted event to the event list of the aggregate?

答:
The idea in Udi's post, as I gather, is that no kind of item appears out of thin air. There is (almost) always something, or more specifically, some domain operation, which caused the item to be created. Just like Udi's example of a user actually being born out of a visitor registering to the site. At that point and at that bounded context Visitor is the aggregate root, which is retrieved by his IP address. This Visitor then creates the new "item", a user at this point, through a domain operation called Register. Same goes for the step before, which is another bounded context: Referrer is the AR, which is retrieved by the URL and that has a domain operation called BroughtVisitorWithIp, where the visitor is born.

Udi writes very nicely on deletion as well: http://www.udidahan.com/2009/09/01/dont-delete-just-dont/. Main idea is, that you don't delete anything, ever. There's always a domain operation behind, which we want to capture. Like an order being cancelled, rather than deleted. Read it, it's a very good post.

The main point here on both accounts, doing DDD and especially Event Sourcing, is that you should never do straight CRUD-operations. If you find yourself in a situation where you really need to just insert, update or delete some data, and there truly is no domain operation behind it, then maybe DDD and Event Sourcing is not a good fit for that bounded context. You are free to combine these two as you wish as long as a single bounded context adheres to one principle. This way the CRUD-style bounded context might create some row in the database, that becomes an entity and an Aggregate root in another bounded context, where you now can retrieve the AR and not have to create it.


问:
Separation of concerns between repository and service in DDD with complex entities
This probably seems as an example of opinion-based question, but I'm actually looking for rationale on how to decide correctly, I believe there is a correct solution that can be backed by solid arguments (that's why I chose SO and hope is really not only opinion based, but I can be wrong; if you'd feel so, please leave a note in a comment). I can't decode how far to go with SoC in DDD and whether is ok to have mostly empty domain objects.

We have .NET, DDD, mainly use EF as our ORM in repositories, our application lives in Azure. For complex queries, we use stored procedures that return multisets (because of Azure SQL) - so one query = one round trip to the server (is's worth it, the query is performed usually on > 10 separate tables, no joins, so it would require many round trips).

For simplicity, imagine domain object called NavigationItem, that have multiple titles (in different languages), items are stored in one table, localized titles are stored in another table, where foreign key is the item title contains culture id.

The navigation object might look like this:

```<code>public class NavigationItem
{
    public int FileRecordId { get; set; }

    public int? ParentId { get; set; }

...

    public Dictionary<int, string> Title { get; set; }
}
</code>```

So the domain object, returned by repository, is constructed (in repository) this way:

```<code>// load list of navigation items
var reader = command.ExecuteReader();
navigation.Items = ((IObjectContextAdapter)_context).ObjectContext.Translate<NavigationItem>(reader).ToList();

// process localized titles
reader.NextResult();
var titles = ((IObjectContextAdapter)_context).ObjectContext.Translate<TitleInfo>(reader).ToList();

// associate titles, so the whole NavigationItem is constructed
foreach (var item in navigation.Items)
{
    item.Title = titles.Where(t => t.FileRecordId == item.FileRecordId).ToDictionary(key => key.CultureId, value => value.Title);
}
</code>```

This is simple example, just to get the point - my question is, wouldn't it be better to return just list of navigation items (where I should omit the Title property) and list of titles and combine that in a service layer, when creating DTD object? Repository is responsible for persistence and retrieving persisted data, and I'm not sure, whether this is simply "too much". On the other hand, the requirement on repository might be just "give me whole entity with titles". Separation of concerns is naturally a good way, but I'm not sure if this is still concern of the repository.

Please take this just as a simple example, my question is more general - in this example, each domain object NavigationItem contains Title, so it feels it's OK to do this in repository. But when we have more complex etities, there is another problem - e.g., each File has common properties, like Name. Some files have image properties, same have also pdf document properties, some have localized titles... some don't. In this case, it seems much more "natural" to have one entity (common File), and return List, List, List, ... from repository and combine it in the service. Or on the other hand, do all the translation in repository, but it would mean that domain object (aggregate root) File will contain entities like ImageInfo, TitleInfo, etc., which will be in most cases null.

What approach - and mainly, why - would you recommend?

EDIT: To be more specific - from DDD perspective, is it ok keep Entity partially empty and sometimes in repository just retrieve few properties (or sometimes all of them), or is better approach to separate such entity to smaller ones and return one entity that aggregates lists of all possible entities? I believe that there can be reasonable answer, typically "yes, partly initialized entity is ok", or "no, it's wrong and you should always use as granular entities as possible", etc.

答:
Sounds like you are using domain entities for both domain operations (commands, which modify application state) and queries (which don't modify application state, but return data for the user). The problems you describe are a direct result of trying to get that single domain entity to do both jobs, which don't mix very well.

My recommendation is to read on CQRS (Command Query Responsibility Segragation) e.g. CQRS by Martin Fowler and try to limit your domain entities to only retrieve what data they need to complete the domain operation. Even though the amount of classes and interfaces will grow, your application will become much more simple and more maintainable due to more adherence to the Single Responsibility Principle.

Also, your choice of domain objects and especially Aggregate roots leads me to question the validity of your domain model. Is a File really such an entity, that it's of dire meaning to the business people? What kind of operations do you do on the file, and what's their value to the business? The whole idea in Domain Driven Design is to identify the actual business entities on which you should act, as if you wouldn't have a computer at all. An Order is a common example. Operations on that Aggragate root would be "Submit", "Cancel" etc. File is just an infrastructural concern, which most often has no value or place in the domain logic.

OwnerDisplayName: Robert Goldwein


问:
Should I use a source-to-source or a traditional compiler in order to develop my own Programming Language?
I'm really interested in writing my own general-purpose high-level programming language, but I'm somewhat confused.

I know that Python and Ruby were written in C, which makes me wonder that if I want to write my 'own Python', is it preferable to use a source-to-source compiler in order to translate all the source code of my language to C, or should I target assembly language?

The point is, I know that I need to dig in Compiler Design and understand Lexical Analysis, and the whole process of parsing the code and generating tokens and an intermediate language and checking for syntax and semantic errors and then generating output code.

However, since I'm not an expert in low level / assembly programming, should I use a source-to-source compiler? What challenges might I face if I attempt to compile my language to assembly? What drawbacks might there be in using a source-to-source compiler? What domain specific facets of my situation should I consider when making this decision?

答:
"I'm really interested in writing my own general-purpose high-level programming language" Are you really? If you are truly interested and want to create your own language complete with a (native) compiler for the experience you would probably be interested on reading up on assembly and how the CPU works, you can examine the assembly output of existing high level languages to give you an idea.

A source to native machine code compiler gives you a lot more freedom to define your language's semantics, if you compile to C you are basically limited to the C way of doing things, so in the end features you may want to include such as proper tail calls will be out of your reach. Building a native compiler is also likely to be a more rewarding and enlightening experience, whereas compiling to C you are basically using something somebody else built C is a very complicated language for something to output to (it's syntax is designed to be good for humans to write not easy for machines to generate), you have to worry about nesting order of declarations, making sure you specify enough information to allow the C compiler to optimize your code effectively (e.g. using restrict when there is no aliasing of pointers).

If you're pragmatic and want to build a language which is going to be used in the near future and you're not really interested in building the compiler as much having a working compiler for your language then source to source is the way to go, however be aware that your language effectively becomes a preprocessor (in-fact a preprocessor is good place to start learning about lexical analysis and parsing). Either way if your goal is to distribute your language try to avoid it becoming a JAP language (Just another programming language) that is a language which offers nothing new and isn't a major improvement over existing languages.


问:
Which algorithm to find the shortest (nodes count) path that encompasses all polygons inside a larger polygon?
Inside a large polygon (say the USA boundaries) I need to find the shortest path that will encompass smaller polygons

(say the following cities: Kansas city, St Louis, Memphis, Oklahoma City)

By shortest I mean with the less nodes as possible. (then will the smaller inner surface)

A 'not-that-bad' result will be the bounding rectangle that comprises the 4 cities

A better one will be a triangle (3 nodes < 4) New York, San Antonio, Seattle

An even better would be the triangle Minneapolis, Louisville, El Paso because surface is less than previous one

Exemple For non US

imagine a large rectangle 0,0 => 1000,1000

inside 4 points 490,490 ; 490,510 ; 510,510 ; 510,490

a good result : rectangle 490,490 => 510,510

a better result : large triangle 490,0 490,490 1000,490

an even better : small triangle 490,490 ; 530,490 490,530

Is there a well known algorithm for this ?

答:
You say, "encompass smaller polygons," but then you seem to treat these polygons as points.
If they are indeed effectively points, as opposed to extended polygons, then
you are seeking to solve the Traveling Salesman Problem, or TSP, which is a
heavily studied (and difficult) problem.

Your instance is not a pure TSP, because you have a bounding, constraining polygon.
This version is
known in the literature as the geodesic convex hull inside a polygon.
There is a paper by Toussaint on this topic that I cannot identify at the moment, but maybe these terms could help your search.


问:
Artificial intelligence decision making
So I am working on a artificial intelligent assistant that is supposed to help you making correct decision when playing the game domino.
Basic rules: http://www.pagat.com/tile/wdom/caribbean.html

As this game has several rules and several different ways you can play a domino to ultimately win the game. Now the question becomes what is the best way to determine what domino is the best domino to be played?

Extremely large else if statements nested and what not? or a ranking based system?

答:
The simplest thing to do is write a function that takes a board state and gives you back a score for that board state.  You then enumerate over all of the possible boards and chose the best one.  That's really at the heart of it.

Consider the game tic-tac-toe for a moment.  Lets consider the person scoring 1 point for each X in a row, column, or diagonal and -1 point point for each O in a row, column, or diagonal (and rows or diagonals with at least one X and O are also scored as 0).

```<code> X |   |     ||  X |   | X   ||  X | X |    ||  X |   |
---+---+---  || ---+---+---  || ---+---+--- || ---+---+---
   | O |     ||    | O |     ||    | O |    ||    | O | X
---+---+---  || ---+---+---  || ---+---+--- || ---+---+---
   |   | X   ||    |   |     ||    |   |    ||    |   |
Score: 1     || Score: 1     || Score: 1    || Score: 1
</code>```

I won't claim that this is the best heuristic for tic-tac-toe, but you get the idea of the idea of a function to evaluate the board state.

That's really at the heart of the game.  Here are two boards - which one is 'better'.  Better could be a "how many moves from a potential win" or "which has more winning possibilities" or any number of other position evaluation functions.

In a game where there is the ability to guess at the next play of the opponent, you get into writing a minimax tree where you try to decide upon the move that still gives you best evaluation for you after your opponent has made the one that is the worst for you.  This isn't a small topic, as noted there is a fairly good sized wikipedia page on it with 13 other pages in the see and many external links and references. This is a fairly big area of game theory - and if you want to explore that it is the subject of books, multiple college lectures and papers resulting in something too large to reasonably answer here.

Title: Artificial intelligence decision making

Body:
The simplest thing to do is write a function that takes a board state and gives you back a score for that board state.  You then enumerate over all of the possible boards and chose the best one.  That's really at the heart of it.

Consider the game tic-tac-toe for a moment.  Lets consider the person scoring 1 point for each X in a row, column, or diagonal and -1 point point for each O in a row, column, or diagonal (and rows or diagonals with at least one X and O are also scored as 0).

 X |   |     ||  X |   | X   ||  X | X |    ||  X |   |
---+---+---  || ---+---+---  || ---+---+--- || ---+---+---
   | O |     ||    | O |     ||    | O |    ||    | O | X
---+---+---  || ---+---+---  || ---+---+--- || ---+---+---
   |   | X   ||    |   |     ||    |   |    ||    |   |
Score: 1     || Score: 1     || Score: 1    || Score: 1

I won't claim that this is the best heuristic for tic-tac-toe, but you get the idea of the idea of a function to evaluate the board state.

That's really at the heart of the game.  Here are two boards - which one is 'better'.  Better could be a "how many moves from a potential win" or "which has more winning possibilities" or any number of other position evaluation functions.

In a game where there is the ability to guess at the next play of the opponent, you get into writing a minimax tree where you try to decide upon the move that still gives you best evaluation for you after your opponent has made the one that is the worst for you.  This isn't a small topic, as noted there is a fairly good sized wikipedia page on it with 13 other pages in the see and many external links and references. This is a fairly big area of game theory - and if you want to explore that it is the subject of books, multiple college lectures and papers resulting in something too large to reasonably answer here.


问:
Templating a member name
I'm writing a library that provides graphs for search algorithms.

Usually you want to rank nodes using a priority queue.
Normally you want to search for an specific node in the queue and lower its key (when you find a better path to it).

Searching would be O(n) unless you know the index of the node (you can add it to the node structure). Adding the index to the Node requires that the queue is able to update the index when needed.

I'm having trouble writing a generic priority queue, because I need to know where to read and write the index of a node on this queue. Is there a way to do it?

The code might look like this

```<code>class SomeNode : Node {
 int indexA;
 int indexB;
}

template <typename N, ?? indexMember>
class Heap{
  update(N node, int key){
    //...
    node.indexMember = i;
  }
}

Heap<SomeNode, 'indexA'> heapA(cmp_A());
Heap<SomeNode, 'indexB'> heapB(cmp_B());
</code>```

I'm asking here because I think that the design may need some rework rather than a probably missing feature

答:
Following the StackOverflow Question suggested by Thomas, the answer should look like this:</p>

```<code>class SomeNode : Node {
 int indexA;
 int indexB;
}

template <typename N, int (N::*indexMember)>  // Note the *
class Heap{
  update(N node, int key){
    //...
    node.*indexMember = i;  // Also here
  }
}

Heap<SomeNode, &SomeNode::indexA> heapA(cmp_A());  // Note the ref to the member
Heap<SomeNode, &SomeNode::indexB> heapB(cmp_B());
</code>```

Title: Templating a member name

Body:
Following the StackOverflow Question suggested by Thomas, the answer should look like this:

class SomeNode : Node {
 int indexA;
 int indexB;
}

template <typename N, int (N::*indexMember)>  // Note the *
class Heap{
  update(N node, int key){
    //...
    node.*indexMember = i;  // Also here
  }
}

Heap<SomeNode, &SomeNode::indexA> heapA(cmp_A());  // Note the ref to the member
Heap<SomeNode, &SomeNode::indexB> heapB(cmp_B());


问:
What exactly is model driven software engineering (MDSE)?
I came accross the accronym MDSE today on infoq, and the information I could find what quite unclear and the description was full of buzzwords :

MDSE is about enabling software engineers to work at a level of abstraction where requirements, architecture and design information is maximally ordered (in terms of information "entropy") and preserved. (Call this the "design work product"). Further, MDSE should provide engineers with the means to verify and validate their designs primarily terms of their "design work product"

And apparently, everyone is doing it: (from the article again)

We’re at the dawning of the age of MDSE. In the next 5 – 10 years we will see a significant shift towards MDSE, to the extent that I believe that by the end of this period perhaps 60 – 80% of software will be designed using model based techniques.

I would like to have a concrete, buzzword-free description of what MDSE is. Is it drawing UML boxes and generating code with it, like they did in the 90s with Rational Rose?

(while were at it, if anyone has an example of software generated using those techniques, I would really like to see a concrete example).

答:
This reminds me a lot of Fat models, skinny controllers concept.

The main idea of this concept is to put as much of the business logic as possible into the model and keep the controller and a view very simplistic.

Personally, I find this a very interesting idea, though I haven't had a chance to use it.

Surprisingly, 8 out of 10 top links in google search speak against it.
But, if you think of a model not as a single class, but a facade of multiple internal classes it makes perfect sense to keep the business logic in the model.


问:
Using delegates to avoid duplicate creation of resources
I'm writing a PCL that uses an HttpClient to go visit a few sites and extract data from them. My initial code looked like this:

```<code>public static class Download
{
    public async static Task<byte[]> FromYouTubeAsync(string videoUri)
    {
        using (var client = new HttpClient())
        {
            string source = await client
                .GetStringAsync(videoUri);

            // get links...

            return await client
                .GetByteArrayAsync(links.First());
        }
    }
}
</code>```

I realized, however, that this would be a waste of resources if the user of my library already had a HttpClient in hand. For example:

```<code>// Caller code
using (var client = new HttpClient())
{
    // Do some work with client

    byte[] bytes = await Download.FromYouTubeAsync("some://uri"); // A second HttpClient is created here, wasting resources and time...

    // Do some work with client and bytes
}
</code>```

One solution could be to add an overload taking an HttpClient as a parameter, but what if the user wanted to use a WebClient instead? Or an HttpWebRequest? Or some other kind of client that wasn't availsble in the PCL?

My solution

I decided to take delegate parameters to get the page source and to download the file based on the URI. My code now looks like this:

```<code>public static class Download
{
    public async static Task<byte[]> FromYouTubeAsync(string videoUri)
    {
        using (var client = new HttpClient())
        {
            return await FromYouTubeAsync(
                () => client
                .GetStringAsync(videoUri),
                uri => client
                .GetByteArrayAsync(uri));
        }
    }

    public async static Task<byte[]> FromYouTubeAsync(
        Func<Task<string>> sourceFactory, Func<string, Task<byte[]>> downloadFactory)
    {
        string source = await sourceFactory();

        // get links...

        return await downloadFactory(links.First());
    }
}
</code>```

The problem

Hm. Wait, what if the caller is using a client that doesn't support async, like HttpWebRequest? Better add another overload taking a Func<string> and a Func<string, byte[]>. What if s/he wants to make the first call synchronous, but the second call async? Or vice versa? OK, just add 2 more overloads. Wait, what if the caller wants the whole operation to be synchronous? Let's go add 4 Download.FromYouTube overloads wrapping each of the async methods. Whoops, it turns out we need to visit another page of YouTube in case the video's signature is encrypted! Sure, let's go add 8 mor-

I think you can see where this is going. How do I maintain this flexibility without scaring the user away when Visual Studio says that there are 17 different overloads for this method?

答:
Your first argument regarding reuse of the HttpClient makes perfect sense.

As for the rest of of the requests, I think you're trying to optimize prematurely. That can lead to unnecessary complexity.

Also, I'd like to warn you of using the static classes. This is usually a bad idea. It makes your code harder to test and extend.

Anyways, below is a design that allows the flexibility you want.

Declare an interface.

```<code>public interface IDownloadable
{
    Task<byte[]> FromUriAsync(string videoUri);
}
</code>```

Implement it for HttpClient and allow passing the instance of HttpClient as a constructor parameter.

```<code>public class HttClientpDownloader : IDisposable, IDownloadable
{
    private readonly HttpClient _client;

    public HttClientpDownloader() : this(new HttpClient())
    {

    }
    public HttClientpDownloader(HttpClient client)
    {
        _client = client;
    }

    public void Dispose()
    {
        if (_client == null)
            return;

        _client.Dispose();
    }

    public Task<byte[]> FromUriAsync(string videoUri)
    {
        throw new NotImplementedException();
    }
}
</code>```

As for the rest of your requests, Factory Method design pattern should be able to resolve them. Just implement WebClientDownloader, HttpWebRequestDownloader and whatever else you desire in dedicated classes.

 Same approach can also work for your partially async request. Just implement that logic in a dedicated class. Something like PartiallyAsyncHttpClientDownloader.

```<code>public class DownloaderFactory
{
    public IDownloadable Create(/*pass whatever parameters to make teh decision*/){
        switch (param)
        {
            case '1':
                return new HttClientpDownloader();
            case '2':
                return new WebClientDownloader();
            ...
        }
   }
}
</code>```

Body:
Your first argument regarding reuse of the HttpClient makes perfect sense.

As for the rest of of the requests, I think you're trying to optimize prematurely. That can lead to unnecessary complexity.

Also, I'd like to warn you of using the static classes. This is usually a bad idea. It makes your code harder to test and extend.

Anyways, below is a design that allows the flexibility you want.

Declare an interface.

public interface IDownloadable
{
    Task<byte[]> FromUriAsync(string videoUri);
}

Implement it for HttpClient and allow passing the instance of HttpClient as a constructor parameter.

public class HttClientpDownloader : IDisposable, IDownloadable
{
    private readonly HttpClient _client;

    public HttClientpDownloader() : this(new HttpClient())
    {

    }
    public HttClientpDownloader(HttpClient client)
    {
        _client = client;
    }

    public void Dispose()
    {
        if (_client == null)
            return;

        _client.Dispose();
    }

    public Task<byte[]> FromUriAsync(string videoUri)
    {
        throw new NotImplementedException();
    }
}

As for the rest of your requests, Factory Method design pattern should be able to resolve them. Just implement WebClientDownloader, HttpWebRequestDownloader and whatever else you desire in dedicated classes.

 Same approach can also work for your partially async request. Just implement that logic in a dedicated class. Something like PartiallyAsyncHttpClientDownloader.

public class DownloaderFactory
{
    public IDownloadable Create(/*pass whatever parameters to make teh decision*/){
        switch (param)
        {
            case '1':
                return new HttClientpDownloader();
            case '2':
                return new WebClientDownloader();
            ...
        }
   }
}


问:
Open Source code bounties
I have a library for R (open source statistics package) mapped out on paper. I have started coding the different functions but I realize that I don't have the time needed to finish this in a reasonable amount of time. I know I can just throw the code up on a repo and call for others to help fill in the blanks. But I'd like to incentivize things a bit. I'm thinking about putting a bounty on each function of, say, $5-$20. There's no way that $20 would be a fair return on time for a developer to code each function. But my thought is that the cash (or Amazon gift certificates) would be an inventive for people to actually work on the project. And it would allow me to put higher bounties on the functions I am most interested in.

I have a few questions related to this:

Good idea?

I going to make
the development work faster, or
slower? I've read Predictably
Irrational and I'm concerned
that by offering menial pay for
functions I might actually
disincentive developers.

Are
there sites devoted to this type of
activity? Can you recommend one based on personal experience?

Would you recommend a totally different approach? I'm open to ideas!

答:
I don't think the idea is completely out of the realm of possibility, however the cost per task paradigm doesn't work as it isn't cost effective to the developer, nor proportionally scalable.

I think a better system might be $/Line Of Code where said loc resides in version control for x amount of time and is not committed over for reasons of incompetence (eg. bug).

Title: Open Source code bounties


问:
C# intentionally flickering
i'm currently working on a project which must provide intentionally flickering of some part of UI (white rectangle which must change color to black).

That changing of color must be done at some frequency, let's say 60Hz, which is practically supported on every monitor.

Flickering must follow the input data stream (binary coded, 0 or 1).

Which is the most elegant way to do this in C# (some code example would be useful) ?

答:
I don't think this is possible, unless you use DirectX or OpenGL. None of existing UI frameworks is designed to support this use case. Games, on the other hand are build on the requirement that screen needs to change quickly and so their frameworks are build around that.

My recommendation is to create a DirectX context and drawing area in place of that control and then render it using DirectX. If you are drawing just plain rectangle, then it shouldn't be problem to reach 1000Hz (eg. 1000FPS)

Title: C# intentionally flickering


问:
How to manage the state in a GUI app with Haskell
I am using wxHaskell to create a simple GUI that has typical components like Buttons, Panels, etc.

When some of these components perform an action (like callback), the generic status of the application can change.

To keep the status I am using IORef as a sort of pointer to a generic data structure with all the properties of the status self.

Anyway using IORef as a sort of top level mutable state is generally not considered a good solution based on https://wiki.haskell.org/Top_level_mutable_state. It might be better State/StateT monad.

wxHaskell is a "bind" to an object oriented library (wxWidgets) and using a State monad is hard unless it's "hooked" to the main event loop thread.

What is the best way to manage a generic GUI status with Haskell in a functional programming way?

答:
TL;DR: FRP

The thing that makes this not as trivial as it is in an imperative impure setting is that the state isn't only being modified on our side, the system modifies it too, and in realtime (e.g. when the user moves the window, or even merely moves the cursor). And we can't listen to events and update our values, because they are immutable.

If we were the only ones responsible for the state that just would have been a whole lot easier.

This is what makes people resort to IORefs:  they don't know what to do, and this pattern is the only solution they're familiar with -- it's great in imperative languages, after all. It's kind of easy, and it's really fast, isn't it? (unlike polling for example).

Well, we obviously can't be pure here, GUI is all about side-effects, but we do want to try to remain as pure as much as we can, and we'd even really like to do so with the functional constructs we've grown to love so much (foldables, functors, applicatives, sometimes arrows), and this is pretty much what FRP (Functional Reactive Programming) can do for you.

There are many FRP libraries out there, imo an easy one is reactive-banana.

I can't think of anything more idiomatic, however if that's an overkill, top-level mutable state shouldn't really be the answer. I'd keep the state, either directly in main, or group it in datatypes (with IORef fields) if there are too many and it becomes an IO zoo.

Tip: I haven't tried it, but I think FRP with a lens library can make state management incredibly easy.


问:
Joshua Bloch Enum Singleton and Third Party APIs
In the book Effective Java he give the best Singleton pattern implementation in his, that is implement by a Enum. I have doubt to how to implement this pattern with a third party API.

I'm using an third party API that provides an interface IRCApi that has a lot of methods like:

```<code>public interface IRCApi{
    void connect();
    void disconnect();
    void disconnect(String aQuitMessage);
    void joinChannel(String aChannelName);
    //...
}
</code>```

My question: Is the code snippet below a valid implementation of that design pattern with all benefits cited by Joshua Bloch (multi thread support, facility to change, etc):

```<code>public enum IRCApiSingleton {
    INSTANCE;

    private final IRCApi ircApi = new IRCApiImpl(false);

    public final IRCApi get() {
        return ircApi;
    }
}
</code>```

using this way:
    IRCApiSingleton.get().connect();

Or do I have to make my enum implement IRCApi and encapsulate all methods of an IRCApi implementation (there are about 40 methods), like:

```<code>public enum IRCApiSingleton implements IRCApi {
    INSTANCE {
        private IRCApi impl = new IRCApiImpl(true);
        @Override
        public void connect() {
            impl.connect();

        }

        @Override
        public void disconnect() {
            impl.disconnect();
        }
        //...
    };
}
</code>```

and use the INSTANCE directly?

答:
Well, as I see it, IRCApiImpl has a public constructor making it difficult to call either way a "classical singleton".

Still, I'd say that if you follow the guideline of not creating another instance of IRCApiImpl at any other point or even better, making the class inaccessable, you can use either implementation.

From a strict Software-Engineering point of view, the first implementation would be preferable, because It would allow less coupling and would not need to be changed when the API of IRCApiImpl changed.

Personally though I'd prefer the second implementation, which saves you the .get() on every call.


答:
I'd take a step back and ask yourself why you are trying to create a singleton in the first place. Don't get me wrong, I know there's a lot of people hating on singleton, and I think a lot of that hate is unwarranted. That said, it doesn't seem like your singleton is providing any functionality except acting as a global constant to IRCApiImpl.

If you had declared IRCApiImpl as an enum (or equivalently, taken all the code in IRCApiImpl and placed it inside of IRCApiSingleton), then I'd think you'd be applying Joshua Bloch's pattern correctly.

But given that not only have you not done that, but IRCApiImpl seems to have a constructor taking a parameter (implying that there could be multiple instances of it, each one taking on a different set of parameters when they got constructed), it sounds like what you're working with isn't a conceptually singleton at all.

If you're trying to use singleton because you want easy access to an object, I'd recommend you look at dependency injection instead.

Title: Joshua Bloch Enum Singleton and Third Party APIs

Body:
In the book Effective Java he give the best Singleton pattern implementation in his, that is implement by a Enum. I have doubt to how to implement this pattern with a third party API.

I'm using an third party API that provides an interface IRCApi that has a lot of methods like:

```<code>public interface IRCApi{
    void connect();
    void disconnect();
    void disconnect(String aQuitMessage);
    void joinChannel(String aChannelName);
    //...
}
</code>```

My question: Is the code snippet below a valid implementation of that design pattern with all benefits cited by Joshua Bloch (multi thread support, facility to change, etc):

```<code>public enum IRCApiSingleton {
    INSTANCE;

    private final IRCApi ircApi = new IRCApiImpl(false);

    public final IRCApi get() {
        return ircApi;
    }
}
</code>```

using this way:
    IRCApiSingleton.get().connect();

Or do I have to make my enum implement IRCApi and encapsulate all methods of an IRCApi implementation (there are about 40 methods), like:

```<code>public enum IRCApiSingleton implements IRCApi {
    INSTANCE {
        private IRCApi impl = new IRCApiImpl(true);
        @Override
        public void connect() {
            impl.connect();

        }

        @Override
        public void disconnect() {
            impl.disconnect();
        }
        //...
    };
}
</code>```

and use the INSTANCE directly?


问:
get weighted random item
I have, for example, this table

```
+-----------------+
| fruit  | weight |
+-----------------+
| apple  |   4    |
| orange |   2    |
| lemon  |   1    |
+-----------------+
```

I need to return a random fruit. But apple should be picked 4 times as frequent as Lemon and 2 times as frequent as orange.

In more general case it should be f(weight) times frequently.

What is a good general algorithm to implement this behavior?

Or maybe there are some ready gems on Ruby? :)

PS

I've implemented current algorithm in Ruby https://github.com/fl00r/pickup

答:
This is a simple Python implementation:

```<code>from random import random

def select(container, weights):
    total_weight = float(sum(weights))
    rel_weight = [w / total_weight for w in weights]

    # Probability for each element
    probs = [sum(rel_weight[:i + 1]) for i in range(len(rel_weight))]

    slot = random()
    for (i, element) in enumerate(container):
        if slot <= probs[i]:
            break

    return element
</code>```

and

```<code>population = ['apple','orange','lemon']
weights = [4, 2, 1]

print select(population, weights)
</code>```

In genetic algorithms this select procedure is called Fitness proportionate selection or Roulette Wheel Selection since:

a proportion of the wheel is assigned to each of the possible selections based on their weight value. This can be achieved by dividing the weight of a selection by the total weight of all the selections, thereby normalizing them to 1.

then a random selection is made similar to how the roulette wheel is rotated.

Typical algorithms have O(N) or O(log N) complexity but you can also do O(1) (e.g. Roulette-wheel selection via stochastic acceptance).

Title: get weighted random item

Body:
This is a simple Python implementation:

from random import random

def select(container, weights):
    total_weight = float(sum(weights))
    rel_weight = [w / total_weight for w in weights]

    # Probability for each element
    probs = [sum(rel_weight[:i + 1]) for i in range(len(rel_weight))]

    slot = random()
    for (i, element) in enumerate(container):
        if slot <= probs[i]:
            break

    return element

and

population = ['apple','orange','lemon']
weights = [4, 2, 1]

print select(population, weights)

In genetic algorithms this select procedure is called Fitness proportionate selection or Roulette Wheel Selection since:

a proportion of the wheel is assigned to each of the possible selections based on their weight value. This can be achieved by dividing the weight of a selection by the total weight of all the selections, thereby normalizing them to 1.

then a random selection is made similar to how the roulette wheel is rotated.

Typical algorithms have O(N) or O(log N) complexity but you can also do O(1) (e.g. Roulette-wheel selection via stochastic acceptance).