答:
This sounds like a potentially good fit for for a CQRS "architecture" (http://martinfowler.com/bliki/CQRS.html) with Event Sourcing. What your system cares about is not so much the domain model state but the changes to it - instead of maintaining tables holding the current state of each entity, changes can be modelled and persisted as events triggered by commands from the UI.

The actual state of the system is discovered by playing back all the events, so you can reject edits and easily revert by skipping them. Because of this, though, queries may become slow. However, as you already have event sourcing, you can maintain query data as pre calculated, de-normalised sets. These can be stored in dedicated tables, in cache memory, or as flat files.

Title: Class structure to implement a Stack Exchange-like review system

Body:
I was reviewing some threads on Stack Overflow and started asking myself how I would design my classes and relationships to create such a system.

My Goal -

I want to build a review system like the Stack Exchange review system.

Let's take a look at how the review system works on Stack Exchange. I will only refer to the Suggested Edits functionality to keep it simple.

Un-experienced user (less than 2000 rep) edits someone post

Add an entry to the "review" system tagged 'suggested-edit'

Experienced user (more than 2000 rep) can review "suggested edits" one by one

As an experienced user I can:

See the diff between the original content and the edited content

Approve the edit

Reject the edit

Improve the edit

Skip to the next review

Final note about other review types. We could imagine "tagging" the reviews with the corresponding types since the actions are the same.

Design

I would start with a Review model. We could have one sub-class for each review type, allowing custom attributes and methods for each type in the future.

ruby

```<code>class Review
class Review::SuggestedEdit < Review
class Review::FirstPost     < Review
class Review::LateAnswer    < Review
class Review::LowQuality    < Review
</code>```

A Review object would have 2 references:

Original Content

Edited Content

Approve

Replace original content by edited content.

Mark the review as approved.

Move to the next review.

Reject

Log the reason for rejection.

Mark the review as rejected.

Move to the next review.

Improve

Directly edit edited content.

Approve.

(We could imaging creating a new Review for this improvement.)

Move to the next review.

Skip

Move to the next review.

How should I structure my classes in order to build such a review system?


问:
What is the real responsibility of a class?
I keep wondering if it is legitimate to use verbs that are based on nouns in OOP.

I came across this brilliant article, though I still disagree with the point it makes.

To explain the problem a bit more, the article states that there shouldn't be, for instance, a FileWriter class, but since writing is an action it should be a method of the class File. You'll get to realize that it's often language dependent since a Ruby programmer would likely be against the use of a FileWriter class (Ruby uses method File.open to access a file), whereas a Java programmer wouldn't.

My personal (and yes, very humble) point of view is that doing so would break the Single Responsibility principle. When I programmed in PHP (because PHP is obviously the best language for OOP, right?), I would often use this kind of framework:

```<code><?php

// This is just an example that I just made on the fly, may contain errors

class User extends Record {

    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

}

class UserDataHandler extends DataHandler /* knows the pdo object */ {

    public function find($id) {
         $query = $this->db->prepare('SELECT ' . $this->getFields . ' FROM users WHERE id = :id');
         $query->bindParam(':id', $id, PDO::PARAM_INT);
         $query->setFetchMode( PDO::FETCH_CLASS, 'user');
         $query->execute();
         return $query->fetch( PDO::FETCH_CLASS );
    }

}

?>
</code>```

It is my understanding that the suffix DataHandler doesn't add anything relevant; but the point is that the single responsibility principle dictates us that an object used as a model containing data (may it be called a Record) shouldn't also have the responsibility of doing SQL queries and DataBase access. This somehow invalidates the ActionRecord pattern used for instance by Ruby on Rails.

I came across this C# code (yay, fourth object language used in this post) just the other day:

```<code>byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);
</code>```

And I gotta say that it doesn't make much sense to me that an Encoding or Charset class actually encodes strings. It should merely be a representation of what an encoding really is.

Thus, I would tend to think that:

It is not a File class responsibility to open, read or save files.

It is not a Xml class responsibility to serialize itself.

It is not a User class responsibility to query a database.

etc.

However, if we extrapolate these ideas, why would Object have a toString class? It's not a Car's or a Dog's responsibility to convert itself to a string, now is it?

I understand that from a pragmatic point of view, getting rid of the toString method for the beauty of following a strict SOLID form, that makes code more maintainable by making it useless, is not an acceptable option.

I also understand that there may not be an exact answer (which would more be an essay than a serious answer) to this, or that it may be opinion-based. Nevertheless I would still like to know if my approach actually follows what the single-responsibility principle really is.

What's a class's responsibility?

答:
Class can have multiple responsibilities. At least in classic data-centric OOP.

If you are applying Single responsibility principle to its full extent, you get responsibility-centric design where basically every non-helper method belongs to its own class.

I think there is nothing wrong with extracting a piece of complexity from a base class as in case of File and FileWriter. The advantage is that you get clear separation of code that is responsible for a certain operation and also that you can override (subclass) just that piece of code instead of overriding the whole base class (e.g. File). Nevertheless, applying that systematically seems to be an overkill to me. You simply get much more classes to handle and for every operation you need to invoke its respective class. It is flexibility that comes at some cost.

These extracted classes should have very descriptive names based on the operation they contain, e.g. <X>Writer, <X>Reader, <X>Builder. Names like <X>Manager, <X>Handler does not describe the operation at all and if they are called like that because they contain more than one operation, then it is not clear what you have even achieved. You have separated the functionality from its data, you still break single responsibility principle even in that extracted class, and if you are looking for a certain method you might not know where to look for it (if in <X> or <X>Manager).

Now, your case with UserDataHandler is different because there is no base class (the class that contains actual data). The data for this class are stored in an external resource (database) and you are using an api to access them and manipulate them. Your User class represents a run-time user, which is really something different than a persistent user and the separation of responsibilities (concerns) might come handy here especially if you have got lots of run-time-user related logic.

You probably named UserDataHandler like that because there is basically just functionality in that class and no real data. However, you might also abstract from that fact and consider the data in database to belong to the class. With this abstraction you can name the class based on what it is and not on what it does. You can give it a name like UserRepository, which is pretty slick and also suggests usage of repository pattern.

ContentLicense: CC BY-SA 3.0


问:
How to best protect from 0 passed to std::string parameters?
I have just realized something disturbing.  Every time I have written a method that accepts a std::string as a paramater, I have opened up myself to undefined behaviour.

For example, this...

```<code>void myMethod(const std::string& s) {
    /* Do something with s. */
}
</code>```

...can be called like this...

```<code>char* s = 0;
myMethod(s);
</code>```

...and there's nothing I can do to prevent it (that I am aware of).

So my question is: How does someone defend themself from this?

The only approach that comes to mind is to always write two versions of any method that accepts an std::string as a parameter, like this:

```<code>void myMethod(const std::string& s) {
    /* Do something. */
}

void myMethod(char* s) {
    if (s == 0) {
        throw std::exception("Null passed.");
    } else {
        myMethod(string(s));
    }
}
</code>```

Is this a common and/or acceptable solution?

EDIT:  Some have pointed out that I should accept const std::string& s instead of std::string s as a parameter.  I agree.  I modified the post.  I don't think that changes the answer though.

答:
Your method in the first code block will never be called if you try to call it with a (char *)0. C++ will simply try to create a string and it will throw the exception for you. Did you try it?

```<code>#include <cstdlib>
#include <iostream>

void myMethod(std::string s) {
    std::cout << "s=" << s << "\n";
}

int main(int argc,char **argv) {
    char *s = 0;
    myMethod(s);
    return(0);
}

$ g++ -g -o x x.cpp
$ lldb x
(lldb) run
Process 2137 launched: '/Users/simsong/x' (x86_64)
Process 2137 stopped
* thread #1: tid = 0x49b8, 0x00007fff99bf9812 libsystem_c.dylib`strlen + 18, queue = 'com.apple.main-thread, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
    frame #0: 0x00007fff99bf9812 libsystem_c.dylib`strlen + 18
libsystem_c.dylib`strlen + 18:
-> 0x7fff99bf9812:  pcmpeqb (%rdi), %xmm0
   0x7fff99bf9816:  pmovmskb %xmm0, %esi
   0x7fff99bf981a:  andq   $15, %rcx
   0x7fff99bf981e:  orq    $-1, %rax
(lldb) bt
* thread #1: tid = 0x49b8, 0x00007fff99bf9812 libsystem_c.dylib`strlen + 18, queue = 'com.apple.main-thread, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
    frame #0: 0x00007fff99bf9812 libsystem_c.dylib`strlen + 18
    frame #1: 0x000000010000077a x`main [inlined] std::__1::char_traits<char>::length(__s=0x0000000000000000) + 122 at string:644
    frame #2: 0x000000010000075d x`main [inlined] std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(this=0x00007fff5fbff548, __s=0x0000000000000000) + 8 at string:1856
    frame #3: 0x0000000100000755 x`main [inlined] std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(this=0x00007fff5fbff548, __s=0x0000000000000000) at string:1857
    frame #4: 0x0000000100000755 x`main(argc=1, argv=0x00007fff5fbff5e0) + 85 at x.cpp:10
    frame #5: 0x00007fff92ea25fd libdyld.dylib`start + 1
(lldb)
</code>```

See? You have nothing to worry about.

Now if you want to catch this a bit more gracefully, you should simply not be using char *, then the problem won't arise.

Body:
Your method in the first code block will never be called if you try to call it with a (char *)0. C++ will simply try to create a string and it will throw the exception for you. Did you try it?

#include <cstdlib>
#include <iostream>

void myMethod(std::string s) {
    std::cout << "s=" << s << "\n";
}

int main(int argc,char **argv) {
    char *s = 0;
    myMethod(s);
    return(0);
}

$ g++ -g -o x x.cpp
$ lldb x
(lldb) run
Process 2137 launched: '/Users/simsong/x' (x86_64)
Process 2137 stopped
* thread #1: tid = 0x49b8, 0x00007fff99bf9812 libsystem_c.dylib`strlen + 18, queue = 'com.apple.main-thread, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
    frame #0: 0x00007fff99bf9812 libsystem_c.dylib`strlen + 18
libsystem_c.dylib`strlen + 18:
-> 0x7fff99bf9812:  pcmpeqb (%rdi), %xmm0
   0x7fff99bf9816:  pmovmskb %xmm0, %esi
   0x7fff99bf981a:  andq   $15, %rcx
   0x7fff99bf981e:  orq    $-1, %rax
(lldb) bt
* thread #1: tid = 0x49b8, 0x00007fff99bf9812 libsystem_c.dylib`strlen + 18, queue = 'com.apple.main-thread, stop reason = EXC_BAD_ACCESS (code=1, address=0x0)
    frame #0: 0x00007fff99bf9812 libsystem_c.dylib`strlen + 18
    frame #1: 0x000000010000077a x`main [inlined] std::__1::char_traits<char>::length(__s=0x0000000000000000) + 122 at string:644
    frame #2: 0x000000010000075d x`main [inlined] std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(this=0x00007fff5fbff548, __s=0x0000000000000000) + 8 at string:1856
    frame #3: 0x0000000100000755 x`main [inlined] std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::basic_string(this=0x00007fff5fbff548, __s=0x0000000000000000) at string:1857
    frame #4: 0x0000000100000755 x`main(argc=1, argv=0x00007fff5fbff5e0) + 85 at x.cpp:10
    frame #5: 0x00007fff92ea25fd libdyld.dylib`start + 1
(lldb)

See? You have nothing to worry about.

Now if you want to catch this a bit more gracefully, you should simply not be using char *, then the problem won't arise.


问:
What's the difference between "use case", "User Story" and "Usage Scenario"?
Is there an exact, but simple and understandable defintion of the distinction between "use case",  "User Story" and "Usage Scenario"?

there are quite a bunch of explanation, but right now, I see no one that explains the differences in a single sentence, or two...

(e.g. http://c2.com/cgi-bin/wiki?UserStoryAndUseCaseComparison very long and hard to get, full of discussion)

答:
A User Story when decomposed to tasks that are individually assignable to developers may or may not be more granular and constrained in scope than a Use Case Scenario. A User Story is about the need of the User -- a Goal or Outcome from their using the System.

Examples of User Stories are:

I am a Customer and I want to pay my account balance online --a pretty high-level view

I am a Customer and I want to update the expiration year on my stored credit information -- a pretty granular view.

At the highest level of abstraction a Use Case sounds very similar -- Customer Updates Card Expiration Year -- but here its a statement of function rather than goal.

As the granularity of the Use Case scenarios are defined they become more about function and procedure.

The Post-condition of a Use Case Main Scenario should be the same outcome as that stated in the User Story -- Customer's Credit Card Expiration Year is Updated.

Use Case Scenarios describe step-by-step either in text or process flow chart (not necessarily UML or BPM - I use a standard cross-functional flow diagram for clarity and ease of use by untrained consumers of the use case.

The bottomline is that User Stories describe Needs and Outcomes (What the System Needs to Deliver) whereas Use Cases describe interactions between Actors required to meet the goal - AND what can go wrong (Extension, Alternate or Error Scenarios) (how the user interacting with the System achieves that outcome)

For a discussionin depth on this topic I suggest reading http://c2.com/cgi/wiki?UserStoryAndUseCaseComparison on Alistair Cockburn's website. Since he's a signatory of the Agile Manifesto, the person who coined User Stories and has been considered a Use Case expert for the last couple of decades I think he's an excellent source for more info.

OwnerDisplayName: Henning

ContentLicense: CC BY-SA 2.5


问:
Strategy for keeping secret info such as API keys out of source control?
I'm working on a website that will allow users to log in using OAuth credentials from the likes of Twitter, Google, etc.  To do this, I have to register with these various providers and get a super-secret API key that I have to protect with pledges against various body parts.  If my key gets ganked, the part gets yanked.

The API key has to travel with my source, as it is used at runtime to perform authentication requests.  In my case, the key must exist within the application in a configuration file or within the code itself.  That isn't a problem when I build and publish from a single machine.  However, when we throw source control into the mix, things get more complicated.

As I'm a cheap bastard, I'd much prefer to use free source control services such as TFS in the cloud or GitHub.  This leaves me with a slight conundrum:

How can I keep my body intact when my API keys are in my code, and my code is available in a public repository?

I can think of a number of ways to handle this, but none of them are that satisfying.

I could remove all private info from code, and edit it back in after deployment.  This would be a severe pain to implement (I won't detail the many ways), and isn't an option.

I could encrypt it.  But as I have to decrypt it, anyone with the source could figure out how to do so.  Pointless.

I could pay for private source control.  LOL j/k spend money?  Please.

I could use language features to segregate sensitive info from the rest of my source and therefore keep it from source control.  This is what I'm doing now, but it could easily be screwed up by mistakenly checking in the secret file.

I'm really looking for a guaranteed way to ensure I don't share my privates with the world (except on snapchat) that will work smoothly through development, debugging and deployment and be foolproof as well.  This is completely unrealistic.  So what realistically can I do?

Technical details:  VS2012, C# 4.5, source control is either going to be TF service or GitHub.  Currently using a partial class to split the sensitive keys off in a separate .cs file that won't be added to source control.  I think GitHub may have the advantage as .gitignore could be used to ensure that partial class file isn't checked in, but I've screwed that up before.  Am hoping for a "oh, common issue, this is how you do it" but I may have to settle for "that doesn't suck as much as it could have", :/

答:
I think this is an issue everyone has had some trouble with at some point.

Here's a workflow I have used, which might work for you. It uses .gitignore with a twist:

All configuration files go in a special folder (w/ sample config files - optional)

All configuration files are included in .gitignore, so that they don't go public

Setup a gitolite server (or your favorite git server) on a private box

Add a repo with all the config files in the private server

Add a script to copy config files to the special folder in the main repo (optional)

Now, you can clone the config repo to any development and deployment system. Just run the script to copy the files to the correct folder and you're done.

You still get all the GitHub candy, share your code with the world and the sensitive data are never in the main repo, so they don't go public. They are still only a pull and a copy away from any deployment system.

I use a 15$/year box for the private git server, but you can also setup one at home, per the cheapskate requirement ;-)

PS: You could also use a git submodule (http://git-scm.com/docs/git-submodule), but I always forget the commands, so quick & dirty rules!


问:
What can slow a developer down?
What things tend to slow a developer down?

Please try to refrain from posting answers that:

are slow now but useful in the feature. (TDD, Refactoring, ...)

list a distraction.

答:
Any attempt to follow a process that is not suited to the task at hand.

This can be all sorts of things, but common ones I see include:

testing methodologies that do not fit the code being tested

processes that are dramatically more agile or traditional than the deliverable(s) warrant

guidelines that are meant for a different toolset than the selected toolset

design principals that are out of scale with the project's needs

using a toolset that is not suited to the task

All of these things can be immensely worthwhile on some projects or in some situations, but some organizations try to do everything one way and that leads to poor fit on other projects which often is productivity death.

Title: What can slow a developer down?


问:
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

答:
Dynamic programming is definitionally about two things:

Optimal substructure

Larger solutions can be derived from smaller solutions; solving is not bidirectional.

Overlapping subproblems

The small solutions will be reused many times. If the subproblems don’t overlap at all, then you don’t benefit from DP/memoisation; what you have is divide and conquer instead.

The general approach to DP problems is:

Write a naïve recursive or iterative version that works.

Notice that the function is doing redundant work.

Find a way to avoid doing that redundant work, often by memoisation.


问:
MVP pattern and references
I am doing a Windows C# application.

I asked this question and I was told that the viewer/presenter should never know anything about the model. Does this mean that I should not add a reference of my model to the GUI I am making and instead of, lets say List<Car> I should transport the information using only strings and ints e.g. Dictionary<carID, carName>?

Because of the fact I am using EntityFramework, half of my domain model are basically in the DAL and rest are in the BLL and then I would need to add reference to both those layers. Is this the approach or am I doing it wrong?

答:
I think thorsten müller worded the answer in a way that might confuse people (although his answer is good).

He says

The view never directly acts on the model layer.

and

the view should really have no knowledge about models.

Both of these statements are true, but allow me to clarify.

When thorsten says that a "view never directly acts on the model", what he means is that a view should not be manipulating or interacting with the model in any significant way. All the view should be doing is reading the properties that it has been given and displaying them to the user.

"view should really have no knowledge about models" means that a view shouldn't know the inner workings of the model. It doesn't really know what they are or how they got their values. Instead, you pass a model to a view and the view says "I don't really know much about this thing, but I see it has properties so I'll just render them".

Things get a little more debatable though, especially because we can use the term model incorrectly. What thorsten might also mean is that views generally don't know about the domain model.

Suppose you have an application for displaying information about University classes. You have teachers, students and courses. In some MVC applications the view will not reference these models and will not understand what they are directly. That is, you cannot give the view these models. Instead you would create appropriate ViewModels. You might create a StudentViewModel or CoursesListViewModel. You'd populate the view-models easily with something like AutoMapper.

Furthermore, thorsten might also mean that views should be generic. Many times in MVC applications when I notice that views and models are very similar (for example an edit form) I don't use separate views. Instead I send my models to a single view (perhaps "_EditForm.cshtml" partial-view) and the view will automatically generate everything required based on the properties of the view-model. The code never needs changing - I simply feed the view a view-model and it decides what will need to be rendered. I achieve this with ModelMetaData, attributes and reflection.

This is more intermediate MVC programming and will be a bit overwhelming for beginners.

Does this mean that I should not add a reference of my model [...] I should transport the information using only strings and ints e.g. Dictionary?

No. This would get very ugly and difficult to maintain. Referencing models or view-models is standard practice.

Title: MVP pattern and references


问:
Cohen–Sutherland algorithm
I was reading Cohen–Sutherland algorithm on Wikipedia  and I am confused in these two parts,

```<code>int ComputeOutCode(double x, double y) {
    ...
    if (x < xmin)       code |= LEFT;
    else if (x > xmax)  code |= RIGHT;
    if (y < ymin)       code |= BOTTOM;
    else if (y > ymax)  code |= TOP;
    ...
}
</code>```

and

```<code>if (outcodeOut & TOP) {           // point is above the clip rectangle
    x = x0 + (x1 - x0) * (ymax - y0) / (y1 - y0);
    y = ymax;
} else if (outcodeOut & BOTTOM) { // point is below the clip rectangle
    x = x0 + (x1 - x0) * (ymin - y0) / (y1 - y0);
    y = ymin;
} else if (outcodeOut & RIGHT) {  // point is to the right of clip rectangle
    y = y0 + (y1 - y0) * (xmax - x0) / (x1 - x0);
    x = xmax;
} else if (outcodeOut & LEFT) {   // point is to the left of clip rectangle
    y = y0 + (y1 - y0) * (xmin - x0) / (x1 - x0);
    x = xmin;
}
</code>```

What I am confused is, How does it handle points who are top-left, top right, etc. It just handles top, left, right and bottom.

Why use | in code |= LEFT; and outcodeOut & TOP in if-else below it? I know that these two somehow handle all 8 possible cases but I don't know how.

答:
code is a bit field which uses bitwise boolean operators to store whether certain flags are set or not.

code |= LEFT; is short for code = code | LEFT; and sets the LEFT flag. outcodeOut & LEFT is an expression that is only true (!=0) when the LEFT flag is set.

The shown excerpt does indeed not handle all (16) possible cases at once, but it's part of a larger loop that may run multiple times. So it's done in several iterations.

Title: Cohen–Sutherland algorithm


问:
How far should we rename code and data when end users nomenclatures change?
A long time ago we added a feature where our users could "Accept" an image after it was added to a workflow queue. Turns out, we used the wrong term, and users actually "Approve" the image.

Changing Accept to Approve on our interface is easy, just replace one word. But we programmed all layers with the word "accept", from the CSS class name to the database values.

The CSS class that turns the button green: ".accepted";

The model method that verifies and binds the class attribute on the DOM node: "isAccepted";

JavaScript status attribute: Array with "unreviewed", "accepted" and "published";

Mysql status column: ENUM with "unreviewed", "accepted" and "published";

Test names;

It's trivial (specially when you have tests) to replace most occurrences of accept to approve. A little bit harder is to migrate the data, specially since it needs to be synchronized with deployment.

This specific case is simple, but I've faced similar, yet more complex cases, during my career. When a file is also renamed and deployment happens on dozens of servers, or when proxy caching, memcached and mysql are involved.

Leaving "accepted" on every other layer except the interface is a bad idea, since new programmers joining the team might not learn the historical reasons it led to this decision, and while accept -> approve are close words in terms of meaning, if it was renamed to "queued for managerial next status meeting", it certainly wouldn't make any sense. And it feels if we compromise here and there, in a few iterations the user interface concepts will have no bearings to the system internals, and I certainly do not want to work on a system where half of the output has no connection to its innards.

So, do you always rename everything when needed? If this happened to you, and you decided that the trade-off was not worth, did it come back to bite you? Is code comment or developer documentation enough to avoid this issue?

答:
I don't always rename code and data because some packages are shared between customers. They are basically using the same thing but call it differently. Examples, in a CMS, one client calls their customer "Customer" and another uses "Client". So we replaced Customer with Client on the surface for one client, but CMS will always be a Customer Management System.

Another example is User management with terms like permissions vs access control list, admin vs manager, etc. It can be confusing to new comers but for core components like those, there are usually core developers who make sure that those components work for all clients and also easy to implements by other developers (e.g. by creating configurable labels).

It might help to think that if you do make this change, hopefully you won't need to do it again if the same piece is used by other customer, basically turning it into a product.


问:
Handling large amounts of sockets
I am working on a project in which we have a desktop application that should be able to receive commands from a web application. To solve this issue, using sockets seems like a good approach (instead of long polling and various other techniques).

The desktop application also uses a web API, and this is secured with mutual authentication in SSL. The sockets should also be secured with SSL.

The question is: what is the best way to handle large amounts of sockets?

I have thought of a solution which involves using a "relay socket". Basically the desktop application creates a socket to [The Relay Station]. Whenever an action should be sent from the web application, the web app also creates a socket to the relay station.

The web app sends a command saying "relay [this] to [socket]".

This approach requires that:

All the desktop-to-relay sockets must be persistent

The desktop application must identify himself, so that the webapp can reference him in his commands

The relay station needs to keep track of all the desktop application sockets, and map those to a unique identifier.

This gives me a good structure, but it also arises some questions:

What should the identifier be?

Is there a better way of sending commands from [WebApp] to the correct desktop application, without using such approach?

答:
The question is whether you'd rather the linking application run on your web server (as a relay server) or the desktop (your app accepts lots of connections). That's a design decision, I think, rather than a programming one.

Somewhere you need an application that will accept large numbers of connections. One per instance of the web app, presumably. A million is fairly straightforward and doesn't have to be done in C (example uses erlang and duplicates the code using C).

How many commands are you looking at, total, and how many instances of the web app (tens? thousands? millions?) If it's millions, it doesn't really matter whether you funnel those down using a relay, you're going to spend a lot of time dealing with replication and multiple instances of your endpoints. A million instances sending one command a minute is 16k commands a second.

I think the identifier question is pretty obvious - use the native identifier that comes with the connection (the socket handle or class reference), then whatever mapping system your language provides to link that to the ID of the web app or command. If you must construct your own ID and don't care about the identity of the command source, just use the IP details directly, otherwise use the user or command ID that you have. It's much easier when debugging to see

```<code>user 123456 issued command Fubar(everything) from 192.168.0.255:54012
</code>```

than have an artificial ID in there (or have to look it up).

I suggest the ID be the source address and port, plus the input port (your IP will be fixed, unless you have multiple IPs in which case store that too). With IPv4 that's 32 bits per IP plus 16 per port, for a maximum of 96. With IPv6 it's 160 bits. Either way, that's not going to be your biggest memory suck. Once you put that into a list of some sort you're going to have a pointer or a native int, which becomes your "real ID". Ideally you'll be able to use a direct link into the network layer in your software for that, to save a layer of indirection.

Title: Handling large amounts of sockets

Body:
The question is whether you'd rather the linking application run on your web server (as a relay server) or the desktop (your app accepts lots of connections). That's a design decision, I think, rather than a programming one.

Somewhere you need an application that will accept large numbers of connections. One per instance of the web app, presumably. A million is fairly straightforward and doesn't have to be done in C (example uses erlang and duplicates the code using C).

How many commands are you looking at, total, and how many instances of the web app (tens? thousands? millions?) If it's millions, it doesn't really matter whether you funnel those down using a relay, you're going to spend a lot of time dealing with replication and multiple instances of your endpoints. A million instances sending one command a minute is 16k commands a second.

I think the identifier question is pretty obvious - use the native identifier that comes with the connection (the socket handle or class reference), then whatever mapping system your language provides to link that to the ID of the web app or command. If you must construct your own ID and don't care about the identity of the command source, just use the IP details directly, otherwise use the user or command ID that you have. It's much easier when debugging to see

user 123456 issued command Fubar(everything) from 192.168.0.255:54012

than have an artificial ID in there (or have to look it up).

I suggest the ID be the source address and port, plus the input port (your IP will be fixed, unless you have multiple IPs in which case store that too). With IPv4 that's 32 bits per IP plus 16 per port, for a maximum of 96. With IPv6 it's 160 bits. Either way, that's not going to be your biggest memory suck. Once you put that into a list of some sort you're going to have a pointer or a native int, which becomes your "real ID". Ideally you'll be able to use a direct link into the network layer in your software for that, to save a layer of indirection.


问:
What was the need of introducing Python 3 when we already had Python 2
I am still learning python and I started with Python 3. This question not Python 2 vs 3 or difference between them like print() is a function and not language construct and 3/2 = 1.5

My question is even if it is still python, what was the need of introduce something new which is not backward compatible, when -

Syntax is the same

Language philosophy is the same (import this)

Edit - Lets say all the popular packages are ported to Python 3, does that mean we no longer need Python 2

答:
Python 3 was introduced to make improvements upon python 2, but I think what you are asking is why they are not backwards compatible. Basically, developers deliberately made python 3 not backwards compatible, for two main reasons:

First of all, they wanted to change some things integral to python 2, and while the differences seemed small, the improvements that they had made would not have combined well with the existing structure. For example, the change to the "print" syntax you mentioned was made because print really is just calling a function, and really isn't a keyword in the same way that something like "if" or "while" is.

The other reason backwards compatibility was severed was to keep python 2 and 3 separate. Some people, including me, prefer python 2.7 over python 3. Because python 3 made larger changes to the language, developers wanted to maintain the two versions almost as separate (if quite similar) languages.

For all intents and purposes, if you use python 2.7, the only difference that should really affect you is the change in "print".


问:
Textarea validation
I'm interested to hear what characters people permit in the various common fields of input forms (barring e-mail...)

For example:

Textarea/Messages:  do you allow completely free text, or restrict to alphanumeric and punctuation? I've tried to go the second route, but you always find someone out there that likes using tilde's...

Full name: do you allow anything, or do you use a regex?

Telephone numbers: numbers only

Addresses: alphanumeric, whitespace, hyphens

City/Town names: alphabet, hyphens, whitespace

[NB: edited as requested]

答:
no restrictions, provided that:

the text is not published back to a web page in a way that would permit hijacking/hacking

the text is not included in a SQL statement in a way that would make it vulnerable to sql injection

you're reasonably sure that a person is responding and not a bot (captcha, for example)

Title: Textarea validation


问:
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?

答:
When deciding just how to build your data structures, ponder the issues involved in relational databases when data is normalized and denormalized

Don't re-invent the wheel because you are looking at the problem from too low a level of detail.


问:
Which useful alternative control structures do you know?
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

答:
The linked article definitely gets it right about Donald Knuth's N+1/2 Loops. Expressed in C/C++/Java:

```<code>for (;;) {
  get next element;
  if (at the end) break;
  process the element;
}
</code>```

This is useful for reading lines or characters from a file, testing if you've reached EOF, and then processing it. I'm so used to seeing the pattern for(;;)..if(..)break; appear that it's idiomatic to me. (Before I had read the Knuth article, reprinted in the book Literate Programming, this one used to be a "wtf?".)

Knuth suggested the keywords loop/while/repeat:

```<code>loop:
  S;
while C:
  T;
repeat
</code>```

Where S and T are place holders for a series of zero or more statements, and C is a boolean condition. If there was no S statement then it would be a while loop, and if there was no T statement then it would be a do loop.

This construct itself could be generalized by allowing zero or more while C clauses, making it perfect for expressing infinite loops and then some rarer conditions that would need two checks.

In the same article, Knuth suggested a signaling mechanism that would be a local version of throwing/catching exceptions (as an alternative to using goto).

For me? I wish Java supported tail-call optimization, so that I could express any general control structure as needed.

Update: I forgot to mention that many C/C++/Java programmers get around this one by using an embedded assignment in the condition of the while:

```<code>while ((c = getc(f)) != -1) {
   T;
}
</code>```

Using the terms from Knuth's construct, this is allowable when S and C can be combined into a single expression. Some people hate to see the embedded assignment above, while others hate to see the break in the for (;;) above. But when S and C cannot be combined, such as when S has multiple statements, the for (;;) is the only alternative without repeating code. The other alternative is to simply duplicate the S code:

```<code>S;
while (C) {
  T;
  S;
}
</code>```

Knuth's loop/while/repeat alternative seems much better.

Body:
The linked article definitely gets it right about Donald Knuth's N+1/2 Loops. Expressed in C/C++/Java:

for (;;) {
  get next element;
  if (at the end) break;
  process the element;
}

This is useful for reading lines or characters from a file, testing if you've reached EOF, and then processing it. I'm so used to seeing the pattern for(;;)..if(..)break; appear that it's idiomatic to me. (Before I had read the Knuth article, reprinted in the book Literate Programming, this one used to be a "wtf?".)

Knuth suggested the keywords loop/while/repeat:

loop:
  S;
while C:
  T;
repeat

Where S and T are place holders for a series of zero or more statements, and C is a boolean condition. If there was no S statement then it would be a while loop, and if there was no T statement then it would be a do loop.

This construct itself could be generalized by allowing zero or more while C clauses, making it perfect for expressing infinite loops and then some rarer conditions that would need two checks.

In the same article, Knuth suggested a signaling mechanism that would be a local version of throwing/catching exceptions (as an alternative to using goto).

For me? I wish Java supported tail-call optimization, so that I could express any general control structure as needed.

Update: I forgot to mention that many C/C++/Java programmers get around this one by using an embedded assignment in the condition of the while:

while ((c = getc(f)) != -1) {
   T;
}

Using the terms from Knuth's construct, this is allowable when S and C can be combined into a single expression. Some people hate to see the embedded assignment above, while others hate to see the break in the for (;;) above. But when S and C cannot be combined, such as when S has multiple statements, the for (;;) is the only alternative without repeating code. The other alternative is to simply duplicate the S code:

S;
while (C) {
  T;
  S;
}

Knuth's loop/while/repeat alternative seems much better.


答: I put secrets into encrypted file(s) which I then commit.  The pass phrase is provided when the system launches, or it is stored in small file that I don't commit.  It's nice that Emacs will cheerfully manage these encrypted files.  For example, emacs init file includes: (load "secrets.el.gpg"), which just works - prompting me for the password on those rare occations when I start the editor.  I don't worry about somebody breaking the encryption.</p>

Title: Strategy for keeping secret info such as API keys out of source control?

Body:
I'm working on a website that will allow users to log in using OAuth credentials from the likes of Twitter, Google, etc.  To do this, I have to register with these various providers and get a super-secret API key that I have to protect with pledges against various body parts.  If my key gets ganked, the part gets yanked.

The API key has to travel with my source, as it is used at runtime to perform authentication requests.  In my case, the key must exist within the application in a configuration file or within the code itself.  That isn't a problem when I build and publish from a single machine.  However, when we throw source control into the mix, things get more complicated.

As I'm a cheap bastard, I'd much prefer to use free source control services such as TFS in the cloud or GitHub.  This leaves me with a slight conundrum:

How can I keep my body intact when my API keys are in my code, and my code is available in a public repository?

I can think of a number of ways to handle this, but none of them are that satisfying.

I could remove all private info from code, and edit it back in after deployment.  This would be a severe pain to implement (I won't detail the many ways), and isn't an option.

I could encrypt it.  But as I have to decrypt it, anyone with the source could figure out how to do so.  Pointless.

I could pay for private source control.  LOL j/k spend money?  Please.

I could use language features to segregate sensitive info from the rest of my source and therefore keep it from source control.  This is what I'm doing now, but it could easily be screwed up by mistakenly checking in the secret file.

I'm really looking for a guaranteed way to ensure I don't share my privates with the world (except on snapchat) that will work smoothly through development, debugging and deployment and be foolproof as well.  This is completely unrealistic.  So what realistically can I do?

Technical details:  VS2012, C# 4.5, source control is either going to be TF service or GitHub.  Currently using a partial class to split the sensitive keys off in a separate .cs file that won't be added to source control.  I think GitHub may have the advantage as .gitignore could be used to ensure that partial class file isn't checked in, but I've screwed that up before.  Am hoping for a "oh, common issue, this is how you do it" but I may have to settle for "that doesn't suck as much as it could have", :/


问:
How do you assess your Agile compatibility?
After adopting Agile for a while now, we started to think that we can improve how we do Agile. But for starter, we need to know how well are we doing now and to identify the problems in our current processes before we can improve it.

One thing we notice is that every team do Agile a little different from another. A ritual might works well for one team but not for another team. So we want to identify these incompatibilities in our team. What are the common tools/methods that your organization uses to identify these problems?

答:
Have you tried (company-wide) retrospectives?

Generally, it's a moment where the team comes together, usually after a sprint, to discuss what went well, what didn't go well, what they should start doing, what they should do more, what they should stop doing. At the end, you should have one or two actionable improvements to implement for the coming sprint.

Usually, this is done per team, but retrospectives can scale up to a whole organisation. However I would recommend an experienced facilitator for this. If it goes badly, you won't easily get a second chance to do it company-wide.

Holding retrospectives is an art in itself; you could take a look at using gamestorming to facilitate these retrospectives: http://www.gogamestorm.com/

This is one technique which was very well received where I work: http://www.scrumalliance.org/community/articles/2013/february/iteration-retrospective-activity-turn-the-tables

One last caveat: don't do the same retrospective technique everytime, people get bored easily.


答:
Here's what we focused on after implementing Agile:

Are your story definitions getting better?

Are your storypoint estimates getting better?

Is the team's velocity improving?

Are you holding end-of-sprint retrospectives?

Are you addressing the issues raised in these retrospectives?

Do you have a good Product Owner

Is your Product Owner actually owning the product, or do other roles in the team pick up their responsibilities?

Are you good at keeping a Sprint's content fixed?

Will you cancel a Sprint if failure is unavoidable?

will you cancel a Sprint if the requirements have changed too much?

Is the culture one of no-blame/every body is equal?

Are you automating your regression testing?

This is key for an iterative approach

Do you have the necessary tools in place?

Source control

Continuous integration

Scripted deployments

TDD or BDD

Are you addressing the technical debt association with iterative development?

Are you doing periodic refactoring/hardening sprints?

And there are more, but I haven't had my second coffee yet.

You'll find that, at first, there's always room for improvement.  But gradually the team will fall into its groove and begin working like a well oiled machine.  At which point you'll start seeing less and less improvement between sprints.  That's OK, though.  It just means you're approaching the team's optimal efficiency.

Once at this point, it's still important to constantly be self-evaluation.  Don't stop having retrospectives.  Don't stop asking how you can make things better.

Oh yeah, and a Scrum Master (if you're doing Scrum) should be able to help you with all this.  I say should because in my experience the importance of a trained Scrum Master is usually under-appreciated.  The role typically falls onto the Project Manager whom does not have the training to play the role.

Title: How do you assess your Agile compatibility?

Body:
After adopting Agile for a while now, we started to think that we can improve how we do Agile. But for starter, we need to know how well are we doing now and to identify the problems in our current processes before we can improve it.

One thing we notice is that every team do Agile a little different from another. A ritual might works well for one team but not for another team. So we want to identify these incompatibilities in our team. What are the common tools/methods that your organization uses to identify these problems?


问:
Are types erased in Haskell?
Haskell has a notion of “generic functions” that has some apparent similarity with common lisp—having neither experience with Haskell nor with common lisp, I might be very approximative here.  This means that one can define a generic to_string facility to define a string representation for all types. Of course, the facility has to be defined in the special cases but there is a to_string function whose signature is α → string.

Are types erased in Haskell, as they are in OCaml?  If yes, how does the implementation of “generic functions” in Haskell differ from that of common lisp, where types are dynamic, and thus not erased?

I understand that implementation details are compiler specific, but there is probably provisions common to many or all implementations.

答:
warning: my background in CS is not very strong, so I might not always use the correct vocabulary, and I might be wrong on some points. Anyway, here is my understanding:

I think you are confusing generics with polymorphism.

Generic types such as List<Foo> are used to describe types which take other types as parameter, and allow richer type checking.

A generic function in haskell might be count:: List a -> Int. It accepts lists of any type, and returns the number of elements. There is only one implementation.

Usually, when defining List, you cannot assume anything about T. You can only store it and give it back.

Your to_string function is a polymorphic function, which means it will behave differently under different circumstances. In haskell, this is done with typeclasses, which works like adjectives for types.

You have a Show typeclass, which defines a show :: a -> String function.

When a type Foo implements the Show typeclass, it must provide the definition of show. This type can then be used in functions requiring the Show qualifier (as in Show a => a -> whatever). Haskell cannot erase types, since those functions have to find the correct implementation of the show function.

Title: Are types erased in Haskell?


答:
The answer so far is misleading.

There needs to be made a distinction between "parametric" and "ad-hoc overloading" polymorphism. Parametric means "behaves uniformly for all types a", whereas "ad-hoc" -- what Simon refers to as polymorphic -- changes implementation based on the type.

Examples of both are reverse :: [a] -> [a], which is parametric, and show :: Show a => a -> String which is "ad-hoc" overloaded.

If you want more of an abstract intuition, I think it helps to consider the classes of natural language verbs that 'work' for all objects, like "to own" or "to think of" which pose no constraints on the object, but "to open" requires what we are talking about can be opened. I can 'think of a door', and 'open a door', while it makes no sense to e.g. 'open a tree'. To take the example even further "to open" is "ad-hoc polymorphic" as "to open a window" and "to open a complaint-ticket with customer service" are two very different things. If this seems forced - forget it! It works for me.

Both are resolved at compile-time, however, and in fact "erased". Modulo various GHC extensions and Template Haskell, etc. Types are in fact erased at compile time and never inspected on run-time.

Parametrically polymorphic functions behave identically for all types, so only one piece of code needs to be generated, whereas the compiler decides at compile time which version of a "type-classed" function needs to be run at a particular program point. This is also why the restriction of one instance per type per type class and the corresponding "newtype" work-around exists.

The implementation is detailed in SPJs textbook and Wadler and Blotts paper on type-classes.

Title: Are types erased in Haskell?

Body:
Haskell has a notion of “generic functions” that has some apparent similarity with common lisp—having neither experience with Haskell nor with common lisp, I might be very approximative here.  This means that one can define a generic to_string facility to define a string representation for all types. Of course, the facility has to be defined in the special cases but there is a to_string function whose signature is α → string.

Are types erased in Haskell, as they are in OCaml?  If yes, how does the implementation of “generic functions” in Haskell differ from that of common lisp, where types are dynamic, and thus not erased?

I understand that implementation details are compiler specific, but there is probably provisions common to many or all implementations.


问:
Split skilled Scrum team
A Scrum team has been forced together and is feeling very uncomfortable.  They are constantly saying that it is not working for them and that they are fed up with hearing the words Agile and Scrum.  They are feeling that the business if simply forcing a new buzz word on them.

They don't have any Agile experiance before this, including the Scrum master.  Also, the team consists of a very disconnected skill set.

1 manual tester

1 .NET developer

2 Cobol developers

A BA turned PO

The scrum master

The .NET dev doesn't want to learn Cobol and the Cobol devs don't want to learn .NET.

I've been asked to help out with making them more Agile, however, one of the main tennets of Agile is that the power for change must lie with those with the domain knowledge.

Kanban could help, but it wouldn't tackle the broken skill set.

Any advise on where to start?

Currently my plan is to start with the PO and see how stories are being written, but I am not sure where to go from there.

答:
To understand how to approach the problem you need to first understand from your superiors what the ultimate business goal is for having a cross functional Agile/Scrum team.  Once you know that and understand the business perspective as well as understand the culture of the company and the goals of the individual members of the team can you begin to address the concern.

Cross functional skill sets among a team is a desired goal however hiring a new team isn't a good option.  Even if you could find a number of .NET/Cobol developers who are experts in both technologies then they would be expensive and rare.

The best option is to invest in training your team.  Depending on the culture of the business and your region this may also be an unattractive option to the business if typically in your area developers have a short tenure and are constantly hopping jobs.  With the stated goal however of a cross functional team with such wildly disparate technology stacks needed for the following project, it is unfortunately the only way given the absolute that the team must be fully Cross Functional Agile.

When estimating user stories, let it be known that any given user story may be assigned to any given technical resource and that if a Cobol developer is given a primarily .NET user story that a .NET developer is obliged to provide guidance and direction to the Cobol developer.  It might be a 1 point story for the .NET dev but a 3 point story for the Cobol dev.  It is important to keep in mind that there are more Cobol devs than .NET devs so the .NET developer will have less available time for guidance and training making .NET tasks much more expensive.  Pair programming is a useful tool while doing this so encourage this.

The advantages are that this investment in your team will result in them being more cross functional to where this is no longer an issue.  The big caveat however is that user story estimation possibly being dependent on one or more people it will make various project management metrics meaningless for a while.  It will be harder to evaluate an individuals contribution to a project if it seems like they aren't producing much but perhaps they are learning a great deal along the way.

On a side note, you mentioned the team has a Scrum Master but that you are called in to do this?  In a typical Scrum team this kind of task is exactly the role of the Scrum Master.

Title: Split skilled Scrum team


答:
Embrace this... you see, Agile does NOT mean the proscribed ways of working are what you have to do. It means you get to decide what works for you and do exactly that.

Now I'm sure, given that advice, your team will become effective immediately with the Cobol guys doing their thing and communicating with the .NET guy who'll do his thing. Hopefully they'll be interested enough to pick up a few pointers to be able to find their way around the different technology, but it does not mean they all have to suddenly become multi-skilled and swap roles daily. It doesn't look to me that the skill stack is broken at all.

Make sure the team sits in a "black box" environment where external managers don't get to see what or how they do what they do. Just ensure the team is fed requirements and produces software regularly so said managers can see progress but otherwise leave them alone and let them get on with it however they choose. That is the core and true meaning of agile, regardless of whatever you've read in some Scrum bu****it manuals.

If you need some backup on this, get Alistair Cockburn's Crystal books - he part invented Agile, he know what its about. What I said above is advice taken from him.

Title: Split skilled Scrum team

Body:
A Scrum team has been forced together and is feeling very uncomfortable.  They are constantly saying that it is not working for them and that they are fed up with hearing the words Agile and Scrum.  They are feeling that the business if simply forcing a new buzz word on them.

They don't have any Agile experiance before this, including the Scrum master.  Also, the team consists of a very disconnected skill set.

1 manual tester

1 .NET developer

2 Cobol developers

A BA turned PO

The scrum master

The .NET dev doesn't want to learn Cobol and the Cobol devs don't want to learn .NET.

I've been asked to help out with making them more Agile, however, one of the main tennets of Agile is that the power for change must lie with those with the domain knowledge.

Kanban could help, but it wouldn't tackle the broken skill set.

Any advise on where to start?

Currently my plan is to start with the PO and see how stories are being written, but I am not sure where to go from there.


问:
Should I bother to write unit test for UI/UX Components?
So I am building an application with Angular and have started to get into UI testing with DalekJS (http://dalekjs.com).  As I have been writing these tests I have been thinking to myself, should I even bother with writing unit test that that are UI/UX components.

Now my angular services generally don't have anything to do with the DOM or directly rendering stuff on the page so those I unit test and it make sense however angular directives are components that render things directly to the page and writing unit tests seems like 1.  It is not an effective way to test UI/UX components and 2. It would overlap with UI/UX Tests.

For point #1, unit test (at least ones I have seen) don't actually write anything to a browser and render it.  For thing that require DOM, you generally mock the DOM in a variable and use that to test whatever you need to test.  If you have an error with a test, you can't load it up in a browser and play around with it like you could with UI/UX tests (which in my experience runs against code that is the true application that renders and everything).

For point #2, one of my directives has a property called contentVisible.  Now I can write a unit test that make sure that property is the correct value at certain points but that really don't not test what I truly want to test because even if contentVisible is set to false, the content still might be rendering to the screen which UI/UX test would pick up.

Is it still worth the effort to write unit test for UI/UX Components where UI tests would be able to pick up everything the unit test would plus also do a better job since it can test what is actually rendered?

Exception
The one exception case where I would need a unit test is for certain ajax requests.  For example, making sure an ajax request is not made of that an ajax request that does not make and changes to the UI are things that can only be tested with unit tests.

答: It would be completely useless to write unit tests for UI/UX components. For UI/UX components you should be writing UI tests using some browser recording tool like Selenium or something. If you are making AJAX calls to the back-end those methods that are called should have unit tests. Always test you app from the user perspective then work backwards.</p>


问:
Does a GPL Bison grammar infect my application?
I am thinking about using a GPL Bison grammar for my own compiler.

Will the grammar "infect" my parser such that it needs to be open source?

The grammar - in terms of - the input of bison is GPL.

答:
While Bison itself is licensed under the GPL, a parser created by Bison is not automatically covered by the GPL, at least not with recent versions of Bison:

Conditions for Using Bison

The distribution terms for Bison-generated parsers permit using the
  parsers in nonfree programs. Before Bison version 2.2, these extra
  permissions applied only when Bison was generating LALR(1) parsers in
  C. And before Bison version 1.24, Bison-generated parsers could be
  used only in programs that were free software.

Source: http://www.gnu.org/software/bison/manual/bison.html#Conditions

However, a parser created from a GPL-licensed grammar is most likely covered by the GPL as well, because it is a "work based on" the grammar (it is an automatic conversion, like compiling a program).

Of course, as in all legal matters, there is no definitive answer, and even lawyers and judges may disagree, but I believe this is the general consensus.


问:
Using Full GPL Libraries in Software as a Service (SaaS) Models
I already searched the site, but I could only find answers relating to using GPL libraries in software that people were going to sell/distribute. In this case the answer is that they must also make the source code available.

What about SaaS? That is, I'll be building an app that clients will pay a monthly fee to use over the Internet, and they won't download anything or get access to the code.

Questions:

In this case am I allowed to use full GPL libraries without having to make my source code available?

Is there some other restriction/requirement of the GPL that I should be aware even if my model is SaaS?

答:
As long as you don't distribute your binaries, there is no problem with using GPL libraries (or other code) in an otherwise closed-source project.

As far as the regular GPL and LGPL are concerned, providing access to use your software over a network (like in SaaS) is not considered distribution. This means that there is no problem with using (L)GPL libraries in a closed-source SaaS project.

What you have to watch out for are libraries that have an AGPL (Affero GPL) licence. In the AGPL license, SaaS is considered distribution and requires you to provide your users access to your source code.


问:
Contract Based Programming vs Unit Test
I am a somewhat defensive programmer and a big fan of Microsofts Code Contracts.

Now I cannot always use C# and in most languages the only tool I have is assertions. So I usually end up with code like this:

```<code>class
{
    function()
    {
         checkInvariants();
         assert(/* requirement */);

         try
         {
             /* implementation */
         }
         catch(...)
         {
              assert(/* exceptional ensures */);
         }
         finally
         {
              assert(/* ensures */);
              checkInvariants();
         }
    }

    void checkInvariants()
    {
         assert(/* invariant */);
    }
}
</code>```

However, this paradigm (or whatever you would call it) leads to a lot of code cluttering.

I have started to wonder if it is really worth the effort and whether proper unit test would already cover this?

答:
I don't think you should think of it as "vs".

As mentioned in comments by @Giorgio, code contracts are to check invariants (in production environment) and unit tests are to make sure you code works as expected when those conditions are met.

Title: Contract Based Programming vs Unit Test


答:
Contracts help you with at least one thing that unit tests don't. When you are developing a public API you can't unit test how people use your code. You can however still define contracts for your methods.

I personally would be this rigorous about contracts only when dealing with public API of a module. In many other cases it probably isn't worth the effort (and you can use unit tests instead), but this is just my opinion.

That doesn't mean I advise not to think about contracts in those cases. I always think about them. I just don't think it is necessary to always explicitly code them.

Title: Contract Based Programming vs Unit Test

Body:
I am a somewhat defensive programmer and a big fan of Microsofts Code Contracts.

Now I cannot always use C# and in most languages the only tool I have is assertions. So I usually end up with code like this:

```<code>class
{
    function()
    {
         checkInvariants();
         assert(/* requirement */);

         try
         {
             /* implementation */
         }
         catch(...)
         {
              assert(/* exceptional ensures */);
         }
         finally
         {
              assert(/* ensures */);
              checkInvariants();
         }
    }

    void checkInvariants()
    {
         assert(/* invariant */);
    }
}
</code>```

However, this paradigm (or whatever you would call it) leads to a lot of code cluttering.

I have started to wonder if it is really worth the effort and whether proper unit test would already cover this?


问:
Can someone explain the concept behind Haskell's memoization?
(note I'm putting the question here because it's about the conceptual mechanics of it, rather than a coding problem)

I was working on a small program, that was using a sequence of fibonacci numbers in its equasion, but I noticed that if I got over a certain number it got painfully slow, googling around a bit I stumbled upon a technique in Haskell known as Memoization, they showed code working like this:

```<code>-- Traditional implementation of fibonacci, hangs after about 30
slow_fib :: Int -> Integer
slow_fib 0 = 0
slow_fib 1 = 1
slow_fib n = slow_fib (n-2) + slow_fib (n-1)

-- Memorized variant is near instant even after 10000
memoized_fib :: Int -> Integer
memoized_fib = (map fib [0 ..] !!)
   where fib 0 = 0
         fib 1 = 1
         fib n = memoized_fib (n-2) + memoized_fib (n-1)
</code>```

So my question to you guys is, how or rather why does this work?

Is it because it somehow manages to run through most of the list before the calculation catches up? But if haskell is lazy, there isn't really any calculation that needs to catch up... So how does it work?

答:
The point of memoization is never to compute the same function twice - this is extremely useful to speed up computations that are purely functional, i.e. without side effects, because for those the process can be entirely automated without affecting correctness. This is particularly necessary for functions like fibo, which lead to tree recursion, i.e. exponential effort, when implemented naively. (This is one reason why the Fibonacci numbers are actually a very bad example for teaching recursion - nearly all demo implementations you find in tutorials or books are unusable for large input values.)

If you trace the flow of execution, you will see that in the second case, the value for fib x will always be available when fib x+1 is executed, and the runtime system will be able to simply read it from memory rather than via another recursive call, while the first solution tries to compute the larger solution before the results for smaller values are available. This is ultimately because the iterator [0..n] is evaluated from left to right and will therefore start with 0, while the recursion in the first example starts with n and only then asks about n-1. This is what leads to the many, many unnecessary duplicate function calls.


答:
Just to explain the mechanics behind the actual memoization,

```<code>memo_fib = (map fib [1..] !!)
</code>```

produces a list of "thunks", unevaluated computations. Think of these like unopened presents, as long as we don't touch them, they won't run.

Now once we evaluate a thunk, we never evaluate it again. This is actually the only form of mutation in "normal" haskell, thunks mutate once evaluated to become concrete values.

So back to your code, you've got a list of thunks, and you still do this tree recursion, but you recurse using the list, and once an element in the list is evaluated, it never gets computed again. Thus, we avoid the tree recursion in the naive fib function.

As an tangentially interesting note, this is especially fast over a series of fibonnaci numbers are computed since that list is only evaluated once, meaning that if you calculate memo_fib 10000 twice, the second time should be instantaneous. This is because Haskell only evaluated arguments to functions once and you're using partial application instead of a lambda.

TLDR: By storing calculations in a list, each element of the list is evaluated once, therefore, each fibonnacci number is calculated exactly once throughout the entire program.

Visualization:

```<code> [THUNK_1, THUNK_2, THUNK_3, THUNK_4, THUNK_5]
 -- Evaluating THUNK_5
 [THUNK_1, THUNK_2, THUNK_3, THUNK_4, THUNK_3 + THUNK_4]
 [THUNK_1, THUNK_2, THUNK_1 + THUNK_2, THUNK_4, THUNK_3 + THUNK_4]
 [1, 1, 1 + 1, THUNK_4, THUNK_3 + THUNK_4]
 [1, 1, 2, THUNK_4, 2 + THUNK4]
 [1, 1, 2, 1 + 2, 2 + THUNK_4]
 [1, 1, 2, 3, 2 + 3]
 [1, 1, 2, 3, 5]
</code>```

So you can see how for evaluating THUNK_4 is much faster since it's subexpressions are already evaluated.

Title: Can someone explain the concept behind Haskell's memoization?

Body:
(note I'm putting the question here because it's about the conceptual mechanics of it, rather than a coding problem)

I was working on a small program, that was using a sequence of fibonacci numbers in its equasion, but I noticed that if I got over a certain number it got painfully slow, googling around a bit I stumbled upon a technique in Haskell known as Memoization, they showed code working like this:

```<code>-- Traditional implementation of fibonacci, hangs after about 30
slow_fib :: Int -> Integer
slow_fib 0 = 0
slow_fib 1 = 1
slow_fib n = slow_fib (n-2) + slow_fib (n-1)

-- Memorized variant is near instant even after 10000
memoized_fib :: Int -> Integer
memoized_fib = (map fib [0 ..] !!)
   where fib 0 = 0
         fib 1 = 1
         fib n = memoized_fib (n-2) + memoized_fib (n-1)
</code>```

So my question to you guys is, how or rather why does this work?

Is it because it somehow manages to run through most of the list before the calculation catches up? But if haskell is lazy, there isn't really any calculation that needs to catch up... So how does it work?

Body:
Just to explain the mechanics behind the actual memoization,

memo_fib = (map fib [1..] !!)

produces a list of "thunks", unevaluated computations. Think of these like unopened presents, as long as we don't touch them, they won't run.

Now once we evaluate a thunk, we never evaluate it again. This is actually the only form of mutation in "normal" haskell, thunks mutate once evaluated to become concrete values.

So back to your code, you've got a list of thunks, and you still do this tree recursion, but you recurse using the list, and once an element in the list is evaluated, it never gets computed again. Thus, we avoid the tree recursion in the naive fib function.

As an tangentially interesting note, this is especially fast over a series of fibonnaci numbers are computed since that list is only evaluated once, meaning that if you calculate memo_fib 10000 twice, the second time should be instantaneous. This is because Haskell only evaluated arguments to functions once and you're using partial application instead of a lambda.

TLDR: By storing calculations in a list, each element of the list is evaluated once, therefore, each fibonnacci number is calculated exactly once throughout the entire program.

Visualization:

 [THUNK_1, THUNK_2, THUNK_3, THUNK_4, THUNK_5]
 -- Evaluating THUNK_5
 [THUNK_1, THUNK_2, THUNK_3, THUNK_4, THUNK_3 + THUNK_4]
 [THUNK_1, THUNK_2, THUNK_1 + THUNK_2, THUNK_4, THUNK_3 + THUNK_4]
 [1, 1, 1 + 1, THUNK_4, THUNK_3 + THUNK_4]
 [1, 1, 2, THUNK_4, 2 + THUNK4]
 [1, 1, 2, 1 + 2, 2 + THUNK_4]
 [1, 1, 2, 3, 2 + 3]
 [1, 1, 2, 3, 5]

So you can see how for evaluating THUNK_4 is much faster since it's subexpressions are already evaluated.


问:
MVC to create desktop and mobile webapps?
I'm planning the creation of a webapp with a dedicated mobile web interface and a dedicated desktop/tablet interface.

I am considering ASP.NET MVC, but it is clear to me that MVC is for separation of concerns as explained here, anyway in my case i'd like to minimize the code and to support elegantly phones and desktop (may be landscape tablet can be "desktop" too).

So is MVC a wise choice in this case or which is the 1st stop for this kind of xdevice web app?

答:
We have developed couple of apps successfully using Asp.Net Mvc that run on multiple devices.

Actually, MVC would structure the presentation layer nicely. Depending on the type of application you may also like to Business and Data layer to it.

Regarding rendering on different devices, you will have to create style sheets in CSS, which will make UI responsive and render it accordingly, depending on the type of device from which request is coming.


答:
In a talk I heard Guido say something like this:

You do not want your library in the Python standard library. Once it is there you can not change the API if you made any mistake.

So a reason I want to add is:

Incompatible changes to the API can only be made between Major Python versions.

Examples:

```<code>import SimpleHTTPServer
import CGIHTTPServer
</code>```

changed to

```<code>import http.server
</code>```

Title: What was the need of introducing Python 3 when we already had Python 2

Body:
I am still learning python and I started with Python 3. This question not Python 2 vs 3 or difference between them like print() is a function and not language construct and 3/2 = 1.5

My question is even if it is still python, what was the need of introduce something new which is not backward compatible, when -

Syntax is the same

Language philosophy is the same (import this)

Edit - Lets say all the popular packages are ported to Python 3, does that mean we no longer need Python 2

Body:
In a talk I heard Guido say something like this:

You do not want your library in the Python standard library. Once it is there you can not change the API if you made any mistake.

So a reason I want to add is:

Incompatible changes to the API can only be made between Major Python versions.

Examples:

import SimpleHTTPServer
import CGIHTTPServer

changed to

import http.server


答:
As already mentioned Contracts and unit tests have different purpose.

Contracts are about defensive programming to make sure that are prerequisites are met, code is called with right parameters, etc.

Unit tests to ensure that code works, in differnt scenarios. These are like 'specs with teeth'.

Asserts are good they make code robust. However, if you are worried that it is adding up lot of code, you may also like to add conditional breakpoints at some places during debugging and reduce the Assert count.

Title: Contract Based Programming vs Unit Test


问:
Is there a special name for a condition which will break a loop if it increments a set number of times
Is there a name for including a limitation in a loop structure to prevent it from running if its primary condition becomes unwieldy.

For example

```<code>for (var i = 0; i < len; i++){

   some_function();

}
</code>```

but if len is somewhere set to ten million, I don't want to run it, so I would do something like:

```<code>for (var i = 0; i < len && i < 50; i++){

   some_function();

}
</code>```

Is there a name for this type of hard-coded condition?

答:
I'd call it a boundary condition.

Some boundary conditions have special names, such as timeouts for example, and other boundary conditions are indicative of logical errors, such as an "off-by-one" error.


答:
This seems to be a type of a guard. See: http://en.wikipedia.org/wiki/Guard_(computer_science)

In computer programming, a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question.

In your case, i < 50 is the guard on the loop, preventing it from executing if i is too large.

I think a guard would usually be written as:

```<code>if (len< MAX_VALUE)
{
    for (var i = 0; i < len; i++)
    {
        do_stuff();
    }
}
//optional else-clause to warn when guard-condition is violated.
//else
//   ERROR("Value for i is too big!!");
</code>```

This form would allow you to write an else clause (where you could warn the user about invalid value of i, perhaps). Your compact form, where you include it in the loop condition doesn't allow for an else, but maybe you don't want one.

As some commenters have also noted, your loop will still execute up to 50 iterations, even if len is larger than 50. Using a traditional if..else guard as written above will not allow you to do this, so it's not equivalent with your code (which also checks the guard condition on each iteration).

Title: Is there a special name for a condition which will break a loop if it increments a set number of times

Body:
Is there a name for including a limitation in a loop structure to prevent it from running if its primary condition becomes unwieldy.

For example

```<code>for (var i = 0; i < len; i++){

   some_function();

}
</code>```

but if len is somewhere set to ten million, I don't want to run it, so I would do something like:

```<code>for (var i = 0; i < len && i < 50; i++){

   some_function();

}
</code>```

Is there a name for this type of hard-coded condition?

Body:
This seems to be a type of a guard. See: http://en.wikipedia.org/wiki/Guard_(computer_science)

In computer programming, a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question.

In your case, i < 50 is the guard on the loop, preventing it from executing if i is too large.

I think a guard would usually be written as:

if (len< MAX_VALUE)
{
    for (var i = 0; i < len; i++)
    {
        do_stuff();
    }
}
//optional else-clause to warn when guard-condition is violated.
//else
//   ERROR("Value for i is too big!!");

This form would allow you to write an else clause (where you could warn the user about invalid value of i, perhaps). Your compact form, where you include it in the loop condition doesn't allow for an else, but maybe you don't want one.

As some commenters have also noted, your loop will still execute up to 50 iterations, even if len is larger than 50. Using a traditional if..else guard as written above will not allow you to do this, so it's not equivalent with your code (which also checks the guard condition on each iteration).


问:
How to store historical user data?
I'm trying to think of fine way to store historical data for my web application. The application has users that add photos, comment and grade them. All this is stored in relational database.

The users also have ability to delete own photos (and thus comments/grades) and own account.

I want to store those deleted entities as historical data.
The aim of it is to distinguish categories of what people like to photograph and classify  users towards those categories.

Should I store it in some NoSQL database? Or maybe in my origin database by marking it with is_deleted field? Maybe different table e.g. archived_users, archived_photos? Another database instance for only historical data?

Has anybody dealt with such task and is willing to share thoughts?

So far, I'm using is_deleted flag for photos and backup table (archived_users) for users. Why such distinction? To avoid violating unique constraint on username field.
This solution has 3 problems to me.

It is incoherent to do same thing in 2 ways. Or maybe it's ok?

It is somehow strange moving user to another table (with associations to photos). It creates some superficial fields. Or maybe it's ok?

"Living" data is mixed with historical data. Could it be a performance problem when database is really huge?

答:
Using flags/indicators in your main database to show what's been deleted is a good way to start. And stick with that if you can.

Your other ideas, such as moving "deleted" data to separate archive tables/databases is probably only necessary if the amount of soft-deleted data is sooooo large that keeping it in the main database has a significant performance impact. Keep it simple, if you can.

Title: How to store historical user data?


答:
On a different note, I would like to see better support for iterators in programming languages. In particular, for when you want to go down two collections in pairs:

```<code>for (String s, Integer i : stringsSet, integersSet) {
    // use the pair (s, i)
}
</code>```

Some dynamic languages may already have this, or easily support via libraries and macros, but I think this is in the spirit of your question.

If the two sets are not the same size, then it could throw an exception or you could have an else after the loop to signal there was a difference in sizes.

Naturally, you could generalize this for going down three or more lists.

Update: Also useful would be doing the Cartesian product between iterables:

```<code>for (String s, Integer i : stringsSet * integersSet) {
    // use the pair (s, i), each s with each i
}
</code>```

which would be nothing more than nested loops:

```<code>for (String s : stringsSet) {
    for (Integer i : integersSet) {
        // use the pair (s, i), each s with each i
    }
}
</code>```

I'm a little concerned that between the two notations I've provided here that there is a O(n) and O(n^2) difference in the number of pairs, with only the change of a single character.

Title: Which useful alternative control structures do you know?

Body:
Similar question was closed on SO.

Sometimes when we're programming, we find that some particular control structure would be very useful to us, but is not directly available in our programming language.

What alternative control structures do you think are a useful way of organizing computation?

The goal here is to get new ways of thinking about structuring code, in order to improve chunking and reasoning.

You can create a wishful syntax/semantic not available now or cite a less known control structure on an existent programming language.

Answers should give ideas for a new programming language or enhancing an actual language.

Think of this as brainstorming, so post something you think is a crazy idea but it can be viable in some scenario.

It's about imperative programming.

Body:
On a different note, I would like to see better support for iterators in programming languages. In particular, for when you want to go down two collections in pairs:

for (String s, Integer i : stringsSet, integersSet) {
    // use the pair (s, i)
}

Some dynamic languages may already have this, or easily support via libraries and macros, but I think this is in the spirit of your question.

If the two sets are not the same size, then it could throw an exception or you could have an else after the loop to signal there was a difference in sizes.

Naturally, you could generalize this for going down three or more lists.

Update: Also useful would be doing the Cartesian product between iterables:

for (String s, Integer i : stringsSet * integersSet) {
    // use the pair (s, i), each s with each i
}

which would be nothing more than nested loops:

for (String s : stringsSet) {
    for (Integer i : integersSet) {
        // use the pair (s, i), each s with each i
    }
}

I'm a little concerned that between the two notations I've provided here that there is a O(n) and O(n^2) difference in the number of pairs, with only the change of a single character.


问:
How is DRY principle ( applied at class level ) related to SRP?
In other words, is DRY (don't repeat yourself) applied at a class level a subset of SRP (single responsibilty principle)?

What I mean is that while SRP states that each class should have only a single responsibility ( ie. class should only have one reason to change ), is it the application of DRY at class level that prevents two classes from having the same responsibility ( thus it is DRY that prevents the repetition/duplication of same responsibility in two different classes )?

Thank you

答:
Some design patterns could allow you to have simpler class by sharing the common routine.

If for example, you have to do a discount calculation on sales and in the sales report, instead of having the same code in both classes, you could have a third, more specific class, that does that calculation.

This way, your class that compute the sale, could rely on the third class to get the final price, as could the sale report class.

See the Strategy Pattern and Composite pattern as starter examples


问:
Should my statefull widget generate necessary html itself?
What behaviour should be preferred for widget initialization:

1) Required HTML is generated by widget itself:

Layout:

```<code><div id="my-widget"/>
</code>```

Initialization:

```<code>$('#my-widget').myWidget(); // Creates HTML
</code>```

2) Required HTML is placed to the page by user:

```<code><div id="my-widget">
  <div class="foo"/>
  <div class="bar"/>
</div>
</code>```

Initialization:

```<code>$('#my-widget').myWidget(); // Won't create nested div's
</code>```

Mark Otto (one of Bootstrap creators) suggest not to generate markup by javascript: https://github.com/mdo/code-guide#javascript-generated-markup

Currently, I use the following function, which appends element to the root of the widget (this.$element) only if it doesn't exist:

```<code>function($content) {
  var $child = this.$element.children('.' + $content.attr('class'));
  return $child.length ? $child : $content.appendTo(this.$element);
};
</code>```

答:
I think it depends on how you will use the widget.

Generate all html by javascript if the widget is not related to the page. Having javascript handle all makes your widget self-contained and it can be easily integrated.

Write your html out and add the behavior with javascript, if your widget is part of your page.

I don't think that there is a reason to refrain from creating html in javascript. It is a design choice you have to take. Either you take javascript as the base or html.

The classic approach is to take html as base, but you could also create everything with javascript. That's what you do when using a framework like ExtJs : the html file would typically have an empty body.

On the other hand I agree fully with the argument stated in the html coding guide you link:

JavaScript generated markup

Writing markup in a javascript file makes the content harder to find,
  harder to edit, and less performant. Don't do it.


问:
Why is a click event triggered only after mouse click and release?
Every click event on the web works on mouse click and release. Is there a way to do a action on a click event before mouse release??</p>

答: Because "mouse click" is defined as down/up in the same spot. On the other hand, down/move/up would not be a mouse click but a mouse drag. If you want to specifically listen for mouse button down, most event systems allow you to subscribe for mouse down event. In JavaScript, that would be the onmousedown event.


答:
OK, this is a fun question.

I would also like to have a general else for while and for loops, for when the condition isn't true on the first test:

```<code>while (condition) {
    // process
}
else {
    // condition was never true
}
</code>```

This avoids the awkward re-computation of the condition or storing it in a variable.

Body:
OK, this is a fun question.

I would also like to have a general else for while and for loops, for when the condition isn't true on the first test:

while (condition) {
    // process
}
else {
    // condition was never true
}

This avoids the awkward re-computation of the condition or storing it in a variable.


答:
What I mean is that while SRP states that each class should have only a single responsibility ( ie. class should only have one reason to change ), is it the application of DRY at class level that prevents two classes from having the same responsibility ( thus it is DRY that prevents the repetition/duplication of same responsibility in two different classes )?

No. You can still not repeat yourself but violate single responsibility. Likewise, you can repeat yourself but classes only have a single (duplicated, but subtly different) responsibility.

While the two guidelines can and will tend to overlap, they are orthogonal concepts.

Title: How is DRY principle ( applied at class level ) related to SRP?

Body:
In other words, is DRY (don't repeat yourself) applied at a class level a subset of SRP (single responsibilty principle)?

What I mean is that while SRP states that each class should have only a single responsibility ( ie. class should only have one reason to change ), is it the application of DRY at class level that prevents two classes from having the same responsibility ( thus it is DRY that prevents the repetition/duplication of same responsibility in two different classes )?

Thank you


答:
In your case, you could trap onmousedown or onmouseup before the click event is fired.

The onmousedown, onmouseup, and onclick events are all parts of a
  mouse-click. First when a mouse-button is clicked, the onmousedown
  event is triggered, then, when the mouse-button is released, the
  onmouseup event is triggered, finally, when the mouse-click is
  completed, the onclick event is triggered.

Javascript Event Tutorial

Title: Why is a click event triggered only after mouse click and release?

Body: Every click event on the web works on mouse click and release. Is there a way to do a action on a click event before mouse release??</p>


问:
Good guidelines and practices for mandatory code review
We are trying out mandatory code review on each commit -- nothing gets into master that hasn't been validated by at least 1 person not the author -- for a couple of sprints. We have buy in from both developers and management (which is an amazing situation to be in) and we want to get some of the benefits that it is known for:

obvious bug reduction

more awareness of changes happening around the project

the "I know someone is going to look at this so I won't be lazy"/anti-cowboy effect

increased consistency within/across projects

But we're introducing something that is known to reduce velocity, and if done wrong could create a stupid bureaucratic step in the commit pipeline that doesn't do anything but take up time. Things that I'm concerned about:

reviews devolving into just nit picking

(hyperbolically) people opening up huge architectural issues as part of a two line commit review.

I don't want to bias answers with other things.

While we're all reasonable people and we'll be doing a lot of self analysis, we could definitely use some battle-won insight into what kinds of things we should be trying to accomplish in a review session to really make reviews work for us. What are some guidelines and policies that you have found to work?

答:
Make reviews short.

It's hard to stay concentrated, especially during code review, for a long time. Moreover, long code reviews may indicate either that there is too much to say on the code (see the next two points) or that the review becomes a discussion over larger issues, such as the architecture.

Also, a review should remain a review, not a discussion. It doesn't mean that the author of the code can't reply, but it shouldn't turn into a long exchange of opinions.

Avoid reviewing code which is too bad.

Reviewing low quality code is depressing both for the reviewer and the author of the code. If a piece of code is terrible, a code review is not useful. Instead, the author should be asked to rewrite the code correctly.

Use automated checkers prior to the review.

Automated checkers avoid wasting precious time pointing mistakes which can be found automatically. For example, for C# code, running StyleCop, Code metrics and especially Code analysis is a good opportunity to find some of the errors prior to the review. Then, code review may be spent on points which are extremely hard to do for a machine.

Choose carefully the persons doing reviews.

Two persons who can't bear each other won't make a good review one of another's code. The same problem arises when one person doesn't respect the other one (no matter whether it's the reviewer or the author, by the way).

Also, some persons are just unable to see their code reviewed, so they require specific training and preparation to understand that they are not criticized and they shouldn't see it as something negative. Doing a review, unprepared, won't help, since they'll be always on a defensive and won't listen to any critics of their code (taking every suggestion as a criticism).

Do both informal and formal reviews.

Having a checklist helps in being concentrated on a precise set of flaws, avoiding to devolve into nit picking. This checklist can contain points such as:

SQL Injection,

Wrong assumptions about a language which can lead to errors,

Specific situations which can lead to errors, such as operator precedence. For example, in C#, var a = b ?? 0 + c ?? 0; might look fine for someone who wants to add two nullable numbers with coalesce at zero, but it isn't.

Deallocation of memory,

Lazy loading (with its two risks: loading the same thing more than one time, and not loading it at all),

Overflows,

Data structures (with errors such as a simple list instead of a hash set, for example),

Input validation and defensive programming in general,

Thread safety,

etc.

I stop the list here, but there are hundreds of points which may figure in a checklist, depending on the weak points of a precise author.

Progressively adjust the checklist.

In order to stay constructive and useful over time, checklists used in formal reviews should be adjusted over time depending on the mistakes being found. For example, first informal reviews may reveal a certain amount of risks of SQL Injection. SQL Injection checking will be included in the checklist. When, a few months later, it appears that the author is now very careful about dynamic vs. parametrized queries, SQL Injection may be removed from the checklist.