问:
Database design/relationship for threading messages
What's the database design or business logic for creating an app for messaging between users?

I am having difficulties with choosing how to approach the relationship between each Conversation of User Thread. I show this figure, but it was really hard to grasp the concept

How all this threading message works (like Gmail or Facebook)?

答:
I would compose the thread of messages and then make the subsequent threads subordinate to the messages they are replies to.

For instance:

Thread A is started.

Thread A receives three messages.

Fourth Message is added and replies to message 3, creating a new thread.

Thread B's parent is set to message 3.

Fourth Message becomes part of ThreadB.

Fifth Message is a reply to the original message and is added to ThreadA.

Sixth Message is a reply to message three and is added to ThreadB.

Then when you're rendering the thread, after displaying a message query for any threads who's parent message match the message you just displayed. If there are any for the message simply render that thread before going to the next message.

I've included a basic (probably technically flawed) diagram illustrating the relationships in the database.

Given the above sample it would look like this when displayed:

(ThreadA)

Message 1

Message 2

Message 3

(ThreadB)

Message 4

Message 6

Message 5

Update: Fixed some relationship and multiplicity issues. I updated it to include textual representations of the relationships as well. Any input on validity would be helpful, been a while since I've done one. I've been using Model Based ORM nearly exclusively lately. Also keep in mind while it use the basic format of IDEF1X. It contains specifics, and IDEF1X is a semantics based modelling system.


问:
Why REST Api do not follow the Facade design pattern
In comparing REST [api] structure with a OO model, I see these similarities:

Both:

Are data oriented

REST = Resources

OO = Objects

Surround operation around data

REST = surround VERBS (Get, Post, ...) around resources

OO = promote operation around objects by encapsulation

However, good OO practices do not always stand on REST apis when trying to apply the facade pattern for instance:
   in REST, you do not have 1 controller to handle all requests AND you do not hide internal object complexity.

On the contrary, REST promotes resources publishing of all relations with a resource and other on at least two forms:

via resource hierarchy relations (A contact of id 43 is composed of an address 453) : /api/contacts/43/addresses/453

via links in a REST json response:

```<code>>> GET /api/contacts/43
<< HTTP Response {
   id: 43, ...
   addresses: [{
      id: 453, ...
   }],
   links: [{
      favoriteAddress: {
          id: 453
      }
   }]
}
</code>```

Coming back to OO, the facade design pattern respect a Low Coupling between an objectA and its 'objectB client' and High Cohesion for this objectA and its internal object composition (objectC, objectD).  With the objectA interface, this allow a developer to limit impact on objectB of the objectA internal changes (in objectC and objectD), as long as the objectA api (operations) are still respected.

In REST, the data (resource), the relations (links), and the behavior (verbs) are exploded in different elements and available to the web.

Playing with REST, I always have an impact on code changes between my client and server:   Because I have High Coupling between my Backbone.js requests and Low Cohesion between resources.

I never figured out how to let my Backbone.js javascript application deal with "REST resources and features" discovery promoted by REST links.  I understand that the WWW is meant to be served by multi servers, and that the OO elements had to be exploded to be serviced by many hosts in there, but for a simple scenario like "saving" a page showing a contact with its addresses, I end up with:

```<code>GET /api/contacts/43?embed=(addresses)
[save button pressed]
PUT /api/contacts/43
PUT /api/contacts/43/addresses/453
</code>```

which lead me to move the saving action atomic transactional responsibility on the browsers applications (since two resources can be addressed separately).

With this in mind, if I cannot simplify my development (Facade design patterns not applicable), and if I bring more complexity to my client (handling transactional atomic save), where is the benefit of being RESTful ?

答:
With this in mind, if I cannot simplify my development (Facade design patterns not applicable), and if I bring more complexity to my client (handling transactional atomic save), where is the benefit of being RESTful ?

The answer to "where is the benefit of being RESTful?" is thoroughly analyzed and explained here: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

The confusion in this question though is that it is not about characteristics of REST and how to cope with them, but assuming the design of the URLs you came up for your example system has something to do with being RESTful. After all, REST states that there are things called resources and an identifier should be provided for those that need to be referenced, but it does not dictate that, say, entities in your E.R. model should have 1-1 correspondence with the URLs you created (neither that the URLs should encode the cardinality of the E.R. relationships in the model).

In the case of contacts and addresses, you could have defined a resource that jointly represents these informations as a single unit, even though you may want to extract and save these informations in, say, different relational DB tables, whenever they are PUT or POSTed.

OwnerDisplayName: Alain

ContentLicense: CC BY-SA 3.0


问:
Tricky logic puzzles - Are they really useful in assessing programming skills?
In the last interview I attended, I was asked to solve a puzzle where I was expected to measure exactly blah liters of water given two buckets with capacities - blah and blah liters respectively. I was unable to solve the puzzle in given time (~5 minutes).

The interviewer was a bit disappointed and said a programmer has got to have "these" skills. I didn't get what skills he was talking about.

I have always felt strange about these kind of puzzles that are normally asked at programming job interviews. I do not understand what, if at all, is the connection between such puzzles and programming. Exactly what skills do interviewers intend to assess with such puzzles?

答:
Two points:

Programming is mainly different from puzzle solving. It is perfrectly explained by Steve McConnell at "Code Complete":

What? You don’t have to be superintelligent?
No, you don’t. Nobody is really smart enough to program computers. Fully understanding an average program requires an almost limitless capacity to absorb details and an equal capacity to comprehend them all at the same time. The way you focus your intelligence is more important than how much intelligence you have.
As Chapter 5 mentioned, at the 1972 Turing Award Lecture, Edsger Dijkstra delivered a paper titled “The Humble Programmer.” He argued that most of programming is an attempt to compensate for the strictly limited size of our skulls. The people who are best at programming are the people who realize how small their brains are. They are humble. The people who are the worst at programming are the people who refuse to accept the fact that their brains aren’t equal to the task. Their egos keep them from being great programmers. The more you learn to compensate for your small brain, the better a programmer you’ll be. The more humble you are, the faster you’ll improve.

Such puzzles can be useful during interview, but Only if the interviewer looks on the Process, not result itself.

But ideally the puzzles should be more complicated and programming related (like small 2-hours project), in my opinion.
The thing is that interviewers are people and doesn't have perfect "interview skills".


问:
How is IntelliJ better than Eclipse?
I know there have been questions like What is your favorite editor/IDE?, but none of them have answered this question: Why spend the money  on IntelliJ when Eclipse is free?

I'm personally a big IntelliJ fan, but I haven't really tried Eclipse. I've used IntelliJ for projects that were Java, JSP, HTML/CSS, Javascript, PHP, and Actionscript, and the latest version, 9, has been excellent for all of them.

Many coworkers in the past have told me that they believe Eclipse to be "pretty much the same" as IntelliJ, but, to counter that point, I've occasionally sat behind a developer using Eclipse who's seemed  comparably inefficient (to accomplish roughly the same task), and I haven't experienced this with IntelliJ. They may be on par feature-by-feature but features can be ruined by a poor user experience, and I wonder if it's possible that IntelliJ is easier to pick up and discover time-saving features.

For users who are already familiar with Eclipse, on top of the real cost of IntelliJ, there is also the cost of time spent learning the new app. Eclipse gets a lot of users who simply don't want to spend $250 on an IDE.

If IntelliJ really could help my team be more productive, how could I sell it to them? For those users who've tried both, I'd be very interested in specific pros or cons either way.

答:
I hear the difference with IntelliJ is that they are much more likely to fix and close bugs that you submit. That could make a big difference if there is some Eclipse bug that is blocking you.

On the other hand, you cannot look at IDEs in isolation; you need to look at the ecosystem. Here, I think Eclipse has an advantage (similar to Firefox's advantage over Chrome*): There are many more plug-ins available, and developers are much more likely to write an Eclipse plug-in than otherwise.

[Tangent: *For Firefox I'm thinking of Zotero and HTTPS-Everywhere. I use both Chrome and Firefox, but some things Chrome just can't handle. Also, when making handouts, I really do need print preview.]

Title: How is IntelliJ better than Eclipse?

ContentLicense: CC BY-SA 2.5


问:
Search Substring in String collection
I have a big collection of strings a[1], …, a[N] where N is about several millions. I am provided a string m and I need to iterate over all the strings a[i] that contain m. In other words, I need to find all the strings a[i] having m as substring.

What would be the most efficient data structure for that problem? I need to be very careful with memory as I am working with a big number of strings.

答:
if you skip n letters then you just need to check if the letter is in the first n of the input string and then check back again to see if it matches

this means creating a data structure (just a 256 long array with information about where the string might start) for the input string but allows the other collection of strings to remain unordered

also check out this blog post, and the boyer moore algorithm

Title: Search Substring in String collection


问:
Data duplication vs Encapsulating. Which design to use?
The problem that I face is how to combine encapsulating and optimal memory use.

I can't show you my code and therefore explain it on extensive (I hope) example.

Let's say we need to have a database of mans. We want to know only 2 things about those people:

Age of the man (in hours from birth).

Name of the town he lives in.

The convenient and natural way to manage this data is to create an object, which corresponds to a man and store it in an array:

```<code>class OMan1 {
  public:
    OMan( const int &age, const astring &t ): fAge(age), fTown(t) {}
    const int& age() const: { return fAge; }
    const astring& Town() const: { return fTown; }
    astring FullId() const: { return fTown+fAge; }
  private:
    int fAge;
    astring fTown;
}

OMan mans[N];
</code>```

Here our OMans are self-containing object and everything fills nice.

Except of the fact that we clone names of the towns thousands of times, and waste memory and execution time this way.

An improvement we can do is to make an independent array for town names and for each OMan, store only the age, an id of the town and a pointer to towns array:

```<code>class OMan2 {
  // same functionality as for OMan1
    int fAge;
    int fTownId;
    astring* fTowns;
}
</code>```

object is still self-contained, sizeof(int) + sizeof(void*) is much less then sizeof(astring), we win a lot. But still it is factor of 2-3 more than sizeof(fAge) and we repeat fTowns billions of times.

Memory optimisation is crucial for me, therefore what I do is keeping only fAge and fTownId and move such functionality as Town() and FullId() out of the OMan class to some class like OManDataBase:

```<code>class OMan3 {
  public:
    OMan( const int &age, const int &tid ): fAge(age), fTownId(tid) {}
    const int& age() const: { return fAge; }
    const int& TownId() const: { return fId; }
    // const astring& Town() const: { return fTown; }
    // astring FullId() const: { return fTown+fAge; }
  private:
    int fAge;
    int fTownId;
}

class OManDataBase {
  // constructor, destructor
    const int& age( const int& i) const: { return fMans[i].TownId()]; }
    const astring& Town( const int& i) const: { return fTown[fMans[i].TownId()]; }
    const astring& FullId( const int& i) const: { return Town(i)+age(i); }
  private:
    vector<OMan3> fMans;
    vector<astring> fTowns;
}
</code>```

And OMan3 now is not self contained object. It doesn't know it's fullname, for instance. That means that if I need to do some data processing with one man I have to use whole OManDataBase instance:

```<code>OBillType47 NewBillType47( const OManDataBase &db, int i ) { ... }
</code>```

instead of

```<code>OBillType47 NewBillType47( const OMan &m ) { ... }
</code>```

encapsulation has been broken here and the code readability has been clearly decreased. (I put Type47 to emphasise that I can have a lot of functions, which works with Oman-S and can't include all of them into OManDataBase class).

I wonder is there any other way(-s) to solve data duplication problem, keeping objects as self-containing as possible?

答:
Flyweight pattern is the right idea.

I found this older Stack Overflow post about the Boost Flyweight Library that might fit your needs.  I'm not much of a C++ user and have never used it, so use at your own risk!


问:
What do programmers "micro-optimize" for today?
Back in the "good ol' days," when we would copy shareware onto floppies for friends, we also used a fair bit of assembly. There was a common practice of "micro-optimization," where you would stare and stare at lines of assembly until you figured out a way to express it in one fewer instruction. There was even a saying, which was mathematically impossible, that "You can always remove one more instruction." Given that changing runtime performance by small constant factors isn't a major issue for (most) programming today, are programmers transferring these micro-optimization efforts elsewhere?

In other words, Can a best-practice be taken to an extreme state where it's no longer adding anything of value? And instead is wasting time?

For example: Do programmers waste time generalizing private methods that are only called from one place? Is time wasted reducing test case data? Are programmers (still) overly concerned about reducing lines of code?

There are two great examples of what I'm looking for below: (1) Spending time finding the right variable names, even renaming everything; and (2) Removing even minor and tenuous code duplication.

Note that this is different from the question "What do you optimize for?", because I'm asking what other programmers seem to maximize, with the stigma of these being "micro" optimizations, and thus not a productive use of time.

答:
Micro-optimization in terms of runtime performance is hardly a closed problem even today (although it might be less common).  I occasionally have to explain to people that the overhead of allocating an extra object every request or adding an extra function call is negligible.

Aside from that, I also see programmers micro-optimize for simplicity (including myself).  I have yet to work somewhere that I didn't have to explain the difference between simplicity and simplism.


问:
What is the most efficient way to manage large collection
I have a rather difficult problem:

I periodically receive a Dictionary<decimal, int> subDict containing 100 records where

decimal is a Price

and int is Amount

The outcome I need is a dataGrid showing prices with amounts. But I cannot display subList directly, because sublist is often missing some prices:

subDict:

Price    |  Amount

100.0001 |  192

100.0005 |  123

100.0007 |  2

100.0008 |  123

above needs to be displayed as:

Price    |  Amount

100.0001 |  192

100.0002 |  0

100.0003 |  0

100.0004 |  123

100.0005 |  0

100.0006 |  0

100.0007 |  2

100.0008 |  123

I have to store a price with 4 decimal places, however the range of Price can be anything from 0 to 10 000. Final requirement is - once I click on the amount in the DataGrid, I need to be able to get access to all values in the row.

So I decided to ask for some help - can anyone think of a good strategy of dealing with such a problem?

One idea that came to my mind would be to initialize Dicionary<decimal, int> bigDictionary containing every price in the range.

However, if I initialize this dictionary with all the prices, with specified granularity (i.e. step of 0.0001) I end up with 10 000 * 10 000 records. That is rather large list, which takes considerable amount of memory. Of course it is easy to bind it to DataGrid in WPF so this can sort of work, but is in my opinion very inefficient.

The other idea I have would be to save incoming prices to a Dictionary<decimal, int> smallDict but then I would need to have some sort of mechanism to update DataGrid in such a way, that price gaps would be filled on the fly. Also I would somehow need to keep the dataGrid sorted by the price.

The first idea I am able to implement. The second one, I have no idea about so any code would be excellent.

I would be greatfull for any ideas!
Thank you for your time

答:
Considering creating some type of drill-down interface. Rather than immediately trying to display 10,000 * 10,000 records to the user, summarize those 100,000,000 records into 100 ranges. Let the user select the desired range and then "zoom in" and split that range into 100 sub-ranges. Keep repeating until you get to the detail level and show the 100 entries that belong to the parent range.

Assuming your price range is 0.0000 to 9,999.9999 and you want to display 100 records at a time, your 100 top level ranges would be 0 - 99.9999, 100 - 199.9999, Etc. The "width" of your ranges would be:

100 (Top Level)

1

.01

.0001 (Detail Level)

This takes care of your display problem. What about the memory-usage issue? Create a view dictionary and bind your grid to it. Every time the user zooms in or out, simply populate this dictionary with the summarized or detail data that correspond to the current range and zoom level. You'll probably need some extra controls to show the current zoom/range to provide a way for the user zoom in and out.


问:
How do you identify a problem as being suitable for dynamic programming?
I have been reading up on dynamic programming lately. Would like to hear from someone who started from scratch and now is pretty good at identifying and solving DP problems. I am struggling in identifying these problems as DP and framing a concise solution.

I have gone through most of the beginner DP problems and MIT resources etc

答:
Most dynamic programming problems can be solved via memoization.  Memoization is normally both more intuitive and easier to code.  You may find it helpful to think in terms of memoization instead of DP.

It's usually easier to intuit whether a problem is well-suited towards memoization (the steps are the same as Slivvz's answer, but I think the mental shift is a little shorter).  However, once you've solved a problem via memoization, you can examine how your memo cache is being filled and then fill it in order, without recursion...which changes your algorithm to a dynamic programming algorithm.

See also

Dynamic programming and memoization: bottom-up vs top-down approaches.

ContentLicense: CC BY-SA 4.0


问:
How is localStorage different from indexedDB?
localStorage and indexedDB are used for offline storage of data in HTML5. What are their key differences and which one is preferable in what situations?</p>

答:
On the surface the two technologies may seem directly comparable, however if you spend some time with them you'll soon realize they are not. They were designed to achieve a similar goal, client side storage, but they approach the task at hand from significantly different perspectives and work best with different amounts of data.

localStorage, or more accurately Web Storage, was designed for smaller amounts of data. It's essentially a strings only key - value storage, with a simplistic synchronous API. That last part is key. Although there's nothing in the specification that prohibits an asynchronous Web Storage, currently all implementations are synchronous (i.e. blocking requests). Even if you didn't mind using a naive key - value storage for larger amounts of data, your clients will mind waiting forever for your application to load.

indexedDB, on the other hand, was designed to work with significantly larger amounts of data. First, in theory, it provides both a synchronous and an asynchronous API. In practice, however, all current implementations are asynchronous, and requests will not block the user interface from loading. Additionally, indexedDB, as the name reveals, provides indexes. You can run rudimentary queries on your database and fetch records by looking up theirs keys in specific key ranges. indexedDB also supports transactions, and provides simple types (e.g. Date).

At this point, indexedDB might seem the superior solution for every situation ever. However, there's a penalty for all its features: Compared to Web Storage, its API is quite complicated. indexedDB assumes a general familiarity with database concepts, whereas with Web Storage you can jump right in. If you have ever worked with cookies, you won't have an issue working with Web Storage. Also, in general you'll need to write more code in indexedDB to achieve exactly the same result as in Web Storage (and more code = more bugs). Furthermore, emulating Web Storage for browsers that don't support it is relatively straightforward. With indexedDB, the task wouldn't be worth its time. Lastly, before you dive into indexedDB, you should first take a look at the Quota API.

At the end of the day, it's completely up to you if you use Web Storage or indexedDB, or both, in your application. A good use case for Web Storage would be to store simple session data, for example a user's name, and save you some requests to your actual database. indexedDB's additional features, on the other hand, could help you store all the data you need for your application to work offline.


问:
Approach to develop an inline editor for enumerated lists

Background

Looking to develop a WYSIWYG editor for ordered lists so that people can directly edit lists of instructions on a web page.

Problem

The contentEditable attribute is woefully immature for editing ordered lists (e.g.,
...
). I discovered four bugs in Firefox 25.0.1 within seconds of editing; Chromium was acceptable; IE8+ will likely border on nightmarish.

A number of inline editors exist, and I've gone through almost all of them. Even the lightest-weight editors are far too heavy, or have too many bugs, for accomplishing such a seemingly simple task.

Question

What approach would you take to developing a browser-based WYSIWYG inline editor for enumerated lists? Some of my ideas have included:

Take the most robust inline editor and trim back all needless functionality.

Build up an inline editor that meets my needs.

Both approaches will be time-consuming.

What other approaches are worth considering?

答:
If you only need simple editing I would recommend implementing your own using a client side MVC framework. check out http://todomvc.com/ for some simple examples of editable lists. You can then extend on your favorite to add advanced features and use one of those plugins if needed.

You can get the code for a basic list editing and be set up for a snappy and scalable web app.


问:
CSS structure for creating responsive websites
I'm a back-end engineer who works on a small team so occasionally needs to do some front-end. I like to develop a good workflow and project structure before I start anything, so I'm wondering about creating a responsive front-end for a web app.

What's a best-practice way to strcture CSS for creating responsive websites that need to "scale down" for smaller screens? Specifically: do you create the mobile version first, then expand the code with min-width media queries in the CSS? Or do you do the opposite, creating the desktop-resolution version first?

Secondly, do you define multiple element selectors and definitions in the same media query? Or do you define a media query for each element and selector? It would seem that the second method would make for more readable code perhaps -- although it's certainly more frustrating to "tweak" a working site to create a new version with media queries rather than simple fence-off the old settings in one media query and re-style the necessary parts from the new version from scratch.

答:
Use a css framework and learn from them

Twitter bootstrap

Foundation

Create the mobile version first.

Forces you to prioritize important elements, creating an awesome UX

Use multiple CSS rules within the same media query


问:
Should code-behind in WPF be considered part of the view?
I've read plenty of articles around different patterns in use with WPF and this is something I've yet to understand: should a code-behind file be considered part of the view? As a consequence, should code-behind files be allowed utilise knowledge of specific elements in the markup?

I have a number of scenarios where the controls which are present in a view are influenced by data in the view model (eg a button for each list item). Currently, I handle these kinds of scenarios in the relevant code-behind file. To me, this feels like an implementation detail of the view and thus part of it; another view of the same view model might choose a list box of list items for example).

答:
It IS part of the view! Ever noticed your xaml.cs is a partial class? So yes, your code behind know and can use specific elements of the view.

Personnally I do my best to stay away from this and use MVVM, but it all depends on what application you are buiding.


问:
success:/failure: blocks vs completion: block
I see two common patterns for blocks in Objective-C. One is a pair of success:/failure: blocks, the other is a single completion: block.

For example, lets say I have a task that will return an object asynchronously and that task might fail. The first pattern is -taskWithSuccess:(void (^)(id object))success failure:(void (^)(NSError *error))failure. The second pattern is -taskWithCompletion:(void (^)(id object, NSError *error))completion.

success:/failure:

```<code>[target taskWithSuccess:^(id object) {
    // W00t! I've got my object
} failure:^(NSError *error) {
    // Oh noes! report the failure.
}];
</code>```

completion:

```<code>[target taskWithCompletion:^(id object, NSError *error) {
    if (object) {
        // W00t! I've got my object
    } else {
        // Oh noes! report the failure.
    }
}];
</code>```

Which is the preferred pattern? What are the strengths and weaknesses? When would you use one over the other?

答:
This feels like a complete copout, but I don't think there is a right answer here. I went with the completion block simply because error handling may still need to be done in the success condition when using success/failure blocks.

I think the final code will look something like

```<code>[target taskWithCompletion:^(id object, NSError *error) {
    if (error) {
        // Oh noes! report the failure.
    } else if (![target validateObject:&object error:&error]) {
        // Oh noes! report the failure.
    } else {
        // W00t! I've got my object
    }
}];
</code>```

or simply

```<code>[target taskWithCompletion:^(id object, NSError *error) {
    if (error || ![target validateObject:&object error:&error]) {
        // Oh noes! report the failure.
        return;
    }

    // W00t! I've got my object
}];
</code>```

Not the best chunk of code and nesting it gets worse

```<code>[target taskWithCompletion:^(id object, NSError *error) {
    if (error || ![target validateObject:&object error:&error]) {
        // Oh noes! report the failure.
        return;
    }

    [object objectTaskWithCompletion:^(id object2, NSError *error) {
        if (error || ![object validateObject2:&object2 error:&error]) {
            // Oh noes! report the failure.
            return;
        }

        // W00t! I've got object and object 2
    }];
}];
</code>```

I think I'll go mope for a while.

Body:
This feels like a complete copout, but I don't think there is a right answer here. I went with the completion block simply because error handling may still need to be done in the success condition when using success/failure blocks.

I think the final code will look something like

[target taskWithCompletion:^(id object, NSError *error) {
    if (error) {
        // Oh noes! report the failure.
    } else if (![target validateObject:&object error:&error]) {
        // Oh noes! report the failure.
    } else {
        // W00t! I've got my object
    }
}];

or simply

[target taskWithCompletion:^(id object, NSError *error) {
    if (error || ![target validateObject:&object error:&error]) {
        // Oh noes! report the failure.
        return;
    }

    // W00t! I've got my object
}];

Not the best chunk of code and nesting it gets worse

[target taskWithCompletion:^(id object, NSError *error) {
    if (error || ![target validateObject:&object error:&error]) {
        // Oh noes! report the failure.
        return;
    }

    [object objectTaskWithCompletion:^(id object2, NSError *error) {
        if (error || ![object validateObject2:&object2 error:&error]) {
            // Oh noes! report the failure.
            return;
        }

        // W00t! I've got object and object 2
    }];
}];

I think I'll go mope for a while.


问:
How to unit test a web client?
I am having a lot of trouble understanding how to unit test my web client.

I have just finished a project using TDD for the first time - this project hd no external dependencies such as API calls or databases, it was pure C# code. I definitely saw the benefits of using TDD and I would like to continue practising it.

My next project involves writing a SOAP client. I'm struggling to get past the first test which is using a simple IClient that logs in to the API successfully.

Here is the IClient interface:

```<code>public interface IClient
{
    bool IsLoggedIn { get; }
    bool Login(out string error);
}
</code>```

I have no idea how I would go about testing this. I'm thinking the unit test method would be something like Login_WithValidCredentials_ReturnsTrue, but I'm not sure how I could do this without actually simulating every possible response from the API. Is this code actually unit testable, or should this be left to an integration test.

If anyone could give me an example of a simple unit test then I would be very grateful (I am using Moq).

答:
Unit tests should run fast and have no external dependencies. Integration tests should cover methods that call web services.

You cannot unit test authentication logic on the client, you will have to do it on the server:

```<code>[WebMethod]
Authenticator{
 bool Login(Credentials credentials){
   return TestableClass.Login(credentials);
 }
}
</code>```

now you can write a unit test on the server

```<code>Login_WithValidCredentials_ReturnsTrue(){
   // test TestableClass.login here
}
</code>```

You can also test client side code that uses the service. say you have some code like this: (pardon my c#)

```<code>Class LoggerOnner{
  public LoggerOnner(IClient client, Response response){
    this.client = client
    this.page = page
  }

  Login() {
   if(this.client.Authenticate())
       response.sendPage("authenticated.aspx");
   else{
       response.sendError()
   }
  }
}
</code>```

You can test that it uses your Client correctly (how i imagine moc works :)

```<code>IClient mocClient= moq.Create(IClient).Authenticate( x-> return true );
Request moxRequest = moq.Create(Request);

LoggerOnner lo = new LoggerOnner(mocClient, mocRequest);

Assert( mocRequst.sendPage().calledWithArgs("authenticated.aspx"));
</code>```

TLDR; don't unit test your Client class, make it small and test everything else

Title: How to unit test a web client?

Body:
Unit tests should run fast and have no external dependencies. Integration tests should cover methods that call web services.

You cannot unit test authentication logic on the client, you will have to do it on the server:

[WebMethod]
Authenticator{
 bool Login(Credentials credentials){
   return TestableClass.Login(credentials);
 }
}

now you can write a unit test on the server

Login_WithValidCredentials_ReturnsTrue(){
   // test TestableClass.login here
}

You can also test client side code that uses the service. say you have some code like this: (pardon my c#)

Class LoggerOnner{
  public LoggerOnner(IClient client, Response response){
    this.client = client
    this.page = page
  }

  Login() {
   if(this.client.Authenticate())
       response.sendPage("authenticated.aspx");
   else{
       response.sendError()
   }
  }
}

You can test that it uses your Client correctly (how i imagine moc works :)

IClient mocClient= moq.Create(IClient).Authenticate( x-> return true );
Request moxRequest = moq.Create(Request);

LoggerOnner lo = new LoggerOnner(mocClient, mocRequest);

Assert( mocRequst.sendPage().calledWithArgs("authenticated.aspx"));

TLDR; don't unit test your Client class, make it small and test everything else


问:
What's the difference between robustness and fault-tolerance?
Systems / programs / distributed algorithms / ... are often described with the predicate robust or fault-tolerant.

What is the difference?

Details:

When I google for +robust +"fault-tolerant", I only get two hits, both unhelpful.

When I googlescholar for the terms, I find a lot of papers that have both terms in their title. Unfortunately, they do not precisely define the terms :( But since they use both terms, it seems that neither implies the other.

答:
Both describe the consistency of an application's behavior, but "robustness" describes an application's response to its input, while "fault-tolerance" describes an application's response to its environment.

An app is robust when it can work consistently with inconsistent data. For example: a maps application is robust when it can parse addresses in various formats with various misspellings and return a useful location. A music player is robust when it can continue decoding an MP3 after encountering a malformed frame. An image editor is robust when it can modify an image with embedded EXIF metadata it might not recognize -- especially if it can make changes to the image without wrecking the EXIF data.

An app is fault-tolerant when it can work consistently in an inconsistent environment. A database application is fault-tolerant when it can access an alternate shard when the primary is unavailable. A web application is fault-tolerant when it can continue handling requests from cache even when an API host is unreachable. A storage subsystem is fault-tolerant when it can return results calculated from parity when a disk member is offline.

In both cases, the application is expected to remain stable, behave uniformly, preserve data integrity, and deliver useful results even when an error is encountered. But when evaluating robustness, you may find criteria involving data, while when evaluating fault-tolerance, you'll find criteria involving uptime.

One doesn't necessarily lead to the other. A mobile voice-recognition app can be very robust, providing an uncanny ability to recognize speech consistently in a variety of regional accents with huge amounts of background noise. But if it's useless without a fast cellular data connection, it's not very fault-tolerant. Similarly, a web publishing application can be immensely fault-tolerant, with multiple redundancies at every level, capable of losing whole data centers without failing, but if it drops a user table and crashes the first time someone registers with an apostrophe in their last name, it's not robust at all.

If you're looking for scholarly literature to help describe the distinction, you might look in specific domains that make use of software, rather than broadly software in general. Distributed applications research might be fertile ground for fault-tolerance criteria, and Google has published some of their research that might be relevant. Data modeling research likely addresses questions of robustness, as scientists are particularly interested in the properties of robustness that yield reproducible results. You can probably find papers describing statistical applications that might be helpful, as in climate modeling, RF propagation modeling, or genome sequencing. You'll also find engineers discussing "robust design" in things like control systems.

The Google File System whitepaper describes their approach to fault-tolerance problems, which generally involves the assumptions that component failures are routine and so the application must adapt to them:

http://static.googleusercontent.com/media/research.google.com/en/us/archive/gfs-sosp2003.pdf ("Our system provides fault tolerance by constant monitoring, replicating crucial data, and fast and automatic recovery.")

This project for a class at Rutgers supports a "component-failure" oriented definition of "fault tolerance":

http://www.ece.rutgers.edu/~parashar/Classes/03-04/ece572/papers/cristian93understanding.pdf ("Some systems are designed to be fault-tolerant: they either exhibit a well-defined failure behavior when components fail or mask component failures to users…")

There are loads of papers on "robust modeling XYZ", depending on the field you investigate. Most will describe their criteria for "robust" in the abstract, and you'll find it all has to do with how the model deals with input.

This brief from a NASA climate scientist describes robustness as a criteria for evaluating climate models:

http://www.giss.nasa.gov/research/briefs/schmidt_04/ ("…robust in that it does not depend significantly on the specifics of parameterization and spatial representation.")

This paper from an MIT researcher examines wireless protocol applications, a domain in which fault-tolerance and robustness overlap, but the authors use "robust" to describe applications, protocols, and algorithms, while they use "fault-tolerance" in reference to topology and components:

http://people.csail.mit.edu/grishac/papers/allerton.pdf ("In short, these uses require robust applications that always operate correctly, even under unpredictable conditions.")


问:
Is it possible to be good at both programming and graphic design?
The stereotypical view of a programmer can't do graphics very well, from what I've read and seen. However, I love programming (preferably OOP, PHP, C++, Objective-C) and can't deny the fact I have a unique taste in web design and others have said I am doing well at it (CSS). I thought to myself "Hey, wait, I'm a programmer - how can I design well?". Question is: is it possible to be good at programming and designing? Does anyone here feel the same?

For the record: actual images I have created have been called programmer art several times before by friends

答: The correct stereotype is "most programmers can't design"; which is generally true. However, it is not true that if you're a programmer that means you cannot design.


问:
Potential issues with code reviews
for clarity, code review = a team meeting and reviewing/sharing code

What are the potentially negative aspects of the code review process in a development environment?
What comes to mind for me

Strong criticism can lead to negative interactions and feelings of
animosity between colleagues.

Laziness to read and understand new    code can lead to apathetic and
very general feedback.

Considerable    Time investment is    required to organize and
execute the review    process.

There must be more than this though, What negative things have you guys noticed or experienced?

答:
Strong criticism can lead to negative interactions and feelings of
  animosity between colleagues.

It's most likely going to be this. Some people don't like to hear that what they did was wrong, or rather, not quite right. The team as a whole has to agree on what is acceptable, but there will always be those that still do not agree with the rest of the team and so may grow to loathe the other team members. This is human nature I'm afraid.

Title: Potential issues with code reviews


答:
This might be mostly just my opinion, but I'm basing this opinion on what my teams have tried in the past and what we've observed.

Our management has tried to institute/enforce team-based code reviews and I've always hated them. In fact I've hated 90% of what management tried to institute/enforce because it seems like most those things did nothing but waste time.

The problem with team based code reviews is that you get a whole bunch of people in a room. All these people should have looked at the code ahead of time (very expensive for all team members to stop their work and look at yours) but they never do (because everyone has their own work).  So meeting starts and presenter starts talking at people and pointing at code they've never seen.  This meeting will only last 1-2 hours, so in the end only maybe 10-20% of code will get "looked" at.  And because no one had the time to really think and understand what they are looking at, the only thing they can comment on is style or nit pick on tiny details which are mostly irrelevant.... the whole thing was a complete waste of time.

At the same time I love code reviews and I make sure that every single line of my code gets looked at.  What worked for us in my previous company when management stopped trying to push their "process" and worked is continuing to work for us in my current company is "asynchronous" code reviews:

I work on a feature and write a bunch of code

When code is ready, I submit it for code review. I pick a reviewer but generally I just go to the team and ask who would like to do the honors (one person most of the time)

Reviewer gets a notification e-mail

I switch branches (if using git) or shelve the code changes (if using perforce) and go on to other work

When reviewer is done, I get an e-mail back with his feedback.

I switch branches (or shelves) and modify my code based on his feedback and push/commit it.

Each code change has different importance.  If it's trivial/easy/simple, we don't even talk about it face-to-face. Everything is done with tools/emails.  If it is more important, after reviewer had a chance in peace and quite on his own time to sit down and understand what I wrote, we hold a meeting and go over his feedback.  If it is even more important, we have multiple people in that meeting.  But the key is that we always have a single "primary reviewer".  This way no one goes into the meeting thinking that other people have looked at the code.  If you are the primary, then you know you HAVE to look at it.

Another good thing about this model is that most of the time interaction is one-on-one between reviewer and reviewee, so it doesn't feel like an interrogation where you stand in front of the group and everyone critiques you. Also we keep our reviews extremely informal. There's no hierarchy. Every developer can ask any other developer to send a review and in the end our goals are:

Get a second set of eyes on the code because there's always something silly that will get missed

Get someone else to be familiar with the code and with your style

Reviewer can learn from you if you did something they've never seen before

You can learn from the reviewer if they did something you've never seen before and they noticed you are solving the same problem the hard way

I found this method to work for us and waste minimal time as the whole team doesn't get put on hold and you do get valuable feedback/interaction because reviewer is actually engaged and has a chance to really sit down and take as much time as needed with no time pressure and on his own schedule.

Title: Potential issues with code reviews

Body:
for clarity, code review = a team meeting and reviewing/sharing code

What are the potentially negative aspects of the code review process in a development environment?
What comes to mind for me

Strong criticism can lead to negative interactions and feelings of
animosity between colleagues.

Laziness to read and understand new    code can lead to apathetic and
very general feedback.

Considerable    Time investment is    required to organize and
execute the review    process.

There must be more than this though, What negative things have you guys noticed or experienced?


问:
Is there a design pattern that describes the separation of a Form from a Model
I am working on a web application implemented in C#, that follows MVC conventions.

This application contains a page that allows me to create or update a Wingding. The view passes a complete Wingding Model back to the controller for me to create or update.

The problem is that the page also has a checkbox that allows me to create identical Wingdings for all users. The current code adds a variable to the Winding Model to capture that data, so it can be passed back from the view.

It seems obvious to me that the page should have a Wingding Page Form object that is passed back from the view to the controller, instead of adding extra variables to the Model that won't get saved to the DB.

I know that this counts as separation of concerns, but is there a more specific design pattern that describes the separation of a From from a Model?

答:
There're multiple solutions:

1.) IMHO the cleanest solution is to have that checkbox as a separate field and pass it to the controller, so it knows what to do.

2.) You can use a PresentationModel pattern to encapsulate everything the controller needs to know and pass that object.

Apart from that, I believe, the way that you are describing your use case, that you have a flaw in your model. If you create the same items for multiple users, then your discriminator is a reference to the user in your model, isn't it? So you need to pass the controller your blueprint of the winding and the list of users.


问:
Search for object in loop or query? Who has better performance?
I have a DB that stores some complex objects of my app. When my app starts I load the objects into list and store them on the RAM.
But sometimes I would like to search for an objects that fulfills conditions (filtering), even the conditions are complexes.

I was always wrote a for loop (sometimes a very complex one) for this thing, that runs on these objects. But I heard recently that DB and SQL queries have a lot optimization mechanisms (dependent the DB company), and its works faster then regular search.
If I understand it correctly, it's better to write a SQL query that search these objects and returns objects IDs. And then by them IDs, get the relevant objects.

Its look like the ultimate solution for searching objects.

But I'm a little bit doubtful about this idea, because all the time we learned that DB is slow, and it's better to load the objects to RAM and work on them...

So I have two questions:

1) Are the queries actually more faster then regular search (for complex searches)?

2) Maybe its true for many many objects (thousands), but is it true for few objects (tens)?

答:
In general, the database search will always be faster - especially if you're searching on indexed elements. That said, communicating with the database is loads slower.

Just how fast/slow depends on many variables particular to your situation. Measure, then optimize. In general, if you have few items or need to do many simple lookups, look to RAM. If latency is a concern, look to RAM or some non-traditional database. Otherwise, databases are specialized for querying and will often be absurdly faster than naive searches.


问:
What are some good examples of using pass by name?
When I write programs I using pass by value or pass by reference always seem to be logical methods. When learning about different programming languages I came across pass by name.

Pass by name is a parameter passing method that waits to evaluate the parameter value until it is used. See Stack Overflow pass by name question for more information on the method.

What I would like to know is: what are some good examples and/or reasons to use pass by name and should it be re-introduced into some more modern languages.

答:
Here's what I think is a super simple example of passing something by name:

```<code>// JavaScript
function apply(a, b, f) { return f(a,b); }

function add(a,b) { return a + b; }

var result = apply(2, 4, add); // result is now 6

// The same in C using function-pointers
int apply(int a, int b, int (*f)(int,int)) { return f(a,b); }

int add(int a, int b) { return a + b; }

int result = apply(2, 4, add); // result is once again 6
</code>```

Notice how I'm passing the name of the function add in as a parameter in the apply function, just like I would with any other variable. The f function isn't evaluated at the time of declaration, simply because it can't be evaluated; its body doesn't exist at declaration. But this opens up for so many possibilities in terms of reducing boilerplate code. Like say you have 2 functions/methods that both do the exact same thing, apart from just one very specific line; instead of having to write the exact same thing twice, you can write it once, and then pass the one line of code that stands out, by name.

Let me show you a more elaborate example from one of my projects:

```<code>// C# snippet from a web-communication utility
private static void PostHelper(string inputUri, Action<WebClient, Uri> clientFunction) {
    var client = new WebClient();
    client.Headers[HttpRequestHeader.ContentType] = "application/json";
    var uri = new Uri(inputUri);
    clientFunction(client, uri);
}

public static void Post(string inputUri, string jsonInput) {
    PostHelper(inputUri, (client, uri) => client.UploadString(uri, "POST", jsonInput));
}

public static void PostAsync(string inputUri, string jsonInput) {
    PostHelper(inputUri, (client, uri) => client.UploadStringAsync(uri, "POST", jsonInput));
}
</code>```

If I hadn't used C#'s ability to pass by name, in the form of higher order functions, I would've had to write the code in the PostHelper twice, with the one minor change that one says UploadString, and the other says UploadStringAsync, doing like I did saves me repeated code, and it even lets me expand it later if I want to add more variations of the method. Because clientFunction is evaluated lazily I can make my code much more scalable.

Body:
Here's what I think is a super simple example of passing something by name:

// JavaScript
function apply(a, b, f) { return f(a,b); }

function add(a,b) { return a + b; }

var result = apply(2, 4, add); // result is now 6

// The same in C using function-pointers
int apply(int a, int b, int (*f)(int,int)) { return f(a,b); }

int add(int a, int b) { return a + b; }

int result = apply(2, 4, add); // result is once again 6

Notice how I'm passing the name of the function add in as a parameter in the apply function, just like I would with any other variable. The f function isn't evaluated at the time of declaration, simply because it can't be evaluated; its body doesn't exist at declaration. But this opens up for so many possibilities in terms of reducing boilerplate code. Like say you have 2 functions/methods that both do the exact same thing, apart from just one very specific line; instead of having to write the exact same thing twice, you can write it once, and then pass the one line of code that stands out, by name.

Let me show you a more elaborate example from one of my projects:

// C# snippet from a web-communication utility
private static void PostHelper(string inputUri, Action<WebClient, Uri> clientFunction) {
    var client = new WebClient();
    client.Headers[HttpRequestHeader.ContentType] = "application/json";
    var uri = new Uri(inputUri);
    clientFunction(client, uri);
}

public static void Post(string inputUri, string jsonInput) {
    PostHelper(inputUri, (client, uri) => client.UploadString(uri, "POST", jsonInput));
}

public static void PostAsync(string inputUri, string jsonInput) {
    PostHelper(inputUri, (client, uri) => client.UploadStringAsync(uri, "POST", jsonInput));
}

If I hadn't used C#'s ability to pass by name, in the form of higher order functions, I would've had to write the code in the PostHelper twice, with the one minor change that one says UploadString, and the other says UploadStringAsync, doing like I did saves me repeated code, and it even lets me expand it later if I want to add more variations of the method. Because clientFunction is evaluated lazily I can make my code much more scalable.


问:
Web API Development and SVN
We are planning to develop a ASP.NET Web API project starting soon.  For source control we use svn.  We typically follow the pattern of the trunk being stable and doing all of our work in the branches.

Most of the time we are lucky that one developer is working on the project.  For this Web API project there are at least two, possibly three developers working on different parts.  By this I mean that one may be working on a set of controllers for working with document models while the other developer is working on a controller or controllers for user authentication and maintenance.

Seeing that these two should not have overlapping work what are advantages/disadvantages to both developers working on a single branch with daily "updates to latest version" to keep both working copies consistent versus each developer working on an individual branch and merging the two branches back into the trunk when they are complete?

It seems to me that a single branch would be better in that the daily updates will keep each developer up on what the other is doing and this can possibly help share code.  My main concern is with performing trial and error coding.  What happens when some code is committed that really probably should not be pulled down by the other developer?  Should that even be a concern?

Another thought I had was that with each developer having their own branch if either developer has code that the other can use that is stable enough we merge that back to the trunk.  Then the developers would update daily from the trunk instead.

Finally I had a thought that maybe we create one branch for this "feature set" and then each developer branch from that branch.  They would then push stable features back to the main branch and update daily from the main branch.  This would keep the trunk clean and stable until the feature set is released.

Those are my thoughts and sorry for the long question.  I really want to start this project right and any guidance would be greatly appreciated.

答:
Seeing that the two developers should not have overlapping work, I cannot imagine what advantage there could be to working from a common branch instead of working in separate, individual branches. If the work will not overlap, working in separate branches seems like a natural solution consistent with Subversion's design. Working from a common branch, meanwhile, seems like a recipe for daily merge conflicts, especially nasty tree conflicts. Not to put too fine a point on it, but having multiple developers work from a single branch seems to defeat the purpose of version control.

For status updates, using a tool that tracks changes in a newsfeed might be helpful. Many are available, both to set up internally and to use via a cloud-based service. These often work with or are a part of a continuous-integration system, which you might also investigate.

Title: Web API Development and SVN


答:
Just use one branch and don't complicate things that are simple. Configure CI server, run unit tests after each commit. Two programmers on one branch is not a problem at all. We have six programmers and there are no problems. What problems are you afraid of? I really don't understand.

You can also read about 'trunk development'. It says that you should not create your local branches and work on trunk instead. It works for many teams!

Title: Web API Development and SVN

Body:
We are planning to develop a ASP.NET Web API project starting soon.  For source control we use svn.  We typically follow the pattern of the trunk being stable and doing all of our work in the branches.

Most of the time we are lucky that one developer is working on the project.  For this Web API project there are at least two, possibly three developers working on different parts.  By this I mean that one may be working on a set of controllers for working with document models while the other developer is working on a controller or controllers for user authentication and maintenance.

Seeing that these two should not have overlapping work what are advantages/disadvantages to both developers working on a single branch with daily "updates to latest version" to keep both working copies consistent versus each developer working on an individual branch and merging the two branches back into the trunk when they are complete?

It seems to me that a single branch would be better in that the daily updates will keep each developer up on what the other is doing and this can possibly help share code.  My main concern is with performing trial and error coding.  What happens when some code is committed that really probably should not be pulled down by the other developer?  Should that even be a concern?

Another thought I had was that with each developer having their own branch if either developer has code that the other can use that is stable enough we merge that back to the trunk.  Then the developers would update daily from the trunk instead.

Finally I had a thought that maybe we create one branch for this "feature set" and then each developer branch from that branch.  They would then push stable features back to the main branch and update daily from the main branch.  This would keep the trunk clean and stable until the feature set is released.

Those are my thoughts and sorry for the long question.  I really want to start this project right and any guidance would be greatly appreciated.


问:
I want to sell a simple calculator. What is the simplest way to implement registration keys?
I want to sell a simple calculator that will help a certain industry. This calculator would be installed on the computer (as opposed to a web service). How is a registration key mechanism implemented?</p>

答:
The simplest way to implement registration keys is to trust your users.  (Or, "don't use keys.")  As long as your sales contract is clear enough and written properly, you can use the courts to collect against the odd successful scofflaw.

Going upwards from that in complexity and security, you have:

Sell your calculator exclusively via an online store, a'la Windows, Android, or iPhone.

Generate a "registration key" based on a relatively short private key and some incremental number.  Require this key to be manually entered at install time, and present in the Windows Registry (or similar system-level repository) at run-time.

Have your installer "dial home" via HTTP to your registration server, sending a hash of information about the system it's installed upon as well as the installation sale number.  Return a private-key-signed registration code, as #2 above.

Have your application itself "dial home" on a regular basis for updates, and check the registration silently at the same time.  If you notice the same sale-code calling home too often, send the customer an updated bill.

Forgo authentication communication entirely, and instead use a dongle.  A small USB stick with an installation of your software that will check to see if that precise stick is present is a good start, but you may be able to find a vendor who can do more for you.

As above with the dongle, but instead make it the whole installer.  Have your "download" website register the particular computer, and generate an installer that will work for that computer and only that computer.

Note that, no matter what you do, a determined individual will be able to use your software in violation of your terms of sale, and you will NOT be able to catch them all.


问:
How do you stay focused at work?
Sometimes, the things I have to do for my job are interesting and engaging.  Sometimes, they aren't.  Occasionally, they really aren't.

Do you have any particular strategies or tricks for dealing with those dull stretches when your brain would rather be doing anything other than what you're supposed to be doing, particularly when the Internet and its boundless opportunities for interesting Slack beckon?

答:
If you really cannot avoid distraction, then learn something

Ask a colleague whether they need a hand - it'll repay itself later

Turn on some music

Work on a different part of the same project

Title: How do you stay focused at work?


答:
My main concern is with performing trial and error coding. What happens when some code is committed that really probably should not be pulled down by the other developer? Should that even be a concern?

Yes, it is definitely a concern. But you're going to have that problem no matter what methodology/technology you use. Developers shouldn't be committing "trial and error" coding - whatever that is :) If you don't want your code to be pulled down by other developers, don't commit it.

Like Peri said - use one branch and don't complicate things and it'll be fine. If the code isn't compiling/running don't commit it.

Title: Web API Development and SVN


问:
Best way to re-platform MS access application to java application
I have a requirement where MS Access application needs to be re-platformed to java application.The MS access app has about 45,000 records and 53 columns with SQL connectivity.These record data need to be edited,data used to send email with pdf report attachment.Report is designed using SQL reporting services.I need to create UI to call the reporting service and generate reports.The customer wants all the 45000 records to be loaded in the single stretch in the datatable.

Can anyone please suggest which is the best way to mimic this in java.Do i need to go with swing app or a web app.

答:
DON'T DO IT!

You're approaching the problem of re-writing a program with a relatively small amount of information from one client solution to a new client solution (MS Access to Java) while still using the same server platform (SQL Server 2008).  This is a bad idea.  Even if you find one-to-one matches for every class and feature you want, you're still throwing away a known code-base for a brand-new set of bugs.

If you're pulling data down from SQL Server Reporting Services to generate an MS Access Report that you save as a PDF and email to someone, you're already using a perfect acceptable tool in exactly the domain said tool was designed for.  While there are other tools that could produce the same solution, unless your problem domain is fundamentally changing you don't want to change one line of that MS Access app if you don't have to.

But it's an MS Access Application (.APP), and those aren't supported in 2013...

Yes, *.app files are gone, and if you have an application written using them, and you don't want to jump on the SharePoint bandwagon, you may very well have a bonna fide need to touch otherwise perfectly working code.

But, in that case, the solution is not to throw away the entire access code base and start again.  Instead, since all of your data is already on SQL server, you can just create an MS Access Desktop database and link the tables and views you need as either "linked tables" or pass-through queries.  At worst, you may need to search through your code base and change references like "dbo.stuff" to either "dbo_stuff" or "stuff", depending on your naming convention.

No, it's a company policy, as we're a Java Shop...

Then you already have program standards.  Follow those, and not random strangers on the internet.

Actually, we're moving mostly to android tablets and iPads and stuff, and want to support them...

Great.  Then you want to make a new web-based "client" to your SQL server, that should work alongside of your Access application instead of having to do EVERYTHING on first release.

I'm a big fan of XSLT for the sort of reports that Access produces, although they're hardly user-friendly.  (XSLT is almost a programming language by itself.)  I know that Java can do the kind of user-friendly drag-and-drop kind of stuff that Access can do, but that's more of a specific platform question than a general programming inquiry.

Ok, you got me.  I'm really just a Java-fluent IT support in a small office who inherited this boondoggle and want to re-do it in anything but Access.

Neat.  Java's not a bad choice at all to move your office's home-grown application to, especially if you're small enough that Apple or Linux is a real possibility.  But, as with the stub answer above about making a web interface, don't try and replace EVERYTHING right away.  Pick a solution that offers some useful benefits, and start there.  If necessary, you can even call back to Access via COM or by sending windows command-line calls.

Hey, I'm not just some kid out of college!  Java as %SOME_FEATURE% we want to use, and we're going to use it!

Great.  Go for it.  Submit more questions with the particular hangups you have in replicating a use-case from Access with your chosen Java toolkit.  But "Java" is almost as broad as "programming", and doesn't really help anyone offer advice until you get a little more specific.

Was there a single answer in there somewhere?

Sure.

Don't do it if you don't have to.

Don't replicate everything your access app does if you can run them side-by-side for a short while.  If all the data is on SQL server, you can connect to different client platforms at once, without having to shut down one over the other.

Figure out what your future platform needs and existing enterprise choices are, and go there.  If you already have a web server, use that.  If you already use some swing apps, do those instead.


答:
The best way to do it is to write a new application in Java, from scratch.

The usual software development life cycle applies; the only difference in your case is that some of the business logic (and possibly the database schema) are already modeled in your Access application (which you should consider your prototype).

Title: Best way to re-platform MS access application to java application

Body:
I have a requirement where MS Access application needs to be re-platformed to java application.The MS access app has about 45,000 records and 53 columns with SQL connectivity.These record data need to be edited,data used to send email with pdf report attachment.Report is designed using SQL reporting services.I need to create UI to call the reporting service and generate reports.The customer wants all the 45000 records to be loaded in the single stretch in the datatable.

Can anyone please suggest which is the best way to mimic this in java.Do i need to go with swing app or a web app.


答:
If multiple developers work on the same branch, they have to merge changes directly to their uncommitted working copy. That means that if anything goes wrong with the merge, SVN can't help them retrieve all the work they done since the previous commit.

Merges from multiple branches can still go wrong - in fact, each merge has a higher chance to go wrong, since you don't have to merge on every single commit and the differences between the developers' working copies have more time to accumulate between merges - but at least all the work is already committed so rolling back and redoing the merge is possible.

Title: Web API Development and SVN


答:
Sounds like you're looking for a View Model.

The View Model is an object that encapsulates only the data that is required for the View to display.  Example:

```<code>public class UserInformationViewModel
{
    public string DisplayName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string StateID { get; set; }
    public string Zip { get; set; }

    public SelectList States { get; set; }
}
</code>```

In this example, States is a list of states or provinces, used to populate a drop down list.  The data is sourced from multiple tables, but contained in a single object.

In smart client scenarios, the View Model can also contain view logic, such as validation and display modification based on user-selected data.

Title: Is there a design pattern that describes the separation of a Form from a Model

Body:
I am working on a web application implemented in C#, that follows MVC conventions.

This application contains a page that allows me to create or update a Wingding. The view passes a complete Wingding Model back to the controller for me to create or update.

The problem is that the page also has a checkbox that allows me to create identical Wingdings for all users. The current code adds a variable to the Winding Model to capture that data, so it can be passed back from the view.

It seems obvious to me that the page should have a Wingding Page Form object that is passed back from the view to the controller, instead of adding extra variables to the Model that won't get saved to the DB.

I know that this counts as separation of concerns, but is there a more specific design pattern that describes the separation of a From from a Model?

Body:
Sounds like you're looking for a View Model.

The View Model is an object that encapsulates only the data that is required for the View to display.  Example:

public class UserInformationViewModel
{
    public string DisplayName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string StateID { get; set; }
    public string Zip { get; set; }

    public SelectList States { get; set; }
}

In this example, States is a list of states or provinces, used to populate a drop down list.  The data is sourced from multiple tables, but contained in a single object.

In smart client scenarios, the View Model can also contain view logic, such as validation and display modification based on user-selected data.


问:
What is a cross-platform way to expose an Array[][] over a webservice? Any JSON nuances to be aware of?
I need to expose an Array[][] to many different clients (iPhone, Android, PC, Unix, etc), and need to make it available over HTTP/s

This brings me to JSON, and makes me wonder how do all the other *endian machines work with JSON and will I need to worry about how the array will be reconstructed on other platforms.

Initially this will be an array of UTF8 strings, but I want to support other types, for example, Array[0][] will be a image, while Array[1][] will be a audio file. ...etc.

If JSON is the right way to send Array[][] data across HTTP, what "gotchas" should I be concerned about?

答:
JSON is a way to serialize a data object to a text file.  Aside from some XMP-related goodies, you don't get a lot of oomph over a classic mutipart MIME message for sending anything that isn't a collection of simple scalar values as JSON.

Of course, your UTF8 strings are "simple scalar values", and so fit in rather well with JSON. Yay!.

When you want to migrate to images and audio files, you may want to change to sending standard URL's, possibly as paths relative to the web service's URL.  So, if you were the https://api.sample.org/MakerOfThings/ service, your JSON might look like:

```<code>{
  [
    ["awesome stuff", "image/cat01.png", "audio/meow.ogg"],
    ["creepy stuff", "image/eww01.jpg", "image/eww02.jpg"]
  ]
}
</code>```

Body:
JSON is a way to serialize a data object to a text file.  Aside from some XMP-related goodies, you don't get a lot of oomph over a classic mutipart MIME message for sending anything that isn't a collection of simple scalar values as JSON.

Of course, your UTF8 strings are "simple scalar values", and so fit in rather well with JSON. Yay!.

When you want to migrate to images and audio files, you may want to change to sending standard URL's, possibly as paths relative to the web service's URL.  So, if you were the https://api.sample.org/MakerOfThings/ service, your JSON might look like:

{
  [
    ["awesome stuff", "image/cat01.png", "audio/meow.ogg"],
    ["creepy stuff", "image/eww01.jpg", "image/eww02.jpg"]
  ]
}


问:
How do I cache data that rarely changes?
In my ASP.NET application there is some data that doesn't change often and so there is no point in querying the database to re-check it every time.

In my current situation I am checking user credentials on every request to see if they have access for what they are attempting to do (i.e. view a particular page).

The security information is stored in the database and I'm noticing a performance hit on every page load. The load time goes from 20ms to 200ms because of the database queries.

It seems to me that I should cache the security-related information so that pages are rendered faster (the data can be refreshed when the application restarts), but I don't know how to go about this. I've searched around for caching methods but no solutions I've seen are about what I'm trying to do.

One way is to store the security information as read-only in a static class or persistent repository that is created and loaded on application startup.

Another way is to use the Tracing and Caching Provider Wrappers for Entity Framework, but according to an answer on StackOVerflow called How to make Entity Framework cache some objects user Alex James says

sometimes this approach is overkill

Is there any disadvantage to storing the data in a few read-only variables (memory concerns?) and any clear advantage to using the caching provider?

答:
You want to store a reference in the ASP.NET session state.

http://msdn.microsoft.com/en-us/library/ms178581.ASPX

ASP.NET session state enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application.

Do the database registration first, and then include sufficient pointers to the security validation in the session state.  A date for "last security check" may be sufficient, depending on what you're doing.


问:
How to tell whether your programmers are under-performing?
I am a team lead with 5+ developers. I have a developer (let's call him A) who is a good programmer, who writes good clean, easy to understand code. However he is somewhat difficult to manage, and sometimes I wonder whether he is really under-performing or not.

Our company requires the developers to indicate the work progress in the bug tracker we use, not so much as to monitor the programmers but to keep the stakeholders apprised of the progress. The thing is, A only updates a task progress when it is done ( maybe 3 weeks after it is first worked on) and this leaves everyone wondering what is going on in the middle of the development week. He wouldn't change his habit despite repeated probing. ( It's OK, developers hate paperwork, I do, too)

Recent 2-3 months he on leave quite often due to various events-- either he is sick, or have to attend a lot of personal events etc. ( It's OK, bad things happen in a string. It's just a coincidence)

We define sprints, or roadmaps for each month. And in the beginning of the sprint, we will  discuss the amount of work each of the developers have to do in a sprint and the developers get to set the amount of time they need for each task. He usually won't be able to complete all of them. (It's OK, the developers are regularly missing deadlines not due to their fault).

I am based in Singapore. Not sure if that matters. Yeah, Asians are known to be reticent, but does that matter?

If only one or two of the above events happen, I won't feel that A is under-performing, but they all happen together. So I have the feeling that A is under-performing and maybe-- God forbid--- slacking off.

This is just a feeling based on my years of experience as programmer. But I could be wrong.

It is notoriously hard to measure the work of a programmer, given that not all two tasks are alike, and there lacks a standard objective to measure the commitment of a programmer to your company. It is downright impossible to tell whether the programmer is doing his job or slacking off. All you can do, is to trust them-- yeah, trusting and giving them autonomy is the best way for programmers to work, I know that, so don't start a lecture on why you need to trust your programmers, thank you every much-- but if they abuse your trust, can you know?

Outcome:

I've a straight talk with him regarding my perception on his performance. He was indignant when I suggested that I had the feeling that he wasn't performing at his best level. He felt that this was a completely unfair feeling. I then replied that this was my feeling and I didn't know whether my feeling was right or not. He would have none of this and ended the discussion immediately.

Before he left he said that he "would try to give more to the company" in a very cold tone. I was taken aback by his reaction. I am sure that I offended him in some ways. Not too sure whether that was the right thing to do for me to be so frank with him, though.

My question is: How can you tell whether your programmers are under-performing? Surely there are experience team leads who know better than me on this?

Extra notes:

I hate micromanaging. So all that we have for our software process is Sprint ( where tasks get prioritized and assigned, and at the end of the month, a review of the amount of work done). Developers would require to update the tasks as they go along everyday.

There is no standup meeting, or anything of the sort. Mainly because we have the freedom to work from home and everyone cherishes this freedom.

Although I am the one who sets the deadline, but the developers will provide the estimate for each tasks and I will decide-- based on the estimate-- the tasks that go into a particular sprint. If they can't finish the tasks at the end of the sprint, I will push them to the next. So theoretically one can just do only 1 or 2 tasks during the whole sprint and then push the remaining 99 tasks to the next sprint and still he will be fine as long as justifies this-- in the form of daily work progress updates

答:
Underperforming?

Intensity ebbs and flows during a person’s career.  If he’s worth more than he costs, then talk to him and try to make his job easier.  Or else start looking for a replacement.

Communication

Don’t rely on weekly meetings. Most people aren’t going to do a complete braindump.  Schedule more 1:1s.  Ask them how things are going, what you can do better, and what you feel they can do better.  Sometimes, there will be nothing to talk about, but that’s ok.  By having more 1:1’s, you increase the likelihood that they'll remember to mention something.

Have a more persistent means of communication

You can get more information out of people if you don’t make it feel like an extra chore.  If they’re all remote, have them use a chat program with logging capabilities like Hipchat or IRC.  Having a more persistent means of communication encourages people to talk more.  Lead by example and talk often, to encourage others to do the same.  At least once a day, have people say where they’re at with their projects.  Sometimes, just by looking at  chat, you can get a feel for how things are progressing.

Source control

Have everyone check in their code daily.  If you’re using git, have them push to their own branch on the company repo.  By looking at the commits, you can tell how they're doing.

Separate the means from the ends

The stakeholders want to be updated?  Deal with the stakeholders yourself.  Part of your job as manager is to be the shit umbrella, so your coders can focus on their work.  Look through the chat logs and commits, then write a summary about how things are going.


答:
Session or Application objects are a good fit for your requirements. These objects can be loaded in your global.asax

Put them in application onstart event handler:

```<code>Sub Application_OnStart
  application("vartime")=""
  application("users")=1
End Sub
</code>```

Restarting your application in IIS will reload your session or application wide vars.

Title: How do I cache data that rarely changes?

Body:
In my ASP.NET application there is some data that doesn't change often and so there is no point in querying the database to re-check it every time.

In my current situation I am checking user credentials on every request to see if they have access for what they are attempting to do (i.e. view a particular page).

The security information is stored in the database and I'm noticing a performance hit on every page load. The load time goes from 20ms to 200ms because of the database queries.

It seems to me that I should cache the security-related information so that pages are rendered faster (the data can be refreshed when the application restarts), but I don't know how to go about this. I've searched around for caching methods but no solutions I've seen are about what I'm trying to do.

One way is to store the security information as read-only in a static class or persistent repository that is created and loaded on application startup.

Another way is to use the Tracing and Caching Provider Wrappers for Entity Framework, but according to an answer on StackOVerflow called How to make Entity Framework cache some objects user Alex James says

sometimes this approach is overkill

Is there any disadvantage to storing the data in a few read-only variables (memory concerns?) and any clear advantage to using the caching provider?

Body:
Session or Application objects are a good fit for your requirements. These objects can be loaded in your global.asax

Put them in application onstart event handler:

Sub Application_OnStart
  application("vartime")=""
  application("users")=1
End Sub

Restarting your application in IIS will reload your session or application wide vars.


问:
Linux kernel development
I am trying to understand the linux kernel and there is one thing that is puzzling me for quite a while. As linux is used across variety of platforms (like  smartphones,desktop,supercomputers etc) and also on various architectures,
so does the same kernel code is used by all or a different one and also since it includes some assembly codes so it must be architecture specific.

so do the developers in linux community apply patches to a single kernel or there are multiple versions of kernel each for different architecture and platforms?

答:
Actually, the assembly parts and the other architecture specific parts are pretty small.

Very little code is actually assembly, mostly parts dealing with the very early booting process.

A little bit more code is platform-specific code, but it's still relatively little compared to the huge majority of code that's pretty platform-independent.

General framework, schedulers, most drivers and many other parts are platform-independent C code that just use the thin platform-dependent layer to actually access the hardware.

So there is a single Linux git repository that holds the code for (almost) architectures that Linux runs on.

Title: Linux kernel development


答: Caching depends on the type of information, their volatility and their scope. There are data that never or rarely change, data that change frequently, and data that are not meant for caching because they are changing all the time.  To cache all these types of information there are two possible ways: to cache in the user session (only to single user), and to cache in application state (global to all users). Caching with these methods can be performed "on-first use" which gets data on first request and caches it for subsequent use, or "pro-actively" with a singleton on different thread that gets data in parallel and caches it for any caller which is definitely give a great boost for application performance.


问:
What do programmers "micro-optimize" for today?
Back in the "good ol' days," when we would copy shareware onto floppies for friends, we also used a fair bit of assembly. There was a common practice of "micro-optimization," where you would stare and stare at lines of assembly until you figured out a way to express it in one fewer instruction. There was even a saying, which was mathematically impossible, that "You can always remove one more instruction." Given that changing runtime performance by small constant factors isn't a major issue for (most) programming today, are programmers transferring these micro-optimization efforts elsewhere?

In other words, Can a best-practice be taken to an extreme state where it's no longer adding anything of value? And instead is wasting time?

For example: Do programmers waste time generalizing private methods that are only called from one place? Is time wasted reducing test case data? Are programmers (still) overly concerned about reducing lines of code?

There are two great examples of what I'm looking for below: (1) Spending time finding the right variable names, even renaming everything; and (2) Removing even minor and tenuous code duplication.

Note that this is different from the question "What do you optimize for?", because I'm asking what other programmers seem to maximize, with the stigma of these being "micro" optimizations, and thus not a productive use of time.

答:
I used to write a lot of assembler back in the day. It is not just that compilers have gotten better, it is that most hardware now has lots of logic devoted to out-of-order execution of code. The real micro-issue is scheduling, most computer instructions take several machine clocks to produce a result -and a memory load that misses cache may take several hundred! So the idea was to schedule other instructions to do something useful, instead of waiting for a result. And modern machines can issue several instructions per clock period. Once we started getting out-of-order execution HW, I found that trying to get great performance with hand coding became a mugs game. First the out-of-order HW would not execute the instructions in your carefully crafted order, the fancy new HW architecture has reduced the penalty of inoptimal software scheduling enough that the compiler was usually within a few percent of your performance. Also I found out that compilers were now implementing wellknown but complexity generating tricks, such as unrolling, bottom loading, software pipelining etc. The bottom line, you have to work really really hard, skip some of these tricks and the compiler beats you. Use them all and the number of assembler instructions you need increase several fold!

Probably even more important, most performance issues, are not about instruction issue rates, but getting the data into the CPU. As I mentioned above, memory latency is now hundreds of cycles, and the CPU can execute several instructions per clock period, so
unless the program -and especially the data structures are designed so that the cache hit rate is exceedingly high, microtuning at the instruction level will have no payoff. Just like
military types say amateurs talk tactics, pros talk logistics. Performance programming is now more than 90% logistics (moving data). And this is hard to quantify, as modern memory management typically has multiple levels of cache, and virtual memory pages are handled by a hardware unit called the TLB. Also lowlevel alignment of addresses becomes important, as actual data
transfers, are not in units of bytes, or even 64bit long-longs, but they come in units
of cache lines. Then most modern machines have hardware that tries to predict which cache line misses you might need in the near future and issue automatic prefetches to get them into the cache. So the reality
is that with modern CPUs performance models are so complex as to be almost un-understandable. Even detailed hardware simulators can never match the exact logic of the chips, so exact
tuning is simply impossible anymore.

There is still a place for some hand coding. Math libraries (like say the exp function), as are the more important linear algebra operations (like matrix multiply) are still usually hand coded
by experts that work for the hardware vendor (i.e. Intel or AMD, or IBM), but they probably
only need a couple of top notch assembler programmers per mega-computer corp.


问:
What architecture to use for AJAX calls?
I am working on a website with PHP as backend.
There are things from the front-end which I'd like to accomplish using AJAX calls.

Which of these methods should I use to design them and why?

Call to different PHP files for different uses

Call to the same PHP file, with instructions on what to do

A RESTful API

Any other better way?

答:
Have a look at building a REST API. you can have clean urls that represent resources and these can be mapped to php servers in variouse different ways.

```<code>POST  /like
    {
      userId: 'foo',
      itemId: 'xxxxxxxxxxxxx'
    }

POST  /comment
    {
      commentText: 'bar',
      itemId: 'xxxxxxxxxxxxx'
    }
</code>```

The Slim framework provides a quick and easy way to set up a REST api in php

Body:
Have a look at building a REST API. you can have clean urls that represent resources and these can be mapped to php servers in variouse different ways.

POST  /like
    {
      userId: 'foo',
      itemId: 'xxxxxxxxxxxxx'
    }

POST  /comment
    {
      commentText: 'bar',
      itemId: 'xxxxxxxxxxxxx'
    }

The Slim framework provides a quick and easy way to set up a REST api in php


问:
Evolution versions of applications
Don't understand some things about evolution versions of some applications. Please tell me why, for example, firefox 26.0b1 released earlier than 25.0? What it means to "x" version? (5.x)? release candidate (rc)? Alpha? Beta?</p>

答:
The b in 26.0b1 stands for beta and according to their release process and release calendar we can see why the beta for the next version is released earlier than the release version. central, aurora, beta and release are stages in their deployment pipeline.

Since version 4.0 (i think), they have adopted the release early, release often philosophy, hence the rapid increase of major version number over a shorter period of time (compared to the 0.1 - 4.0 release window). The Chrome team uses the same philosophy.

The x could stand as a placeholder for all the minor versions in the major version 5, but this really depends on who is developing the application, since the versioning strategy is often different from company to company.

Title: Evolution versions of applications


问:
Returning view code in an API response
I have an API that returns a JSON formatted array of users within a given pair of lat/ long bounds.

I'm using this data to plot a number of markers on a map, based on the location of each user.
I also want to render a HTML list on each client request so that I can show the list of plotted users alongside the map.

What is the best way to get the list HTML to the client?

To me it seems like an incorrect solution to return the HTML for the user list within the initial API call (response.html, or something), although this feels like I'm shoe-horning functionality into an otherwise clean API response.

I also don't want to make two API calls (one for the initial data and one for the HTML), for obvious reasons (overhead).

Finally, I don't want to generate the HTML client-side (in JavaScript), as I already have a class to do this for me server-side.

What options does that leave me with?

Thanks

答:
REST is a vary adaptive architecture (as I am sure you realize).

The answer to your question I think has more to do with you as a programmer than anything else. For example, there is nothing wrong with the following API call

```<code>GET http://yourapi.com/users.json
GET http://yourapi.com/users.html
</code>```

These are two different representations of the same resource. Perfectly acceptable in a REST API.

I do however see your point about keeping the API 'clean'. I have a REST API which only outputs json, but I then need to have a client which converts the json to HTML. This could either be another web server or could be done through javascript.

On re-reading your question I can see that you want both a json response and a HTML response with the same API call. The only way you are really going to achieve this is as mentioned in the comments above: use an ajax request to GET the json, and then manipulate the page as required with javascript (i.e. use javascript to update the marker data from json, and the users list)

Title: Returning view code in an API response

Body:
REST is a vary adaptive architecture (as I am sure you realize).

The answer to your question I think has more to do with you as a programmer than anything else. For example, there is nothing wrong with the following API call

GET http://yourapi.com/users.json
GET http://yourapi.com/users.html

These are two different representations of the same resource. Perfectly acceptable in a REST API.

I do however see your point about keeping the API 'clean'. I have a REST API which only outputs json, but I then need to have a client which converts the json to HTML. This could either be another web server or could be done through javascript.

On re-reading your question I can see that you want both a json response and a HTML response with the same API call. The only way you are really going to achieve this is as mentioned in the comments above: use an ajax request to GET the json, and then manipulate the page as required with javascript (i.e. use javascript to update the marker data from json, and the users list)


答:
Return the data for the list and use client side templating to convert it into HTML.

```<code>GET http://yourwebserver.com/users.json

[{ name: 'foo'}]
</code>```

using a Mustache.js template like this

```<code>Mustache.render('<ul>{{#.}}<li>{{name}}</li>{{/.}}</ul>', data)
</code>```

With this aproach you have a simple interface, reduce data transfer, and make the template static therefore cachable.

Title: Returning view code in an API response

Body:
I have an API that returns a JSON formatted array of users within a given pair of lat/ long bounds.

I'm using this data to plot a number of markers on a map, based on the location of each user.
I also want to render a HTML list on each client request so that I can show the list of plotted users alongside the map.

What is the best way to get the list HTML to the client?

To me it seems like an incorrect solution to return the HTML for the user list within the initial API call (response.html, or something), although this feels like I'm shoe-horning functionality into an otherwise clean API response.

I also don't want to make two API calls (one for the initial data and one for the HTML), for obvious reasons (overhead).

Finally, I don't want to generate the HTML client-side (in JavaScript), as I already have a class to do this for me server-side.

What options does that leave me with?

Thanks

Body:
Return the data for the list and use client side templating to convert it into HTML.

GET http://yourwebserver.com/users.json

[{ name: 'foo'}]

using a Mustache.js template like this

Mustache.render('<ul>{{#.}}<li>{{name}}</li>{{/.}}</ul>', data)

With this aproach you have a simple interface, reduce data transfer, and make the template static therefore cachable.