问:
RESTFul: state changing actions
I am planning to build a RESTfull API but there are some architectural questions that are creating some problems in my head. Adding backend business logic to clients is an option that I would like to avoid since updating multiple client platforms is hard to maintain in real time when business logic can rapidly change.

Lets say we have article as a resource ( api/article ), how should we implement actions like publish, unpublish, activate or deactivate and so on but to try to keep it as simple as possible?

1) Should we use api/article/{id}/{action} since a lot of backend logic can happen there like pushing to remote locations or change of multiple properties. Probably the hardest thing here is that we need to send all article data back to API for updating and multiuser work could not be implemented. For instance editor could send 5 seconds older data and overwrite fix that some other journalist just did 2 seconds ago and there is no way that I could explain to clients this since those publishing an article is really not in any way connected to updating the content.

2) Creating new resource can also be an option, api/article-{action}/id , but then returned resource would not be article-{action} but article which I am not sure if this is proper. Also in server side code article class is handling actuall work on both resource and I'm not sure if this goes against RESTfull thinking

Any suggestions are welcomed..

答:
I find the practices described here to be helpful:

What about actions that don't fit into the world of CRUD operations?

This is where things can get fuzzy. There are a number of approaches:

Restructure the action to appear like a field of a resource. This
  works if the action doesn't take parameters. For example an activate
  action could be mapped to a boolean activated field and updated via
  a PATCH to the resource.

Treat it like a sub-resource with RESTful
  principles. For example, GitHub's API lets you star a gist with
  PUT /gists/:id/star and unstar with DELETE /gists/:id/star.

Sometimes you really have no way to map the action to a sensible RESTful
  structure. For example, a multi-resource search doesn't really make
  sense to be applied to a specific resource's endpoint. In this case,
  /search would make the most sense even though it isn't a resource.
  This is OK - just do what's right from the perspective of the API
  consumer and make sure it's documented clearly to avoid confusion.

ContentLicense: CC BY-SA 4.0

Title: RESTFul: state changing actions


问:
How should nodes in a chain be connected?
Suppose you were building a system that receives data on one end and sends filtered data on the other end.

The system is a chain of nodes, each receiving data from the node before and sending filtered data to the next one.

You have two approaches to choose from regarding the way the nodes would be connected:

A- Each node holds a reference to the next one through a particular interface.

B- Each node exposes an event, and the next node in line would be registered to that event, notified when that event is fired (when the previous node in line sends data).

In both cases, an outside entity connects the nodes to one another; they have no direct knowledge of each other.

Currently, I think events may be better because this way, a node doesn't care what the next node does; only what it has to send it. Thus enabling us to insert nodes in the middle easily.

There is a possibility nodes would need to be inserted in the middle, in the future.

Taking that into account, which approach would you prefer, and why? What are the pros and cons of each approach?

答:
Identifying the pattern.

This pattern is actually pretty smart. In fact it's so useful that Microsoft has written a considerable and well liked library called Reactive Extensions to solve this using a technique called functional reactive programming. The pattern you're trying to name is called an Observable.

It generalizes an IEnumerable fundamentally. You have a collection of items you'd like to steam through a series of transformations like mapping, filtering aggregating and so on. However - you also have a Task fundamentally since you have a time dependent action which is not immediately available.

Basically we have a chart that goes something like this:

```<code>          |   Singular    | Plural
------------------------------------------------
Spatial   |   Value           | Enumerable<Value>
Temporal  |   Task<Value>     | Observable<Value>
</code>```

Conceptually an observable is what models your problem. There has been a lot of research into this and you should really avoid inventing the wheel if possible. The flow of using an observable is something like this:

The workflow when using an observable

I link to actual examples later.

You start with a source - for example a timer, or a stream of data packets, a function that makes a request every few seconds or back-to-back and so on.

Then, transformations are applied at each turn - you can take an existing observable and .Select it into a new mapped observable or .Where it into a filter. You can also debounce it, flatMap it and perform interesting transformations. This is like LINQ only LINQ represents a single deferred one time query where an Observable represents an ongoing process.

You can unwrap the observable by subscribing to it, executing a function on its end.

You can fork an observable creating not only "lists of nodes" but whole trees.

This concept of a functional observable that chains is not only more powerful than events and aggregates well (You can merge observables, test them easily and so on) - it's also very simple. Your code can look something like:

```<code>GetDataItems() // returns a new observable
.Where(IWantItemsForTheNextRound) // filtering logic
.Select(Mapper) // mapping logic
... // any more transformations
</code>```

Just like working with IQueryable in LINQ the old transformations don't care and are not aware of what's passed from then on. Like LINQ you get a strong abstraction over processing a collection - only this time there's time involved.

You can insert a node in the middle by putting a hook for it and injecting a function that does something with that hook - if you flat map on that you can put arbitrarily complicated logic there extending it as much as you want.

Actual theory and reading.

There is plenty of theoretical material about why this approach is very robust in KrisKowal's gtor or Erik Meijer's Duality and the end of reactive.

Here are Some Rx videos on channel 9.

Here is the Home Page

Here are some samples.

ContentLicense: CC BY-SA 3.0

Body:
Identifying the pattern.

This pattern is actually pretty smart. In fact it's so useful that Microsoft has written a considerable and well liked library called Reactive Extensions to solve this using a technique called functional reactive programming. The pattern you're trying to name is called an Observable.

It generalizes an IEnumerable fundamentally. You have a collection of items you'd like to steam through a series of transformations like mapping, filtering aggregating and so on. However - you also have a Task fundamentally since you have a time dependent action which is not immediately available.

Basically we have a chart that goes something like this:

          |   Singular    | Plural
------------------------------------------------
Spatial   |   Value           | Enumerable<Value>
Temporal  |   Task<Value>     | Observable<Value>

Conceptually an observable is what models your problem. There has been a lot of research into this and you should really avoid inventing the wheel if possible. The flow of using an observable is something like this:

The workflow when using an observable

I link to actual examples later.

You start with a source - for example a timer, or a stream of data packets, a function that makes a request every few seconds or back-to-back and so on.

Then, transformations are applied at each turn - you can take an existing observable and .Select it into a new mapped observable or .Where it into a filter. You can also debounce it, flatMap it and perform interesting transformations. This is like LINQ only LINQ represents a single deferred one time query where an Observable represents an ongoing process.

You can unwrap the observable by subscribing to it, executing a function on its end.

You can fork an observable creating not only "lists of nodes" but whole trees.

This concept of a functional observable that chains is not only more powerful than events and aggregates well (You can merge observables, test them easily and so on) - it's also very simple. Your code can look something like:

GetDataItems() // returns a new observable
.Where(IWantItemsForTheNextRound) // filtering logic
.Select(Mapper) // mapping logic
... // any more transformations

Just like working with IQueryable in LINQ the old transformations don't care and are not aware of what's passed from then on. Like LINQ you get a strong abstraction over processing a collection - only this time there's time involved.

You can insert a node in the middle by putting a hook for it and injecting a function that does something with that hook - if you flat map on that you can put arbitrarily complicated logic there extending it as much as you want.

Actual theory and reading.

There is plenty of theoretical material about why this approach is very robust in KrisKowal's gtor or Erik Meijer's Duality and the end of reactive.

Here are Some Rx videos on channel 9.

Here is the Home Page

Here are some samples.


问:
Dependency promotion strategies: siloed or orchestrated?
We have a lot of apps and web services (some public facing products, some internal and part of a private "backend") that are interdependent on one another. Each one of these components has 4 environments (clusters of servers/nodes serving specific purposes):

Non-Production

DEV - Integrated development environment where CI builds push changes; useful for engineers to troubleshoot hard-to-find bugs that are not locally reproducible

QA - Isolated QA/Testing environment

DEMO - Stable UAT environment for business stakeholders

Production

LIVE - Our live/production environment

Code promotion goes: LOCAL (developer's machine) => DEV => QA => DEMO => LIVE.

Say we have an application called myapp that is backed by a RESTful web service called myws, which itself is backed by a DB called mydb.

Currently, we have what I would call "orchestrated" promotion amongst these dependencies: the myapp-dev points to myws-dev which uses mydb-dev. Similarly, myapp-qa points to myws-qa which uses mydb-qa. Same for DEMO and LIVE.

The problem with this is that anytime I make a change to, say, myapp, this requires me to make changes to myws and mydb as well. But because each DEV environment points to its dependencies' DEV environments, it means I have to schedule and rollout these changes all at the same time. Furthermore, if one build becomes unstable/broken, it often brings down other upstream components; for instance if a developer breaks something when changing mydb-dev, the myws-dev and myapp-dev clusters usually also become unstable.

To solve this, I am putting together a proposal for what I would call a "siloed" promotion strategy: all inter-component dependencies follow this guideline:

Upstream dependencies depend on the DEMO environment for their downstream dependencies, for all of their non-production environments (DEV, QA and DEMO); and

Upstream dependencies depends on the LIVE environment for their downstream dependencies for their production environment

Using this convention, myapp-dev would actuall point to myws-demo, which would use mydb-demo. Similarly, myapp-qa would also point to myws-demo and mydb-demo.

The advantage here that I can find is build stabilization: it is much less likely that the DEMO environment for a particular component will become unstable, because code can't make it to DEMO without rigorous testing both on DEV and QA.

The only disadvantage I can find to this method is that, if DEMO does break for a particular component, all the non-production environments for all upstream dependencies will suddenly be broken. But I would counter that this should happen extremely rarely because of the testing performed on DEV and QA.

This has got to be a problem that many developers (much smarter and experienced than myself) have solved, and I wouldn't be surprised if this problem and its solutions already have names to them (besides what I am calling orchestrated/siloed). So I ask: Do the merits of a siloed promotion strategy outweigh any cons, and what are the cons that I may be overlooking here?

答:
If I'm reading your post right, it doesn't seem like this proposal actually solves either of the alleged problems.

anytime I make a change to, say, myapp, this requires me to make
  changes to myws and mydb as well. But because each DEV environment
  points to its dependencies' DEV environments, it means I have to
  schedule and rollout these changes all at the same time

The "siloed promotion strategy" seems like it would only make this worse. If myapp v2, myws v2 and mydb v2 are only on DEV, and myapp v2 relies on mydb v2 to not crash, then when I try to run myapp v2 on DEV I'll hit mydb v1 DEMO and it crashes. You'd essentially be forced to either constantly override the silos, or deploy mydb v2 all the way to prod before you can even start working on myapp v2. More importantly, you would never be testing mydb v2 on DEV, so if it is broken you don't even find out until it breaks on DEMO, and then you're back at square one.

To some extent, the problem you describe is inevitable no matter how your workflow is set up, but it can be minimized. The trick is to ensure that the interface between mydb and myws (and the interface between myws and myapp) is strictly defined, and require all updates to that interface to be fully backwards compatible. At my job we have an XML schema defining the interface between our apps and services, and many of our internal tools simply won't let us make incompatible updates to those schemas.

Furthermore, if one build becomes unstable/broken, it often brings
  down other upstream components; for instance if a developer breaks
  something when changing mydb-dev, the myws-dev and myapp-dev clusters
  usually also become unstable.

This sounds to me like a serious problem, but not a deployment problem. A broken database will certainly prevent the service and app from working properly, but they shouldn't become "unstable". They should be returning error messages of some kind, so that anyone running myapp on dev sees "We're sorry, our database is having problems today" instead of simply crashing.

If the issue is that a broken database causes these problems at all, then what you can do is set up some "temporary siloing" system that lets you say "mydb DEV is broken now, please route all myws DEV queries to mydb DEMO for the time being". But this should only be a way to perform temporary fixes until mydb DEV is working normally again. If everything is "siloed" that way by default, then you're back at the problems I described above because nobody ever runs against mydb DEV at all.

I feel like I'm probably misunderstanding your proposal somehow, but hopefully this answer at least makes it obvious what was being misunderstood and how best to rephrase it.


问:
Best approach to develop / distribute proprietary module
I've been brainstorming for a while regarding the best approach to distribute closed-source modules. I'd like to mention that I have found similar question(s) on SE sites but don't think this is exactly the same scenario.

Let's say I wrote a set of well-tested PHP classes which I used as a core for multiple projects (copyright is mine). It has EntityManager, ACL, ORM, Configurable Cacheing, Action logging Admin panel functionalities etc which can be very handy in any database driven projects. (Let's not start argument regarding the integrity of the project itself ;)

My plan is to implement SAAS with the current set of functionalities, but the problem is most of the people I discussed would like it hosted in their servers and wouldn't mind paying a small recurrent loyalty fee. That leads to the ultimate question of choosing the best way of distributing such module / micro-framework.

I found following options to consider:

PHP Extension:
First solution that'll come to anyone's head is to develop and distribute as a standard php extension (Which will check for valid license-code in the cache once in a while and a cronjob will update license from license server periodically). I checked php-cpp.com regarding this and it seemed pretty impressing. One major difficulty is that the extension should be able to talk to mysql / redis etc (based on the configs passed to instantiate the object) by itself. At the moment, current php classes utilise MySQL and PHPRedis extension. I'd like to be able to add Mongodb, Cassandra/ElasticSearch functionality in near future. I'm not sure how it could be achieved. If anyone can possibly shed a light about how an extension can perform mySQL query internally that would be a great help.

Zephir:
I've seen some performance benchmark and Phalcon is one of the top competitors. The major advantage for me is that Zephir is php-like and it'll take considerably less time than writing C++ extension. But looking at the discussion boards, it appears that Zephir is a bit undercooked. By the time it'll be ready for production, php itself will introduce PHP7/NG. Also, same difficulty in the extension writing is present here.

HHVM:
Arguably, the best solution as it converts everything to byte-code and I wont't have to worry about the extension-difficulty here. But I have a new problem: I won't be able to allow users to attach their function (anonymous function) to the events triggered in my module (e.g: OnDuplicate() or OnPost()).

Any idea, resource or comment is greatly appreciated. Thanks.

答:
What about using Zend Guard or ionCube PHP Encoder? Or why is it a problem to distribute your source code for a fee?

This is a problem not special to PHP. Many companies write libraries that they sell in source code form.


问:
Writing my own voice recognition code
Problem Description

I am wanting to use voice recognition as part of a hardware project, which I would like to be completely self containing (I'm using small low power, low speed devices such as Arduino's and Raspberry Pi's, Kinects etc, no running traditional computer with an OS is involved. So a closed / self containing project).

Voice recognition can be very complicated depending on the level of sophistication you desire. I have what I believe a comparatively simple set of requirements. I only want to recognise my own voice, and I have a small dictionary of 20 or so words I'd like to recognise. Thus I don't require complex speech-to-text and voice recognition libraries or any of the excellent 3rd party software I find via Internet search engines (there is no shortage of these!). I believe my requirements are "simple enough" (within reason) that I can code my own solution. I am wondering if anyone has written their own process like this, and is my method is massively flawed? Is there a better way to do this without requiring a high level of mathematics or having to write a complex algorithm? That is the solution I have tried to think up below.

Solution Description

I will be writing this in C but I wish to discuss a language agnostic process, focussing on the process its self. So lets ignore that if we can.

1 . I will pre-record my dictionary of words to match those being spoken. We can imagine I have 20 recordings of my 20 different words, or perhaps short phrases or sentences of two or three words. I believe this makes the process of comparing two recording files easier than actually converting the audio to text and comparing two strings.

2 . A microphone is connected to my hardware device running my code. [1]. The code is continuously taking fixed length samples, say 10msec in length for example, and storing 10 consecutive samples for example, in a circular logging style. [2]. (I'm inventing these figures off the top of my head so they are only examples to describe the process).

[1] This would likely be connected through a band-pass filter and op-amp, as would the dictionary recordings be made, to keep the stored and collected audio samples smaller.

[2] I'm not sure exactly how I will take a sample, I need to work out a method though were I produce a numerical figure (integer/float/double) that represents the audio of a 10msec sample (perhaps a CRC value or MD5 sum etc of the audio sample), or a stream of figures (a stream of audio readings of frequencies perhaps). Ultimately a "sample" will be a numerical figure or figures. This part is going to be much more hardware involved so not really for discussion here.

3 . The code looks at it's stored 10 consecutive samples and looks for a volume increase to indicate a word or phrase is being said (a break from silence) and then increases is consecutive sample collecting to say 500 samples for example. That would mean it captures 5 seconds of audio in 10 msec samples.

It is these samples or "slices" that are compared between the stored sound and captured sound. If a high enough percentage of samples captured matched the equivalent stored ones, the code assumes its the same word.

```<code>The start of a store recording of the world "hello" for example,
stored words are split into 10 msec samples also

Stored Sample No           | 1| 2| 3| 4| 5| 6| 7|  8|
Stored Sample Value        |27|38|41|16|59|77|200|78|

Incoming audio (me saying "hello") with some "blank" samples
at the start to symbolise silence

Incoming Sample No         | 1| 2| 3| 4| 5| 6| 7| 8| 9|10| 11|12|
Incoming Sample Value      |  |  |  |20|27|38|46|16|59|77|200|78|
</code>```

4 . Once the code has collected a full sample stream, it then chops off the blanks samples at the start to produce the following audio recording. It could also move the sample set backwards and forwards a few places to better align with the stored sample.

This produces a sample set like the below:

```<code>Stored Sample No           | 1| 2| 3| 4| 5| 6|  7| 8|
Stored Sample Value        |27|38|41|16|59|77|200|78|

Incoming Sample No      |-1| 1| 2| 3| 4| 5| 6|  7| 8|
Incoming Sample Value   |20|27|38|46|16|59|81|201|78|
</code>```

5 . I believe that by having a percentage value for how close each sample must be, so sample 7 differs by a value of 1 which is less than %1, and a percentage value for the total number of samples which must be within their sample matching percentage, the code has an easily tunable level of accuracy.

I have never done anything like this with audio before, it could be a lot of work. This is why I am asking this question, if you perhaps already know the answer to this question to be obvious (what ever that answer may be). I am hoping this won't be a computationally massive tasks as some of the hardware I will be using will be low sec stuff. In the hundreds of Megahertz (Maybe 1Ghz using an over-clocked Rasp Pi). So this is a rather crude way to match audio samples using lower computational power. I'm not aiming for instant results, but less than 30 seconds for a decent proof of concept.

PS
I don't have the rep to tag this with a new tag like "audio", "audio recognition", "voice", "voice recognition" etc.

答:
Arduino and Raspberry Pi are prototyping boards with little chips on them. You should focus on the chip first. Look for something with a DSP (digital signal processing) toolbox, maybe you already have a DSP toolbox and don't know it.  DSP toolboxes have algorithms on call like fft (fast fourier transform) and ifft (inverse fft) for fast frequency domain analysis.

Focus on your programmatic style:
Are your samples in a stack or a queue? You will want a queue for this type of data. A queue looks like:

```<code>Position NO --|1|2|3|4|5|6|7|8|
Sample Value  |5|7|9|1|2|2|9|8|
</code>```

Next iteration:

```<code>Position NO --|1|2|3|4|5|6|7|8|
Sample Value  |0|5|7|9|1|2|2|9|
->  First in First out (FIFO)
</code>```

Notice how things shift toward the 'right'?  I think you described a "circular" algorithm. Just overwrite the oldest samples with the second oldest samples, then overwrite the second oldest samples with the third oldest, ..., all the way to the beginning of the queue where you insert your newest data.

"The code is continuously taking fixed length samples, say 10msec" <--incorrect
Think this way: The code is discretely taking quantized (height) samples, at a sampling rate of 10000 samples per second, which makes each sample 0.1 ms apart.

What is your sampling frequency? What is the bitrate on your quantizer? Lower numbers will help you free up memory.  I would suggest a low sampling rate like 6600 samples per second (Nyquist). I suspect 4 bit (16 levels) would be sufficient for recognition. So thats 3300 bytes of recording per second. Now do fft and delete everything above 3300 Hz (telephony filter). Now you have 1650 bytes used for one second of sound.  These DSP tricks will save a lot of memory.

I don't know who thinks 512 MB is small.  With the above info that is 300,000+ seconds of recording... over 3 days solid.

I think you will find the frequency domain (by using fft) to be a better environment to perform voice recognition.

I hope I didnt confuse you worse :)

Title: Writing my own voice recognition code

Body:
Arduino and Raspberry Pi are prototyping boards with little chips on them. You should focus on the chip first. Look for something with a DSP (digital signal processing) toolbox, maybe you already have a DSP toolbox and don't know it.  DSP toolboxes have algorithms on call like fft (fast fourier transform) and ifft (inverse fft) for fast frequency domain analysis.

Focus on your programmatic style:
Are your samples in a stack or a queue? You will want a queue for this type of data. A queue looks like:

Position NO --|1|2|3|4|5|6|7|8|
Sample Value  |5|7|9|1|2|2|9|8|

Next iteration:

Position NO --|1|2|3|4|5|6|7|8|
Sample Value  |0|5|7|9|1|2|2|9|
->  First in First out (FIFO)

Notice how things shift toward the 'right'?  I think you described a "circular" algorithm. Just overwrite the oldest samples with the second oldest samples, then overwrite the second oldest samples with the third oldest, ..., all the way to the beginning of the queue where you insert your newest data.

"The code is continuously taking fixed length samples, say 10msec" <--incorrect
Think this way: The code is discretely taking quantized (height) samples, at a sampling rate of 10000 samples per second, which makes each sample 0.1 ms apart.

What is your sampling frequency? What is the bitrate on your quantizer? Lower numbers will help you free up memory.  I would suggest a low sampling rate like 6600 samples per second (Nyquist). I suspect 4 bit (16 levels) would be sufficient for recognition. So thats 3300 bytes of recording per second. Now do fft and delete everything above 3300 Hz (telephony filter). Now you have 1650 bytes used for one second of sound.  These DSP tricks will save a lot of memory.

I don't know who thinks 512 MB is small.  With the above info that is 300,000+ seconds of recording... over 3 days solid.

I think you will find the frequency domain (by using fft) to be a better environment to perform voice recognition.

I hope I didnt confuse you worse :)


问:
Know any good resources/information on architecting an iOS app?
I spent a few months working on an iOS app of mine (in Swift) before realizing it was really a bunch of MVCs (Massive View Controllers).
I want to start fresh and build something modular, scalable, and maintainable, but finding any clear information on good ways to do this is more difficult than I thought. I am new to programmers.SE, but not to stackoverflow and I am a competent developer (don't mind my reputation).

Has anyone come across any good resources on how to create well designed apps in terms of code and architecture (not UI)? Such as how to keep things separate and organized, easy to modify and maintain, different classes for logic/networking/etc.

I understand that I can find info via Google, however if anyone has any input/resources from past experience or prior knowledge sharing would be great!

答:
I would start by moving any code that implements or supports the implementation of any delegate or data source into their own classes.  So for example if you have a screen that contains a table view inside a navigation controller, move the tableview's delegate and data sources into separate classes and inject them into the VC.

The once you've split up all of those, see what other protocols you're implementing and factor those out too.

Then see how big your View Controllers are. Find all the code that belongs in the models and move them to where they belong.

Last should be moving code from the controls into your view subclasses.  If you don't have any view subclasses then good for you you're probably done.

Anything more than that is usually asking for trouble.


问:
Architecture for monitoring lots of mini-games
In my project, I'm going to create lots of mini games. Those mini games can last 30 seconds to 1 week (the duration of the game is decided when it is created and is fixed).

The number of concurrent games can be large (more than 1 game per user and we hope to have many users of course :-)).

Nothing really happens during the game. They are composed of just a winning condition and end time.

Once a game reaches its end, I need the server to check the winning condition (using a remote service) and finalize the game (decide who won and give points). During the time the game takes place, the server does not need to manage it.

You can think of the games as bets. Someone places a bet that something will happen in 30 seconds and after 30 seconds I need to check if that something really happened and update the system.

Latency of the game finalization should be very fast, especially for short games. Not more than a second or two. I.e, for a game of 30 seconds, I should be able to update if it won or lost a second or two after it ended.

I thought about persisting each game to a row in a sql table and schedule a task to run when it ends and finalize it.

For example, a user starts a game of 1 minute. The server will create the game in the db and schedule a task to run in 1 minute (and pass it the game's id). When the task triggers, it will finalize the game and update its status in the db.

Are there other ways to solve this problem? Maybe something that does not require having a task per game? I thought also about having 1 task that will check for all finished games but for short games (e.g. 30 secs) the polling time must be very short and I'm not sure how well it can scale.

答:
I'm pretty sure there is some canonical representation of my problem. For example, you can think of the games as tasks that need to start at a specific time (the game's end time). I guess this is some kind of scheduling problem.

For my case, I have 2 solutions.

The "naive" solution - I have a task that wakes up every second or so, loads all the games that need to be finalized from the db and finalizes them. Only one task handles all the games which means that when there are a lot of games, latency will increase. But at least it degrades slowly and doesn't just fall apart. It also does not depend on the number of concurrent games, only on the number of games that end at each second.

Since I'm using Azure, I thought about using the Storage Queue. Messages in the Azure storage queue can have an "invisibility" time, so I can put each game in the queue and set it to be invisible until it is time for it to be finalized. Then I can have as many threads as I like reading games from the queue and finalizing them. But I'm not sure this the queue is optimized for such a use case.


答: I would go for the approach of using table,however I would do a slight modification to the way they are processed. Instead of spinning up a task for each and every row I would create number of monitoring tasks, and they would execute a SQL against current table to find out which games needs finalizing at given point, and based on number of monitoring tasks they would distribute the number of rows among themselves based on some sort of sorting and taking certain amount of rows.</p>

Title: Architecture for monitoring lots of mini-games

Body:
In my project, I'm going to create lots of mini games. Those mini games can last 30 seconds to 1 week (the duration of the game is decided when it is created and is fixed).

The number of concurrent games can be large (more than 1 game per user and we hope to have many users of course :-)).

Nothing really happens during the game. They are composed of just a winning condition and end time.

Once a game reaches its end, I need the server to check the winning condition (using a remote service) and finalize the game (decide who won and give points). During the time the game takes place, the server does not need to manage it.

You can think of the games as bets. Someone places a bet that something will happen in 30 seconds and after 30 seconds I need to check if that something really happened and update the system.

Latency of the game finalization should be very fast, especially for short games. Not more than a second or two. I.e, for a game of 30 seconds, I should be able to update if it won or lost a second or two after it ended.

I thought about persisting each game to a row in a sql table and schedule a task to run when it ends and finalize it.

For example, a user starts a game of 1 minute. The server will create the game in the db and schedule a task to run in 1 minute (and pass it the game's id). When the task triggers, it will finalize the game and update its status in the db.

Are there other ways to solve this problem? Maybe something that does not require having a task per game? I thought also about having 1 task that will check for all finished games but for short games (e.g. 30 secs) the polling time must be very short and I'm not sure how well it can scale.


问:
Summarizing time spent on UI tests
I was working with a team on a web-based software. We have written ~70-80 Selenium test for the product. Mainly happy-path tests with some regression ones for bugs reported by users.

It was the first time when our company did automatic UI end-to-end testing and it seems quite helpful. We have some success stories as well, like catching a serious regression in a library we used (it is developed by another team in the company).

Anyway, writing these tests needs a lot of time, partly because we didn't have much experience with neither Selenium nor automatic UI testing.

After a few months of development my team and the product owner got the idea that we should make statistics about how much time writing and maintaining these tests took. (We usually made separate JIRA subtasks for Selenium tests so we could get a rough number.)

I'm afraid that this number alone could make a bad impression about testing. How can we produce a number to pair with this time to show benefits of testing as well, so we could decide whether it's worth it (or not)?

We can dig JIRA for bugs which was caught by these tests but summarizing their logged work times does not seem good enough. Fixing a bug caught by automatic tests takes less time than fixing a released one reported by users and there are other benefits, for example, less interruptions for developers. Furthermore, catching a bug during a sprint gives faster feedback to the developers and usually we haven't created separate JIRA subtask for these.

It is a good idea to summarize these time values at all?

答:
Number of bugs caught or fixed has a very bad reputation as a software metric (it is no metric at all). Just Google it and you will find some horror stories.
Summarizing these time values indeed won't tell much. What you want to tell your product owner alongside with the statistics is the following:

You were working with a new tool, new methodology, you have set up a new configuration to run the tests. That means that you spent a significant amount of time learning, which is an investment. Because of this as you get more and more of an expert on this, the time you spend on writing this tests are likely to decrease in the futture.

I assume you and your team have a good opinion about these tests, and you feel much safer releasing your product this way. Make sure your PO understands that, you are the experts after all. Emphasize that a bug caught before release is cheaper to fix by an order of magnitude then a bug caught after release.

If I understand correctly, you are using scrum. If you think that you have a good way measuring the teams throughput (in userstory points or whatever), you can suggest to make statistics about how it grows in the long run because of the tests.

Final thoughts: for the UI tests to work effectively, you should have even more unit and integration tests. You can read abut this on Martin Fowler's page.

Title: Summarizing time spent on UI tests


问:
Check all "lines" in an array?
I have a 3D array with booleans and I need to check if there are "lines" that all contain true or false. With lines I mean horizontally, vertically and diagonally within the array. However I only need to check this when an element changes and I know the location of the changed element. The array is always equal on all 3 sides/dimensions.

I am looking for an efficient way to traverse the possible direction from the element that changed. What I'm currently doing is to first check the straight lines x, y and z which are easy. Then i check for the 2 horizontal diagonals:

```<code>if (element.x + element.y == arraySize || element.x == element.y)
    //Only now there can be a full diagonal line
</code>```

And that for each side (x, y and z). Now I only need the 4 complete diagonals accros the array. But I'm wondering if there is a clever trick to make this more efficient.

答:
From a theoretical standpoint, there's not a whole lot you can do because whether or not one line contains all trues or all falses doesn't tell you much about whether the other lines do, i.e. you have to "check all of them" no matter what.

What you can do is make sure you don't check anything twice. If you check whether there's a line from (0,0,0) to (8,8,8), then you should not also check whether there's a line from (8,8,8) to (0,0,0) later in your algorithm. For example, when checking for horizontal and vertical lines, only do the checks for three of the six sides of your cube.

The data structure you use is probably the most important factor in practice. You obviously need random access since the "lines" go in several different directions, so an ArrayList would be a lot better than a LinkedList (though I'm guessing you knew that already).

If those generic tips aren't enough, then we'd have to start talking about things like the actual size of your cube, the exact code you've tried, how you measured its performance, how the trues or falses tend to be distributed, and so on.

Title: Check all "lines" in an array?


问:
C++ Template Metaprogramming and Call By Need Evaluation
I recently wrote a fairly complex C++ meta function that boils down to:

```<code>template <size_t N, typename val>
struct Rec {
    using type = typename std::conditional<N == 0,
        val,
        typename Rec<N - 1, val>::type>::type;
};
</code>```

Both Clang and G++ barf on this type of recession, stating that, "Template instantiation depth exceeds maximum of X". I quickly rewrote the program and fixed the problem, but it got me thinking about the evaluation strategy of C++ template parameters.

Is there anything in the C++ standard that would prevent templates from using call by need evaluation of template parameters, or is this limitation purely an implementation defect?

答:
To instantiate std::conditional<N==0, val, typename Rec<N-1, val>::type>, the compiler needs to prove that both val and Rec<N-1, val>::type evaluate to a type and that N==0 evaluates to a constant expression that can be used in a boolean context.

If those conditions are not met, then the program is not well-formed and requires a diagnostic.

It is also only after evaluating the template arguments that the compiler can start looking for specializations that match, because for all the compiler knows, there might be a specialization of std::conditional for the parameters true,val,Rec<-1,val>::type that is more specialized than the default one for std::conditional<true, T, F>.

This is also why you need a specialization of Rec to stop the recursion: The condition used in std::conditional is only checked after the recursion has run its course and hit a terminating condition.

The compiler would be perfectly happy if you added the specialization

```<code>template <class val>
class Rec<-42, val> {
  typedef void type;
};
</code>```

and give you the expected results (even if val != void).

Body:
To instantiate std::conditional<N==0, val, typename Rec<N-1, val>::type>, the compiler needs to prove that both val and Rec<N-1, val>::type evaluate to a type and that N==0 evaluates to a constant expression that can be used in a boolean context.

If those conditions are not met, then the program is not well-formed and requires a diagnostic.

It is also only after evaluating the template arguments that the compiler can start looking for specializations that match, because for all the compiler knows, there might be a specialization of std::conditional for the parameters true,val,Rec<-1,val>::type that is more specialized than the default one for std::conditional<true, T, F>.

This is also why you need a specialization of Rec to stop the recursion: The condition used in std::conditional is only checked after the recursion has run its course and hit a terminating condition.

The compiler would be perfectly happy if you added the specialization

template <class val>
class Rec<-42, val> {
  typedef void type;
};

and give you the expected results (even if val != void).


问:
peer review code documentation
We all know that code reviews are generally a good practice, but what about reviewing documentation? Many devs that I work with will put up wiki pages, javadocs, etc, but most of the time, unless someone else needs it right away the docs will go unnoticed and unreviewed.

Are there any good tools or methodologies for peer reviewing code documentation?

答:
Given that any quality produce requires documentation, even if its a getting-started document you should be creating, updating and reviewing the docs.

The problems come when documentation is hard to access, so if you have to check out a word document from sharepoint edit it and then upload it again, you're not going to find many people wanting to make the changes. So I find it best if you assume the documentation is part of the source code, and if you put the document sources alongside the code there's no excuse for not updating it - eg if your documentation is text files in a markup language then doc changes are as easy as editing a big comment. Your CI system can turn those sources into word or PDF or HTML, so you always have up to date documentation that is both easy to edit and easy to review (you just check the scm history diffs).

wiki pages are less easy as they do not closely correspond to SCM history, but you do still have their history you can check, the editor will have to say which pages they changed.

Other than that, there's no tooling for Word documentation reviewing that is any good (you still have to manually go in and read the whole thing to see if it it correct) so you end up having to add a review comment that you updated the docs in section X, chapter Y, page Z. The answer to this is obviously to stop using Word.

Title: peer review code documentation


答:
As Ixrec wrote in the asspect of performance there is not much to do, you will need to travers the array many times. However I can give you a tool that makes it simpler:

```<code>public class LineEnumerator
{
    int dx, dy, dz;
    public LineEnumerator(int dx, int dy, int dz)
    {
        this.dx = dx;
        this.dy = dy;
        this.dz = dz;
    }
    public IEnumerable<bool> GetLine(bool[, ,] arr, int x0, int y0, int z0)
    {
        int xLength = arr.GetLength(0);
        int yLength = arr.GetLength(1);
        int zLength = arr.GetLength(2);

        while (x0 >= 0 && x0 < xLength &&
               y0 >= 0 && y0 < yLength &&
               z0 >= 0 && z0 < zLength)
        {
            yield return arr[x0, y0, z0];
            x0 += dx;
            y0 += dy;
            z0 += dz;
        }
    }
}
</code>```

This is a total general directional enumerator for a 3D array. Using this it is easy to wirte the treversing. For example traversing a line in the X direction can be writen like this:

```<code>var XEnumerator = new LineEnumerator(1, 0, 0);
foreach(bool b in XEnumerator.GetLine(arr, 0, 0, 0))
{
  //Do whatever
}
</code>```

Or you can instantiate a diagonal enumerator like this:

```<code>var DiagonalEnumerator1 = new LineEnumerator(1, 1, 1);
</code>```

or an other like this:

```<code>var DiagonalEnumerator2= new LineEnumerator(1, 1, -1);
</code>```

Title: Check all "lines" in an array?

Body:
I have a 3D array with booleans and I need to check if there are "lines" that all contain true or false. With lines I mean horizontally, vertically and diagonally within the array. However I only need to check this when an element changes and I know the location of the changed element. The array is always equal on all 3 sides/dimensions.

I am looking for an efficient way to traverse the possible direction from the element that changed. What I'm currently doing is to first check the straight lines x, y and z which are easy. Then i check for the 2 horizontal diagonals:

```<code>if (element.x + element.y == arraySize || element.x == element.y)
    //Only now there can be a full diagonal line
</code>```

And that for each side (x, y and z). Now I only need the 4 complete diagonals accros the array. But I'm wondering if there is a clever trick to make this more efficient.

Body:
As Ixrec wrote in the asspect of performance there is not much to do, you will need to travers the array many times. However I can give you a tool that makes it simpler:

public class LineEnumerator
{
    int dx, dy, dz;
    public LineEnumerator(int dx, int dy, int dz)
    {
        this.dx = dx;
        this.dy = dy;
        this.dz = dz;
    }
    public IEnumerable<bool> GetLine(bool[, ,] arr, int x0, int y0, int z0)
    {
        int xLength = arr.GetLength(0);
        int yLength = arr.GetLength(1);
        int zLength = arr.GetLength(2);

        while (x0 >= 0 && x0 < xLength &&
               y0 >= 0 && y0 < yLength &&
               z0 >= 0 && z0 < zLength)
        {
            yield return arr[x0, y0, z0];
            x0 += dx;
            y0 += dy;
            z0 += dz;
        }
    }
}

This is a total general directional enumerator for a 3D array. Using this it is easy to wirte the treversing. For example traversing a line in the X direction can be writen like this:

var XEnumerator = new LineEnumerator(1, 0, 0);
foreach(bool b in XEnumerator.GetLine(arr, 0, 0, 0))
{
  //Do whatever
}

Or you can instantiate a diagonal enumerator like this:

var DiagonalEnumerator1 = new LineEnumerator(1, 1, 1);

or an other like this:

var DiagonalEnumerator2= new LineEnumerator(1, 1, -1);


问:
Programming language heritage of the word 'field'
What programming language introduced the word "field" to describe what we might call a member variable in C++? What modern programming languages carry on this usage as the preferred term?

I've seen this word used in both a C and C++ context but it always feels a bit foreign. I don't have a copy of  the C standard, but the C++ standard  uses the phrase "member variable". (It does use the word "field" in the phrase "bit-field".) Whenever I hear this I can't help but wonder where the speaker got that word from.

答:
The concept / use of field, a logical part of any data, has been with us since at least punched cards/tape.  These fields were typically fixed length.

All of the first languages probably used the term since they were processing punched cards / tape.  I say 'probably' because I used 'All' and did not program using them all.  In the late 60's when I started programming the term 'field' was used in all of the languages I programmed in.

My guess would be that the first use of 'field' in a programming language would be an early IBM assembler, perhaps SPS.


问:
Meaning of an "instance of a database"
From http://en.wikipedia.org/wiki/Extension_(semantics)#Computer_science

In computer science, some database textbooks use the term 'intension' to refer to the schema of a database, and 'extension' to refer to particular instances of a database.

does a "particular instance of a database" mean

a database,
or

a tuple of a relational database, for a relational database viewed as a relation in mathematics?

Thanks.

答: The way that I've seen "instance" used, at least in business contexts, is a deployment of a given database (schema + data). For example, I might say "this report is dangerous, because it is going against the master instance and may be slow; it should use the reporting instance." Or you might have "five instances of the testing database" on your staging servers.

Title: Meaning of an "instance of a database"


问:
Git workflow for Microsoft SQL Stack
My team of developers are currently working at a client who has required us to move away from SVN and begin using their native workflow program. (Source tree by Atlassian). We are data warehouse developers and utilise primarily the Microsoft SQL stack for development.
 The stack is commonly:

SQL Server Analysis Services (SSAS)

SQL Server Integration Services (SSIS)

SQL Server Management Studio (SSMS)

We also utilise a data-visualization tool named Tableau Server.

At the client these tools are used to develop simultaneously across four subject areas, for the purpose of this we will call them Subjects Areas; W, X, Y and Z.

Each subject area gets its own lot of solutions in all three SS programs as well as some files associated to tableau.

Since switching to sourcetree we have had a workflow of a master branch which reflects the work that will be migrated to the production environment. As well as a development branch which all developers commit to on a frequent basis.

After a large bug was detected in one of our subject areas we needed to revert back to the last good commit for the production environment. This was nearly impossible due to the large number of commits and merges and our disorganised gitflow.

This leads me to the question:

What is the ideal way to manage in effect the development of four subject areas across four programs simultaneously using github?

From my reading it would seem that 18 branches (4subject x 4 programs + Master + Dev) is a solution however this seems to be overkill.

Points to note:

All subject areas are developed simultaneously.

Programs (SSMS/SSIS) are developed by multiple developers simultaneously in different subject areas.

We have changed our master branch to be a sole reflection of our production environment with no extra commits already.

We only have access to a single repository.

Some work on some programs (SSIS for Subject X) are developed but never merged to production. This work needs to be maintained though.

As this is a subjective question, any opinions or further clarification is welcomed.

答:
Summary: Vanilla Git Flow is pretty sane. For code that exist next to each other, use directories rather than branches. Feature branches should be short-lived, and don't introduce additional develop branches for each program and subject.

For projects of a certain size – and your project is well past that point –, the “Git Flow” describes best practices for Git branch management. The central branch is the develop branch, which is used for integration of features. If you do continuous integration testing, this is the branch you test. The master branch is always in a production-ready state and only lists previous releases.

As an aside: the master branch being production-ready does not imply that the contents of the master branch will literally be deployed in production. Although it's sometimes used as one, Git is not a deployment system. Instead, the master branch describes the states of the project that can be used to create the actual deliverable. This (hopefully automated) build process can then ignore subjects, programs, or really any files that are not needed for the that build.

There are now a couple of workflows that make up the Git Flow:

Releasing: When we want to release, we create a temporary branch from develop and perform release testing. Any work associated with releasing (such as minor fixes or bumping the version) can be committed on this branch. Once everything works out, this branch is merged into master and develop, and the merge commit on master is tagged with the version number. So master represents the current release, master^ the previous release, and so on.

Development: Development happens on relatively short-lived feature branches. These are forked of develop. Once they are complete, they get merged back into develop. If these branches are long-lived, it's a good idea to rebase the feature branch onto develop on a regular basis in order to prevent large merge conflicts. Also, keeping features small is a good strategy to make merging more pleasant.

Hotfixes: are not relevant here.

This is outside of the scope of Git Flow, but it can make sense to subdivide feature branches further, for large features that require the immediate collaboration of multiple people (this is not the default!). The sub-team working on this feature could treat the feature branch as if it were a local develop branch, and merge their own sub-features into this branch using the normal development workflow. Once the feature is ready, it would be merged into the main develop branch. However, this subdivision has certain dangers: The feature branch and the main develop are likely to drift apart over time. This can be counteracted by having a liaison developer regularly merge the main develop into the feature branch (which acts as the sub-teams develop branch). But when this mega-feature is merged into the main project, the impact for everyone else will be substantial and disrupt smooth development. Therefore, such over-complication should be only used as a last resort. It's preferable to have lots of small feature branches.

If we try to follow the Git Flow, having 4 subjects × 4 programs = 16 develop branches is not recommended. Quite likely all of that shouldn't be in the same repo, but if you have to, just use different directories inside the repo. You don't need a separate branch for each topic (i.e. subject, program). Git Flow uses branches to keep track of multiple threads of development (in the case of feature branches) or to signify the status of the code (in the case of develop and master).

As an analogy: I'm storing a blog about cats and dogs in a Git repo. I do not have two long-lived branches cat and dog where I write all posts about cats and dogs, respectively. Instead, I'd create a new feature branch for each post, but all cat-related posts are kept in the cat/ directory. Once the post is complete, it can be merged back into the main branch.

Title: Git workflow for Microsoft SQL Stack


问:
sorting / merging hashtable
For my project I have a hashtable with 1M buckets (sometimes more).

Each bucket contains lots of values and they are stored sorted in a dynamic array.

I am looking for easy enough way to store all values in a file (printf will do as well), but in sorted way.

Is there a way to do so in less N*N complexity (e.g. merging all 1M arrays/buckets)

答:
You can make a min-heap where you store all buckets sorted by the first element.

Then you pop an element from the first bucket and re-heapify.

If you are not allowed to change the buckets then keep an index per bucket of which element still has to be popped from it.

Title: sorting / merging hashtable


答:
I believe the second half of the mergesort algorithm is what you're looking for, since the first half is splitting the numbers into subranges, and the second half is merging those subranges. Mergesort as a whole has a complexity of O(n log n), and I believe the second half by itself would also be O(n log n).

To get you started, here's a reasonably short and readable implementation of mergesort in C, taken from http://www.cquestions.com/2011/07/merge-sort-program-in-c.html

```<code>#include<stdio.h>
#define MAX 50

void mergeSort(int arr[],int low,int mid,int high);
void partition(int arr[],int low,int high);

int main(){

    int merge[MAX],i,n;

    printf("Enter the total number of elements: ");
    scanf("%d",&n);

    printf("Enter the elements which to be sort: ");
    for(i=0;i<n;i++){
         scanf("%d",&merge[i]);
    }

    partition(merge,0,n-1);

    printf("After merge sorting elements are: ");
    for(i=0;i<n;i++){
         printf("%d ",merge[i]);
    }

   return 0;
}

void partition(int arr[],int low,int high){

    int mid;

    if(low<high){
         mid=(low+high)/2;
         partition(arr,low,mid);
         partition(arr,mid+1,high);
         mergeSort(arr,low,mid,high);
    }
}

void mergeSort(int arr[],int low,int mid,int high){

    int i,m,k,l,temp[MAX];

    l=low;
    i=low;
    m=mid+1;

    while((l<=mid)&&(m<=high)){

         if(arr[l]<=arr[m]){
             temp[i]=arr[l];
             l++;
         }
         else{
             temp[i]=arr[m];
             m++;
         }
         i++;
    }

    if(l>mid){
         for(k=m;k<=high;k++){
             temp[i]=arr[k];
             i++;
         }
    }
    else{
         for(k=l;k<=mid;k++){
             temp[i]=arr[k];
             i++;
         }
    }

    for(k=low;k<=high;k++){
         arr[k]=temp[k];
    }
}
</code>```

Sample output:

```<code>Enter the total number of elements: 5
Enter the elements which to be sort: 2 5 0 9 1
After merge sorting elements are: 0 1 2 5 9
</code>```

Note that ratchet freak's suggestion is basically the heapsort algorithm, which is also O(n log n), so that one should be fine too.

Title: sorting / merging hashtable

Body:
For my project I have a hashtable with 1M buckets (sometimes more).

Each bucket contains lots of values and they are stored sorted in a dynamic array.

I am looking for easy enough way to store all values in a file (printf will do as well), but in sorted way.

Is there a way to do so in less N*N complexity (e.g. merging all 1M arrays/buckets)

Body:
I believe the second half of the mergesort algorithm is what you're looking for, since the first half is splitting the numbers into subranges, and the second half is merging those subranges. Mergesort as a whole has a complexity of O(n log n), and I believe the second half by itself would also be O(n log n).

To get you started, here's a reasonably short and readable implementation of mergesort in C, taken from http://www.cquestions.com/2011/07/merge-sort-program-in-c.html

#include<stdio.h>
#define MAX 50

void mergeSort(int arr[],int low,int mid,int high);
void partition(int arr[],int low,int high);

int main(){

    int merge[MAX],i,n;

    printf("Enter the total number of elements: ");
    scanf("%d",&n);

    printf("Enter the elements which to be sort: ");
    for(i=0;i<n;i++){
         scanf("%d",&merge[i]);
    }

    partition(merge,0,n-1);

    printf("After merge sorting elements are: ");
    for(i=0;i<n;i++){
         printf("%d ",merge[i]);
    }

   return 0;
}

void partition(int arr[],int low,int high){

    int mid;

    if(low<high){
         mid=(low+high)/2;
         partition(arr,low,mid);
         partition(arr,mid+1,high);
         mergeSort(arr,low,mid,high);
    }
}

void mergeSort(int arr[],int low,int mid,int high){

    int i,m,k,l,temp[MAX];

    l=low;
    i=low;
    m=mid+1;

    while((l<=mid)&&(m<=high)){

         if(arr[l]<=arr[m]){
             temp[i]=arr[l];
             l++;
         }
         else{
             temp[i]=arr[m];
             m++;
         }
         i++;
    }

    if(l>mid){
         for(k=m;k<=high;k++){
             temp[i]=arr[k];
             i++;
         }
    }
    else{
         for(k=l;k<=mid;k++){
             temp[i]=arr[k];
             i++;
         }
    }

    for(k=low;k<=high;k++){
         arr[k]=temp[k];
    }
}

Sample output:

Enter the total number of elements: 5
Enter the elements which to be sort: 2 5 0 9 1
After merge sorting elements are: 0 1 2 5 9

Note that ratchet freak's suggestion is basically the heapsort algorithm, which is also O(n log n), so that one should be fine too.


答:
I have seen that term mostly used in an Oracle context. From the Oracle docs:

A database instance is a set of memory structures that manage database
  files. A database is a set of physical files on disk created by the
  CREATE DATABASE statement. The instance manages its associated data
  and serves the users of the database.

So in that context, the term database means simply the files holding the schema and the actual data, while database instance refers to the server processes and the related memory structures which actually manage those files.

Microsoft, for example, uses the term "instance" for "a copy of the sqlservr.exe executable that runs as an operating system service", so the meaning is very similar, though in that context one instance can manage multiple databases.

I am not sure if other vendors use the terms exactly in one of the above meanings, but I would not be too surprised.

Title: Meaning of an "instance of a database"

Body:
From http://en.wikipedia.org/wiki/Extension_(semantics)#Computer_science

In computer science, some database textbooks use the term 'intension' to refer to the schema of a database, and 'extension' to refer to particular instances of a database.

does a "particular instance of a database" mean

a database,
or

a tuple of a relational database, for a relational database viewed as a relation in mathematics?

Thanks.


答:
From what you wrote, I don't see a reason why original information about the hashtable and the buckets has to be used - it just overcomplicates things. </p>

<p>So flatten all buckets into a list (complexity O(N)) and apply an arbitrary sorting algorithm with complexity O(N * log(N)), for example, quick sort or merge sort. Then write the results into a file. </p>

Title: sorting / merging hashtable

Body:
From what you wrote, I don't see a reason why original information about the hashtable and the buckets has to be used - it just overcomplicates things.

So flatten all buckets into a list (complexity O(N)) and apply an arbitrary sorting algorithm with complexity O(N * log(N)), for example, quick sort or merge sort. Then write the results into a file.


问:
Is there any material difference between queries joined by WHERE clauses, and queries using an actual JOIN?
In Learn SQL the Hard Way (exercise six), the author presents the following query:

```<code>SELECT pet.id, pet.name, pet.age, pet.dead
    FROM pet, person_pet, person
    WHERE
    pet.id = person_pet.pet_id AND
    person_pet.person_id = person.id AND
    person.first_name = "Zed";
</code>```

and then goes on to say that:

There are actually other ways to get these kinds of queries to work called "joins". I'm avoiding those concepts for now because they are insanely confusing. Just stick to this way of joining tables for now and ignore people who try to tell [you] that this is somehow slower or "low class".

Is that true? Why or why not?

答:
There are two different aspects of this to consider:  Performance and Maintainability/Readability.

Maintainability/Readability

I chose a different query, as it is something that I think is a better/worse example than the original query that you posted.

What looks better to you and is more readable?

```<code>select
    e.LoginID,
    DepartmentName = d.Name
from HumanResources.Employee e
inner join HumanResources.EmployeeDepartmentHistory edh
on e.BusinessEntityID = edh.BusinessEntityID
inner join HumanResources.Department d
on edh.DepartmentID = d.DepartmentID
where d.Name = 'Engineering';
</code>```

Or...

```<code>select
    e.LoginID,
    DepartmentName = d.Name
from HumanResources.Employee e,
HumanResources.EmployeeDepartmentHistory edh,
HumanResources.Department d
where e.BusinessEntityID = edh.BusinessEntityID
and edh.DepartmentID = d.DepartmentID
and d.Name = 'Engineering';
</code>```

For me personally, the first one is quite readable.  You see that we are joining tables with INNER JOIN, meaning that we are pulling the rows that match on the subsequent join clause (i.e. "join Employee with EmployeeDepartmentHistory on BusinessEntityID and include those rows").

The latter, the comma means nothing to me.  It makes me wonder what you are doing with all of those WHERE clause predicates.

The former reads more like my brain thinks.  I look at SQL all day every day and the commas for joins.  Which leads me to my next point...

There are actually other ways to get these kinds of queries to work called "joins"

They are all joins.  Even the commas is a join.  The fact that the author doesn't call them that is indeed their downfall.... it isn't obvious.  It should be obvious.  You're joining relational data, whether you specify JOIN or ,.

Performance

This is most definitely going to be RDBMS-dependent.  I can only speak on behalf of Microsoft SQL Server.  Performance-wise these are equivalent.  How do you know?  Capture the post-execution plans and see what exactly SQL Server is doing for each of these statements:

In the above image, I highlighted that I'm using both queries as above, differing only in the explicit characters for the join (JOIN vs ,).  SQL Server does the exact same thing.

Summary

Don't use commas.  Use explicit JOIN statements.

Body:
There are two different aspects of this to consider:  Performance and Maintainability/Readability.

Maintainability/Readability

I chose a different query, as it is something that I think is a better/worse example than the original query that you posted.

What looks better to you and is more readable?

select
    e.LoginID,
    DepartmentName = d.Name
from HumanResources.Employee e
inner join HumanResources.EmployeeDepartmentHistory edh
on e.BusinessEntityID = edh.BusinessEntityID
inner join HumanResources.Department d
on edh.DepartmentID = d.DepartmentID
where d.Name = 'Engineering';

Or...

select
    e.LoginID,
    DepartmentName = d.Name
from HumanResources.Employee e,
HumanResources.EmployeeDepartmentHistory edh,
HumanResources.Department d
where e.BusinessEntityID = edh.BusinessEntityID
and edh.DepartmentID = d.DepartmentID
and d.Name = 'Engineering';

For me personally, the first one is quite readable.  You see that we are joining tables with INNER JOIN, meaning that we are pulling the rows that match on the subsequent join clause (i.e. "join Employee with EmployeeDepartmentHistory on BusinessEntityID and include those rows").

The latter, the comma means nothing to me.  It makes me wonder what you are doing with all of those WHERE clause predicates.

The former reads more like my brain thinks.  I look at SQL all day every day and the commas for joins.  Which leads me to my next point...

There are actually other ways to get these kinds of queries to work called "joins"

They are all joins.  Even the commas is a join.  The fact that the author doesn't call them that is indeed their downfall.... it isn't obvious.  It should be obvious.  You're joining relational data, whether you specify JOIN or ,.

Performance

This is most definitely going to be RDBMS-dependent.  I can only speak on behalf of Microsoft SQL Server.  Performance-wise these are equivalent.  How do you know?  Capture the post-execution plans and see what exactly SQL Server is doing for each of these statements:

In the above image, I highlighted that I'm using both queries as above, differing only in the explicit characters for the join (JOIN vs ,).  SQL Server does the exact same thing.

Summary

Don't use commas.  Use explicit JOIN statements.


问:
Try to find a word in the dictionary that has most letters given
I recently came across an algorithm design problem that I'd like some help with:

Given some letters, for example a,e,o,g,z,k,l,j,w,n and a dictionary of words. Find a word in the dictionary that has most letters.

My first attempt:

Let us assume that the dictionary is in a tree. Start by finding the permutations of the given letters, here we could be using recursion, we can prune the recursion tree, by checking the letters in the dictionary. and we maintain a variable which holds the largest string formed till now.

How is this solution? Is there a better one?

答:
Just want to provide an alternative solution. If the number of random letters is small, you can try to generate all different permutations of the letters and check whether the dictionary contains a permutation.

For example, if you only have 3 letters "a", "b" and "c".

All the permutations are "abc", "bca", "cab", "ab", "bc", "ac", "a", "b" and "c". You can go from the longest ones to the shortest and check whether the dict contains the word.
It is more efficient when the dictionary is large and the number of random letters is small.


问:
How to implement error handling/returning while streaming a message
Say someone calls a web service on a server, the relevant data is being retrieved in batches and the message is being streamed to the client. In the middle of the message some kind of exception is encountered. My current implementation sort of just stops streaming the (in this case soap) message and starts streaming an error message, but obviously the result won't be a valid message or even valid XML.

I considered a few options, none of them seem to make much sense:

Put all the relevant data in memory and then only stream the message itself.

Do a double-take, so see if it works out with a fake stream and then do the real stream.

Stream to a disk first and then use a file input stream to stream to the client

Because this is an implementation for a generic application platform, I do not know how big the messages will be, but I have heard people are using web services in our app platform with gigabytes of data.

As you can see all have serious downsides in terms of memory/disk consumption, speed/resource efficiency or even validity of the data. How would I best implement error handling in this situation? Do I just have to pick the least worst of these options? If so I tend to favor to the current situation where the message is just invalid in cases like these, because it at least doesn't affect the base case where everything is fine.

答: How about throwing a SOAP exception from the server side and handling it on client side? This is standard way of handling soap faults.</p>


问:
Should ids be mapped to the implementation type
This is a question of model design, and hopefully some architecture nerds have strong opinions on this. I've been developing one that I will post in an answer.

Typically, in every codebase I've ever seen, if your model has an integer id, it is typed as an int and if it has a guid id it is a Guid. Is this really correct? Is this leaky abstraction? Is it a leaky abstraction worth keeping?

答:
So lately I've been thinking that semantically the id is any unique identifier; the fact that it happens to be in the integer or the guid format is an implementation detail and exposing the fact in the type is a leaky abstraction.

Thinking about it, exposing it as a string or a dedicated Identifier type has some advantages, it makes things easier to mock, repeat, or switch to ordered identifiers. Of course, the database should be whatever makes it preformant, but that is another implementation detail.

My intuition is that a dedicated Identifier type is the way to go, and if your ORM doesn't support that, a string seems a second best option.


答:
Using native types (int, Guid, etc.) instead of types which express the intent (Price, ProductIdentifier, etc.) has two drawbacks:

The type change is cascaded all over the code base, making it particularly painful.

For instance, switching from smallint (short) to uniqueidentifier (Guid) is not only painful at database level (how do you transform production data from auto-incremented fields to randomly generated UIDs?), but also at code level. You must go through the entire code base and replace short by Guid, eventually dealing with compile errors or even runtime errors (in a case of a dynamic language or when Reflection is used).

The type-related methods are spread through the code base instead of being constrained within a single class. This creates a risk of code duplication.

When you have ProductIdentifier, you can easily locate CheckIfValueInRange method: obviously, it is in ProductIdentifier class and only there.

When you have int as product identifier, you may guess that CheckIfValueInRange is in data access layer, but then it's up to you to locate it. Under pressure, some programmers may be reluctant spending time searching for the method, and write their own checker:

```<code>if (this.Id <= 0 || this.Id > 100000)
{
    throw new Exception("The product ID is invalid.");
}
</code>```

which may unfortunately differ from another implementation which is more conform to the spec:

```<code>const int MAX_ID = 100000;
if (this.Id < 0 || this.Id > MAX_ID)
{
    throw new OutsideRangeException("The identifier is outside the allowed range.");
}
</code>```

leading to refactoring/maintenance nightmare, which could easily be avoided if one were using ProductId class.

Do identifiers change their type often?

Actually, they are. A developer decides to use smallint for a small website; the website becomes hugely popular and once the limit of 32,767 values reached, the type should be changed. Another developer uses uniqueidentifier, and later it appears that there are no benefits for this type in the actual context, but having an auto-incremented, ordered value would be nice.

This makes identifiers a good candidate for using a custom type instead of a native one.

Do identifiers have business logic?

Aside range checking (see above), there are many cases where it makes sense to link the business logic to the identifier itself:

Generation of a new ID,

Checking of the existence of an ID,

Checking if the ID belongs to a specific group (such as ID 1 to 10000 is group A, and IDs higher than 10000 are group B),

etc.

Note that by removing the leaky abstraction of an ORM through the usage of a custom type, you're also creating a new leaky abstraction. Imagine you want to order something by ID. If ProductId corresponds to an auto-incremented field, it makes sense. If ProductId corresponds to a GUID, ordering doesn't make sense and you should be searching for a different criteria, like Product.CreatedTimeUtc.

Title: Should ids be mapped to the implementation type

Body:
This is a question of model design, and hopefully some architecture nerds have strong opinions on this. I've been developing one that I will post in an answer.

Typically, in every codebase I've ever seen, if your model has an integer id, it is typed as an int and if it has a guid id it is a Guid. Is this really correct? Is this leaky abstraction? Is it a leaky abstraction worth keeping?

Body:
Using native types (int, Guid, etc.) instead of types which express the intent (Price, ProductIdentifier, etc.) has two drawbacks:

The type change is cascaded all over the code base, making it particularly painful.

For instance, switching from smallint (short) to uniqueidentifier (Guid) is not only painful at database level (how do you transform production data from auto-incremented fields to randomly generated UIDs?), but also at code level. You must go through the entire code base and replace short by Guid, eventually dealing with compile errors or even runtime errors (in a case of a dynamic language or when Reflection is used).

The type-related methods are spread through the code base instead of being constrained within a single class. This creates a risk of code duplication.

When you have ProductIdentifier, you can easily locate CheckIfValueInRange method: obviously, it is in ProductIdentifier class and only there.

When you have int as product identifier, you may guess that CheckIfValueInRange is in data access layer, but then it's up to you to locate it. Under pressure, some programmers may be reluctant spending time searching for the method, and write their own checker:

if (this.Id <= 0 || this.Id > 100000)
{
    throw new Exception("The product ID is invalid.");
}

which may unfortunately differ from another implementation which is more conform to the spec:

const int MAX_ID = 100000;
if (this.Id < 0 || this.Id > MAX_ID)
{
    throw new OutsideRangeException("The identifier is outside the allowed range.");
}

leading to refactoring/maintenance nightmare, which could easily be avoided if one were using ProductId class.

Do identifiers change their type often?

Actually, they are. A developer decides to use smallint for a small website; the website becomes hugely popular and once the limit of 32,767 values reached, the type should be changed. Another developer uses uniqueidentifier, and later it appears that there are no benefits for this type in the actual context, but having an auto-incremented, ordered value would be nice.

This makes identifiers a good candidate for using a custom type instead of a native one.

Do identifiers have business logic?

Aside range checking (see above), there are many cases where it makes sense to link the business logic to the identifier itself:

Generation of a new ID,

Checking of the existence of an ID,

Checking if the ID belongs to a specific group (such as ID 1 to 10000 is group A, and IDs higher than 10000 are group B),

etc.

Note that by removing the leaky abstraction of an ORM through the usage of a custom type, you're also creating a new leaky abstraction. Imagine you want to order something by ID. If ProductId corresponds to an auto-incremented field, it makes sense. If ProductId corresponds to a GUID, ordering doesn't make sense and you should be searching for a different criteria, like Product.CreatedTimeUtc.


问:
How to model Aggregate Roots for this music event system?
Let's say I am modeling a music event system.

I have:

music events

listing events (the items in a lineup) - a listing event has acts (the artists playing in an item in the lineup - these can be collaborations)

artists (the artists that make up an act)

If I were to say that each of these were an AR - they indeed have identity.

When loading my music event AR would that mean that in order to work with the listing events within it they should be value objects?

When loading a listing event - let aside it may be a value object because I need to load it by itself - I want to modify the acts within that listing event - does that mean the acts need to be value objects?

I can't have this as one massive tree

a) some of these events are huuuuuge

b) artists play at many events - I don't think I want that data duplicated do i? Or do i? that might be ok... hmmm

What's the thinking here? how should this be modeled? Indeed - (and I know it's naughty to think about this) how would such a huge tree be persisted in something like Postgres? if I blob all the value data I lose the ability to query that data... So it's in my interests to have this data in tables where it is index-able.

I don't want to go the full CQRS/ES route with read models for querying. How can I best handle this inter-related data in a DDD manner?

答:
Here,
MusicEvent is the can have many EventListings
each EventListing could have multiple EventListingArtists

However the EventListingArtist is linked to Artist as a reference

When it comes to persisting, this should be good enough for your requirement, even if you have an event with large number of listings. Only trick is to use optimized queries when fetching data.


问:
Java applets with Safari on Windows as compared to Safari on OS X
I have a developed an Applet which works fine on Chrome/IE/FF on Windows. I am not expecting any users for Safari on Windows but there might be the odd user who may be on a Mac.

As of now, I don't have a Mac to test my applet on.

I was wondering how similar is the behaviour of Safari on Windows is as compared to Safari on a Mac as far as Java Applets go. I was wondering if testing on Safari on Windows would be good enough or do I need to buy a Mac. I know that I can never be sure without actually testing on Mac, but I am on a tight budget for this and am willing to take a risk if it's not too big.

UPDATE: The applet accesses local devices.

答: Since the Safari browser for Windows is horribly outdated (the latest download is from May 9, 2012), it is not a reliable browser to use as test and compare with the Mac version. On a project I am working on, we found there where to many differences between the Mac / iPad version of safari and the Windows version, so we decided it was worth to buy a Mac (also for debugging).</p>


问:
Should I use a large if statement inside a view or create a different view entirely?
I'm using the MVC architecture Laravel 4.2 to create a relatively complex web application. This application consists of a website which is very heavily based on whether an event has occurred or will occur. i.e. if an event is in the future, I will be displaying a countdown, whereas if it is in the past, I will be displaying information about it.

Overall, about 50% of the entire "page" markup may be unique depending on whether it has occurred or will occur.

My question is, should I be using a large if statement inside the view to display what I want based on its future/past occurrence (Yes! Otherwise you will be violating DRY with duplicated markup) or should I create a view which contains the markup for future events and another view which contains the markup for past events and get my controller to route to the applicable view (Yes! Views should be dumb and display & routing logic should be left to the controller).

What would be the correct choice in this situation, or more appropriately what questions could I ask myself to help me determine the best approach to take to this in the future?

答: I've never used Laravel, so I'm not 100% sure this will work for you, but one method I've used in the past is to include either a list or an optional value in my viewmodel that contains the name of another model to render and the data to put there. The view then iterates over the list/checks for presence of the value and includes the appropriate view definition.</p>


答:
While views shouldn't contain business logic, they still can contain basic conditional logic, loops, etc.

Since your website is “very heavily based on whether an event has occurred or will occur”, this is definitively a case where you'll have two views, not one.

What questions could I ask myself to help me determine the best approach to take to this in the future?

What you should ask yourself is whether each view corresponds to a page, as it would be defined by a person who don't know anything about the internal workings of a website.

For example, a list of products and the details of a product are logically two pages, and so you'll find two views.

Internally, it may correspond to a single AJAX request which retrieves all info about all the products. Or in order to display the details of a product, you may be doing a dozen AJAX requests to different APIs. What matters is that non-technical persons will see it as a page which shows a list of products and a page which shows the details.

On the other hand, a list of products ordered by a price and a list of products ordered by a name feel more like a single page, and will probably correspond to a single view.

Since the notion of pages is itself not very precise, you may also be guided by how much change is there between two views:

If two views are sharing no more than a header and a footer, there are chances they should remain separate.

If two views are practically a copy-paste with only a tiny part being different, they should be merged in a single view with an if/else statement.

In between, the choice remains rather subjective.

Note that having two different views doesn't necessarily lead to code duplication (or rather markup duplication in this case). Most view/template engines have:

Master views, which enable for a given template to inherit from a master template which contains the surrounding markup,

Partial views, which enable for a given template to embed markup from another template, markup which can this way be shared between several views.

Title: Should I use a large if statement inside a view or create a different view entirely?

Body:
I'm using the MVC architecture Laravel 4.2 to create a relatively complex web application. This application consists of a website which is very heavily based on whether an event has occurred or will occur. i.e. if an event is in the future, I will be displaying a countdown, whereas if it is in the past, I will be displaying information about it.

Overall, about 50% of the entire "page" markup may be unique depending on whether it has occurred or will occur.

My question is, should I be using a large if statement inside the view to display what I want based on its future/past occurrence (Yes! Otherwise you will be violating DRY with duplicated markup) or should I create a view which contains the markup for future events and another view which contains the markup for past events and get my controller to route to the applicable view (Yes! Views should be dumb and display & routing logic should be left to the controller).

What would be the correct choice in this situation, or more appropriately what questions could I ask myself to help me determine the best approach to take to this in the future?


答:
If I've understood, you have to apply business logic while streaming down the response, so you may get an error, which need to get forwarded to the client.

In this scenario, as you are composing the xml of the response "on the fly", you may add in the end of the SOAP envelope some fields which tell the client if the response was correct && complete.

In case of error, you can complete the current field (so that the envelope is well formed) and add your error fields at the end of the response.

Title: How to implement error handling/returning while streaming a message

Body:
Say someone calls a web service on a server, the relevant data is being retrieved in batches and the message is being streamed to the client. In the middle of the message some kind of exception is encountered. My current implementation sort of just stops streaming the (in this case soap) message and starts streaming an error message, but obviously the result won't be a valid message or even valid XML.

I considered a few options, none of them seem to make much sense:

Put all the relevant data in memory and then only stream the message itself.

Do a double-take, so see if it works out with a fake stream and then do the real stream.

Stream to a disk first and then use a file input stream to stream to the client

Because this is an implementation for a generic application platform, I do not know how big the messages will be, but I have heard people are using web services in our app platform with gigabytes of data.

As you can see all have serious downsides in terms of memory/disk consumption, speed/resource efficiency or even validity of the data. How would I best implement error handling in this situation? Do I just have to pick the least worst of these options? If so I tend to favor to the current situation where the message is just invalid in cases like these, because it at least doesn't affect the base case where everything is fine.


问:
Closed source proprietary web application with an AGPL source code in iframe or sub-domain
In a closed source proprietary web application, if I use an AGPL product in a sub-domain or in an iframe do I have to open-source my project?

If answer is no, is it possible that both applications can share the same database?

答:
IANAL, this is not legal advise. If you want to be sure, talk to a lawyer.

If you are offering a web-service that appears to be a single product, then it is likely that your users will treat it as such, regardless of how it is technically realized.

This means that if a sufficiently interested user tries to download the source of the site (to exercise his rights under the AGPL), you can expect a formal request to provide the sources for the proprietary part as well. And if you are unwilling to release them, possibly a lot of bad press and legal actions.

The scenario that you propose has not yet been extensively tested in a court of law, so even for a lawyer it will be hard to tell what your chances are.

The big question then is: Are you willing to risk it and perhaps become the case that establishes the case-law for the future?


问:
When testing is it OK to use a method of the subject to test another method of the subject?
I have two methods in the same helper class one that creates an image (createImage) and one that compares two images (compareImages).

```<code>Image createImage(Data data);
Boolean compareImages(Image from, Image to);
</code>```

I want to check the return of createImage against an existing image. To do this I need a method exactly like compareImages.

Is it OK to use compareImages to validate createImage even if they both belong to the subject? This feels nasty to me.

答:
Despite established wisdom in writing unit tests, Martin Fowler has said that his idea of a unit is generally

"a bunch of closely related classes and treat them as a single unit.
  Rarely I might take a subset of methods in a class as a unit."

So there's no real reason why you shouldn't be unit testing a couple of tightly related methods as one unit.
Obviously you might want to test method B independently passing in 2 images you know are the same, or are different to ensure it works, but once tested - use it as the test condition for your generation method.

There's nothing nasty in being practical, nasty is when ideology forces you to suffer.


问:
Understanding the difference between mutable and immutable classes
I faced this question in one interview. I explained that String is immutable and StringBuffer is mutable class. I don't know very much about mutable and immutable and also don't know the exact answer. What are the key concepts to be able to distinguish the two ideas?  Is there a performance impact when chosing one over the other?

答:
I would like to give a more clear picture on understanding the concept of Mutable and immutable class.

Mutable means whose value can be changed reverse is true for Immutable as already told.

Actually whenever you are calling constructor of any class we are actually allocating a memory space of that type of variable in heap.
for e.g

```<code>String str1 = new String("john");
String str2 = str1 ;
System.out.println(str1.hashCode());
System.out.println(str2.hashCode());
</code>```

Here as I have called constructor of string class a memory is allocated for this variable with value as "john" and its reference code is returned to str1 varible. In the very next statement str2 is also made pointing to the same memory location.The two println statement will output the same value indicating that both variable is pointing to same memory location. Now write this code

```<code>str2 = "monk";
System.out.println(str2.hashCode());
</code>```

The moment you write this line a new memory space for string type data is created in heap ,its value is set to "monk" and the reference of the same is returned to str2 and hence str2 is no more pointing to same memory location and hence you will get different hashcode value in println statement.
The reason for this is "String is immutable class". So you can not change its value by any means.
For StringBuffer Class you can check its mutability using this code

```<code>StringBuffer sb = new StringBuffer("mohan");
StringBuffer sb1 = sb.append(" kumar");
System.out.println(sb.hashCode());
System.out.println(sb1.hashCode()+" - "+(sb1==sb)+" - "+sb.hashCode());
</code>```

Body:
I would like to give a more clear picture on understanding the concept of Mutable and immutable class.

Mutable means whose value can be changed reverse is true for Immutable as already told.

Actually whenever you are calling constructor of any class we are actually allocating a memory space of that type of variable in heap.
for e.g

String str1 = new String("john");
String str2 = str1 ;
System.out.println(str1.hashCode());
System.out.println(str2.hashCode());

Here as I have called constructor of string class a memory is allocated for this variable with value as "john" and its reference code is returned to str1 varible. In the very next statement str2 is also made pointing to the same memory location.The two println statement will output the same value indicating that both variable is pointing to same memory location. Now write this code

str2 = "monk";
System.out.println(str2.hashCode());

The moment you write this line a new memory space for string type data is created in heap ,its value is set to "monk" and the reference of the same is returned to str2 and hence str2 is no more pointing to same memory location and hence you will get different hashcode value in println statement.
The reason for this is "String is immutable class". So you can not change its value by any means.
For StringBuffer Class you can check its mutability using this code

StringBuffer sb = new StringBuffer("mohan");
StringBuffer sb1 = sb.append(" kumar");
System.out.println(sb.hashCode());
System.out.println(sb1.hashCode()+" - "+(sb1==sb)+" - "+sb.hashCode());


答:
It's important to understand that a single method may not be your "unit". To give a contrived example, if (for some reason) you created a class with public methods:

```<code>Add(object key, object value);
Get(object key);
</code>```

which just wrapped a private Dictionary, it would be inconceivable to test just one of those methods at a time, independent of the other.

For the exact situation you describe, though, it may not be so clear-cut. It sounds like rather than being intrinsically dependent on each other for their function like the above example, your methods are linked only in that one happens to be useful in a test of the other.

In this case, it might be informative to start with the idea of duplicating method B exactly in your test code and asking whether or not this is a violation of DRY. Obviously you're repeating your code, but as demonstrated by Mathias Verraes, this doesn't always mean a DRY violation. A good way to think about this is: when one of these methods changes, will the other one always require the same change?

It's hard for me to judge without knowing the exact methods, but it's quite possible that you might want, for example, your test version of B not to do some validation that the production version does, or similar. In this case, having two versions may be fine.

There are additional practical trade-offs:

If you do use method B in testing method A, then a bug in method B could mask a bug in method A, or at least prevent you from knowing the true result of your test of method A. This is similar to the reason that people generally try to avoid multiple asserts.

On the other hand, if you make a test version of method B and allow it to vary independently of the production version, the test version itself will not be as well tested, which could be a problem if the method is sufficiently complex or liable to change.

Title: When testing is it OK to use a method of the subject to test another method of the subject?

Body:
I have two methods in the same helper class one that creates an image (createImage) and one that compares two images (compareImages).

```<code>Image createImage(Data data);
Boolean compareImages(Image from, Image to);
</code>```

I want to check the return of createImage against an existing image. To do this I need a method exactly like compareImages.

Is it OK to use compareImages to validate createImage even if they both belong to the subject? This feels nasty to me.

Body:
It's important to understand that a single method may not be your "unit". To give a contrived example, if (for some reason) you created a class with public methods:

Add(object key, object value);
Get(object key);

which just wrapped a private Dictionary, it would be inconceivable to test just one of those methods at a time, independent of the other.

For the exact situation you describe, though, it may not be so clear-cut. It sounds like rather than being intrinsically dependent on each other for their function like the above example, your methods are linked only in that one happens to be useful in a test of the other.

In this case, it might be informative to start with the idea of duplicating method B exactly in your test code and asking whether or not this is a violation of DRY. Obviously you're repeating your code, but as demonstrated by Mathias Verraes, this doesn't always mean a DRY violation. A good way to think about this is: when one of these methods changes, will the other one always require the same change?

It's hard for me to judge without knowing the exact methods, but it's quite possible that you might want, for example, your test version of B not to do some validation that the production version does, or similar. In this case, having two versions may be fine.

There are additional practical trade-offs:

If you do use method B in testing method A, then a bug in method B could mask a bug in method A, or at least prevent you from knowing the true result of your test of method A. This is similar to the reason that people generally try to avoid multiple asserts.

On the other hand, if you make a test version of method B and allow it to vary independently of the production version, the test version itself will not be as well tested, which could be a problem if the method is sufficiently complex or liable to change.