问:
Is Pair Programming also used to train less experienced developers and bring them up to speed?
I am familiar with Agile and Pair Programming (http://en.wikipedia.org/wiki/Pair_programming).  I thought Pair Programming was used if there was a complex requirement i.e. two sets of eyes is better than one.

Is Pair Programming also used to train less experienced developers and bring them up to speed?

Also, how often is it used e.g. all the time i.e. the two developers will work together at one screen permanently or perhaps one day per week? I have read an Agile book, which talks about this concept but it does not mention frequency of use.

答:
Strongly disagree with this answer.

I have previously mentored junior developers and new joiners through pair programming. On a review, they found it very useful and they were up to speed much quicker than people who were left on their own.

When I was driving, they saw me use a range of short cuts within IDE which significantly improves my productivity. When they were driving I encouraged them to use the same short cuts - within days they were already more productive.

Unit testing was another area. Many junior developers had no exposure to unit testing. I was able to demonstrate them how we write test, what our naming conventions are and what a good unit test looks like. When I was 'navigating' I was able to advise 'driver' as they were writing tests.


问:
Why are different components of the "web platform" not modularized?
The web platform is hip these days.  But the web platform consists of many parts that are conceptually separable, developed at different times and paces, and (most important to me) could be useful on their own.  Basically the web platform is "a browser", but the browser lumps together several things:

HTML/CSS renderer

DOM

scripting on the renderer and DOM (JavaScript)

sandboxing (including cross-site scripting restrictions, limited access to local files, etc.)

the browser itself, which is a GUI app with its own look and feel

My question is, am I really the only one who thinks it would be useful to have each of these as separate components that are usable on their own, mixable and matchable with different versions of each other and with other programming tools?  The renderer/DOM are the ones I'd really like to see abstracted, because HTML/CSS is a very nice way to describe interfaces, but it's annoying that it can only be used to describe interfaces on a web page.

Most notably, the link between the rendering engine, JavaScript, and the browser GUI seems almost impenetrable.  This makes it really annoying to use HTML/CSS for interface design, because your interface is always going to be running inside a browser that you don't control, and you have to use JavaScript.  Compare that to other interface toolkits (like Tk, Qt, Wx), which often have bindings to multiple programming languages and can be leveraged in standalone apps that you have total control over.  (This means, for instance, that browser-wide user preferences for things like fonts can interfere with your presentation, and it means any menus, keyboard shortcuts, or other UI doodadssyou create have to compete with those of the enclosing browser.)

In similar fashion, it's very tough to write something that has an HTML/CSS interface, but stores data on your local computer, because browsers think it's an insecure web app, even if what you want it to be is just a "regular app".

I know there are historical reasons why people did all this together, but I find it baffling that at no point have people thought it would be worthwhile to make a separate, pluggable rendering engine that could be used with multiple programming languages, or a "browserapp maker" that would run a single web app in its own window, or anything like that.

Or, do such things already exist?  I'm aware of things like the web widgets in GUI toolkits, and XULRunner, but as far as I can see these still seem to be embedding a browser-like amalgam of several components.  (In particular, there does not appear to be a stable, mature rendering engine with DOM-access bindings for languages other than JavaScript.)  This makes them more heavyweight and less integrable into an application than it would be if you could just grab an HTML rendering library the same way you grab Qt or a PNG library or anything else.

答:
There's indeed been an attempt, FireFox tried to open up its GUI toolkit for non-browser applications under the label "XulRunner". We tried it, not a success.

For starters, XulRunner competes with far better toolkits such as Qt. The C++ interface is downright horrible. You're also tied to Javascript for a lot of tasks. Performance isn't great.

It's also documented up to the usual Open Source standards. We never figured out how to remove the spelling component.

That said, you're mistaken if you think Qt is lightweight similar to a PNG library. However, it is far better designed, and you can actually remove bits you don't need. It's really easy.

So, the conclusion is that it's been tried, and did not create a convincing product.

ContentLicense: CC BY-SA 3.0


问:
What is the most obscure sorting algorithm you know?
I just read about cyclesort via a sortvis.org blog post.
This is probably the most obscure one I have heard of so far, since it uses maths that I am not familiar with (detecting cycles in permutations of integer sets).

What is the most obscure one you know?

答:
Slowsort works by multiply and surrender (as opposed to divide and conquer). It is interesting because it is provably the least efficient sorting algorithm that can be built (asymptotically, and with the restriction that such an algorithm, while being slow, must still all the time be working towards a result).

This offsets it from bogosort because in the best case, bogosort is quite efficient – namely, when the array is already sorted. Slowsort doesn’t “suffer” from such a best-case behaviour. Even in its best case, it still has runtime   for ϵ > 0.

Here is its pseudocode, adapted from the German Wikipedia article:

```<code>function slowsort(A, i, j):
  if i >= j: return

  m = (i + j) / 2
  slowsort(A, i, m)
  slowsort(A, m + 1, j)

  if A[j] < A[m]:
    swap(A[j], A[m])

  slowsort(A, i, j - 1)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Slowsort works by multiply and surrender (as opposed to divide and conquer). It is interesting because it is provably the least efficient sorting algorithm that can be built (asymptotically, and with the restriction that such an algorithm, while being slow, must still all the time be working towards a result).

This offsets it from bogosort because in the best case, bogosort is quite efficient – namely, when the array is already sorted. Slowsort doesn’t “suffer” from such a best-case behaviour. Even in its best case, it still has runtime   for ϵ > 0.

Here is its pseudocode, adapted from the German Wikipedia article:

function slowsort(A, i, j):
  if i >= j: return

  m = (i + j) / 2
  slowsort(A, i, m)
  slowsort(A, m + 1, j)

  if A[j] < A[m]:
    swap(A[j], A[m])

  slowsort(A, i, j - 1)


问:
Factory method vs Factory design pattern
I know about Simple Factory Idiom, Factory Method and Abstract Factory Design patterns.

But I have two situations that I'm not sure how to call (PHP code example) :

```<code>class User {
  public static function LoadUserById($id) {
    $objUser = new User();
    //load details from DB
    return $objUser;
  }
}

class UserFactory {
   public function Create($id) {
    $objUser = new User();
    //load details from DB
    return $objUser;
   }
}
</code>```

What are these two situations? Simple Factories (programming idiom) or are they called something else?

Is a good practice to name the class UserFactory? Isn't this something that might get confused with the A factory design pattern? Should I use different name for it like UserFinder?

When I think of the Factory Design Pattern I always think of examples where there are families of components derived from a parent class but it is clearly not the case here.

答:
The former one is called a violation of the single responsibility principle :) Your User class shouldn't know or care about the database. It is an anti-pattern, if anything.

There should be only one reason to change the User class - and it is that the concept of user within your application may change.

Implementing LoadUserById on the User class means that you'd have to rewrite that class for totally unrelated reasons - such as switching from MySQL to PostgreSQL, for example, which has nothing to do whatsoever with the user as such. Such implementation details should be detached, externalized.

The latter one is more of a Repository pattern than Factory, I believe. UserRepository could be a quite reasonable name for such a class.

Note that the role of a Factory is to create objects, especially whenever this task is complex and involves some advanced logic that you want to keep in one place.

Retrieving data from the database is a different responsibility. It's not about creating an object in itself - the real goal is obtaining data for that object (or "hydrating" it, as some insist).


问:
Mapping variable inputs to user interface elements

Background

Developing a system for creating eBooks. The data is highly normalized. The eBook designs are packaged as "themes." The themes can be configured with options for: fonts, colours, some layout, and thematic elements (such as squares for bullet lists could become circles, hexagons, or arrows).

The options are tightly coupled to the theme. For example, one theme might only allow the user to select certain fonts, while another theme might not have any thematic elements at all, while all themes might provide options for changing the page number layout, theme colours, and content for the header/footer.

Creating eBooks is one example of the general class of problem:

The output depends on configurable options; the available options depend on a particular constraint set.

Problem

When a new constraint set (e.g., eBook theme) is created by a developer, the configurable options must be exposed as user interface elements. The user interface elements could be mapped to the options using a descriptive language, or XML. For example:

```<code><group id=”page-number”>
  <group id=”text-attribute”>
    <string name=”UserInputPage” default=”# / ##” id=”ui-page” />
    <colour name=”UserColourPrimary” id=”ui-colour-primary” />
    <select name=”UserSelectBullet” id=”ui-bullet”>
      <option id=”ui-select-square” />
      <option id=”ui-select-circle” />
    </select>
    <integer name="UserRandomSeed" min="1" max="50" id="ui-random-seed" />
  </group>
</group>
<text language="en">
  <!-- Tab name -->
  <ref id=”page-number”>Page Number</text>
  <!-- Group name -->
  <ref id=”text-attribute”>Text Attributes</text>
  <!-- Display name for select options -->
  <ref id=”ui-select-square”>Square</text>
  <ref id=”ui-select-circle”>Circle</text>
</text>
</code>```

The underlying theme implementation (whether PHP, Lua, Java, or C++) would define, expose, and use variables such as:

```<code>UserInputPage
UserColourPrimary
UserSelectBullet
</code>```

Using XSLT, it would be reasonably trivial to convert the above map into sensible UI widgets that correspond to the variable definition in the XML.

By creating this map, developers need not explicitly create the user interface, nor worry about either its layout or menu structure. The developer creates a map of the software's input variables and the computer automatically generates the UI. The UI, in this case will be XHTML, but could be XUL or any other representation.

Comparison

Frameworks such as JavaServer Faces are similar to this idea; JSF and ADF issues include:

Too complex with too much overhead.

Often tied to specific implementation languages.

The inputs are bound too closely to their final representation.

For example:

```<code><h:inputText value="#{helloBean.name}" ... />
<af:selectOneRadio value="#{bindings.x.hints.inputValue} layout="vertical" />
</code>```

Vertical "selectOneRadio" radio button inputs should not be hard-coded throughout the application. Instead, the final UI representation should be based on intelligent defaults. In the XML example from the problem section, the UI should generate two radio buttons because there are two inputs in the select item. Three items would generate a drop-down. One item would create a checkbox.

Similarly, the <string> could generate any of:

input in HTML;

JTextField in Java; or

QLineEdit using QT4.

Also similarly, the <integer> could generate a slider or a simple input field. Validation would be performed elsewhere.

With HTML, the final look and feel of the item would be driven by CSS, just as with JSF.

Related

Somewhat related:

Development Approach: User Interface In or Domain Model Out?

http://en.wikipedia.org/wiki/User_interface_markup_language

Question

What approach would you take to create such a variable map definition that can then generate UI code?

答:
First off, I would agree that most of the solutions that are already available look very complex and tied to concrete implementations. Although you are essentially going to be re-inventing the wheel, I don't think it is an overly difficult wheel to re-invent and I think that the benefits you will gain over time from having a nice, clean, simple solution will definitely justify the up-front investment.

My approach would be as follows:

Themes should be able to produce their own metadata files. I was going to suggest that JSON would be just as good as XML for these files, but on reflection I think XML would be the better option. Either way, you wouldn't be editing them manually, so what matters is convenience for the theme programmer.

I would write a separate validator to validate both theme metadata files and the config that the UI generator creates.

I would then identify the different kinds of controls you are going to need and build those into the specifications of the theme metadata file. This is where some flexible thinking comes into play. I would have options like "boolean", which will get rendered as a checkbox but for lists I would provide "radio" and "dropdown" options, because sometimes a set of radio buttons is more appropriate than a drop down list and vice versa. I would also provide a "regex" option so that the UI can carry out some basic validation where necessary. Things like page number formatting I would implement by including a list of tokens with a field description, which the UI displays to the user so that the user knows they can use those tokens in the field. For example, the page format field might be a string field, max 30 characters and provides the [page_no] and [total_pages] tokens to be included in the config. So the theme metadata file would be fairly flexible, with elements containing optional parameters, validation info, option lists, etc.

The resulting theme config files would use the same format (eg. XML) and, as mentioned, should be able to be validated by a stand-alone tool. (I realise that's an implementation detail, but it would be the first place I would start, as I would be running this tool constantly during development as both it and the theme metadata format evolved).

Rendering the UI based on this kind of file wouldn't be all that hard on any platform, assuming a single, vertically formatted scrollable page. I think the key to making this work is being creative around the definition of the theme metadata files and not boxing one's thinking into one paradigm or another.


问:
Using Autoincrement Primary keys as Foreign Keys
When creating a table, there is an option for us to set the numeric primary key as autoincrement where its value increases whenever a new data in inserted.

This primary number can be used for setting the relationship of a table where it is assigned as a foreign key to that table.

So my question is it a good practice for us to use the autoincrement numeric primary as foreign key or should we use the programmatically generated code.

e.g.
for a table products we have the fields id (autoincrement primary key), productCode (program generated unique item code. field property also set to unique), Description. and we are going to create a relationship to a transactions table. What field should be used as foreign key: autoid or productCode?

答:
An autoincrement primary key is just as much programatically created as one you calculate yourself. And it's just as (if not more so) unique.

I've never encountered a situation where people had any second thoughts about using them as foreign keys (where a foreign key on the primary key is appropriate of course, which is normally the case).


问:
How do I unit test multi-threaded code?
Are there ways to unit test your multi-threaded code for race conditions and deadlocks?

To see if they are performing the way they should be...

答:
I don't remember the details exactly, but this is the general idea. And I've only done it once, but what I did was separate the re-entrant code from the code performing the task, using an interface to be able to mock the task class.

Then I designed my mock-up to be able to lock on a call so that I know the thread is in the critical section, and then call it again and verify that it is waiting, before releasing the first thread and finish cleanly.

Something like that.

I'm not sure that would work for more complex scenarios, but it helps preserve the behaviour during refactorings.

Title: How do I unit test multi-threaded code?


答:
I'd use the auto-increment key. These keys are completely meaningless and in no way connected to the business or something in the environment that might change them, and this makes them much easier to use as foreign keys in other tables.

No matter how much the business is promising that some meaningful key will never change, or that the algorithm that is creating the keys will stay the same forever, these things might change, and when they do there will be problems if you didn't remember to set up cascading updates or something like that.

Title: Using Autoincrement Primary keys as Foreign Keys

Body:
When creating a table, there is an option for us to set the numeric primary key as autoincrement where its value increases whenever a new data in inserted.

This primary number can be used for setting the relationship of a table where it is assigned as a foreign key to that table.

So my question is it a good practice for us to use the autoincrement numeric primary as foreign key or should we use the programmatically generated code.

e.g.
for a table products we have the fields id (autoincrement primary key), productCode (program generated unique item code. field property also set to unique), Description. and we are going to create a relationship to a transactions table. What field should be used as foreign key: autoid or productCode?


问:
Is it ever OK to commit non-working code?

Is it good idea to require to commit only working code?

This commit doesn't need to leave the repository in a working state as:

... we are in early design stages, the code is not yet stable.

... you are the sole developer on the project. You know why things aren't working. Furthermore, you are not stopping anyone's work by committing broken code.

... the code currently doesn't work. We are going to make a big change to it. Let's commit, in order to have a point to revert to if things get ugly.

... the chain is long, no trouble if broken code exists in the local branch. I.e.

local files

staging area

commits in local branch

commits in remote personal feature branch

merge with remote develop branch

merge with remote master branch

merge with remote release branch

... commit early,commit often.

So in the above-linked question, the majority of answers say that committing not-compilable code is no problem in local and feature branches. Why? What is the value of a broken commit?

Some of the highly voted comments say that on a local brach one can do whatever one wants. However, I am not interested in the technical side of the question. Rather I would like to learn the best practices - the habits that people who have worked many years in the industry have found most productive.

I am amazed at the vast amount of great answers! They lead me to the conclusion that I am not adept enough at using branches to organize my code.

答: The value of any commit, broken or not, is that the code is commited to a server. In professional environments, that server is secure, redundant and running backups. If I work all day, commiting is a form of making sure my code survives whatever happens to my local machine. Hard disks die. Laptops get lost or stolen. Backups of the repository server will be available even if the building burns down. </p>

ContentLicense: CC BY-SA 4.0


问:
Refactorable God v.s. too many classe
So I have this problem: in order to structure my code hierarchically, for every new tiny thing, I create a separate sub-folder, file, class ... and in it one 10-line function. It is an anti-pattern.

Lately I have been trying to err on the opposite side. That is, when I need something new, instead of dreaming up grand hierarchies, I just type the code somewhere inside the existing classes.

This is beginning to look like another anti-pattern, and I wander which is the lesser evil.

So the pattern is the following: write everything here and now, and, when the need arises, refactor the code out to a separate class. Kind of refactorable God.

Am I using this as an excuse to write God classes? Or is there a pattern/worklfow, similar to this one, that I can adopt? What are the indicators that things are going well/terrible?

答:
When creating a new method, first think:

Does this method correspond to a property or a behavior of an object, or:

Is it something completely new?

In the first case, you'll rather put it in the corresponding class. In the second case, indeed, you'll create a new class.

The problem with the first case is that sometimes, you'll end up with a class too big. This is a hint that the class should be refactored into multiple smaller classes. What is big or not depends on the circumstances. For example:

```<code>Rectangle
{
    int x;
    int y;
    int width;
    int height;
}
</code>```

can easily be refactored into:

```<code>Rectangle
{
    Point position;
    Size size;
}

Point
{
    int x;
    int y;
}

Size
{
    int width;
    int height;
}
</code>```

Title: Refactorable God v.s. too many classe

Body:
When creating a new method, first think:

Does this method correspond to a property or a behavior of an object, or:

Is it something completely new?

In the first case, you'll rather put it in the corresponding class. In the second case, indeed, you'll create a new class.

The problem with the first case is that sometimes, you'll end up with a class too big. This is a hint that the class should be refactored into multiple smaller classes. What is big or not depends on the circumstances. For example:

Rectangle
{
    int x;
    int y;
    int width;
    int height;
}

can easily be refactored into:

Rectangle
{
    Point position;
    Size size;
}

Point
{
    int x;
    int y;
}

Size
{
    int width;
    int height;
}


问:
Auto - incremental ID in Domain Object
I read a lot about auto-incremental id (guid, interlocked.increment, ObjectIdGenerator...) but don't find nothing for my situation.

In my domain model user ask to have an automatic progressive numeric Id for each Activity they create.

Since it's a user request I want to put it in my domain model, but the mode I usually do it in older application without good architecture ) is accessing database, retrieve the max and add 1; so I can't do it in my object since domain layer must not be aware of db.

Don't like db identity for lack of control (sometimes db administrator have to change the id for user error on creation of activity).

interlocked.increment look fine but my application is installed on every user machine so I can't use it

Since it must be intelligible and progressive I can't use guid

I find a good idea in Lev Gorodinski article about Service Domain in Domain-Driven-Design: define the interface of a GenerateActivityId in domain layer as a Domain Service, but I don't find a way to make a good implementation of it.

Any suggestion?

EDIT:
Lev Gorodinski idea:

```<code>public class Activity {
  public int Id {get; private set;}
  public string Description {get;set;}

  public Activity (string description){
    this.Description = description
    this.Id = generator.GenerateId()
  }
}

public interface IIdGenerator{
  int GenerateId()
}
</code>```

but i don't see where "generator" is defined and don't found IIdGenerator implementation: where should i put the implementation?
In ActivityRepository? If yes i can omit IIdGenerator for the IActiviryRepositoryInteface ?

答:
My idea:

Domain Layer

```<code>public class Activity {
  public int Id {get; private set;}
  public string Description {get;set;}

  public Activity (string description){
    this.Description = description
    var activityRepository = kernel.Get<IActivityRepository>();
    this.Id = activityRepository .GetMaxId() + 1
  }
}

public interface IActivityRepository{
  public int GetMaxId();
}
</code>```

Data Access layer

```<code>public class ActivityRepository
{
    pulic int GetMaxId()
    {
      // query for retriving max id from table
    }
}
</code>```

Somewhere (where?) i define dependecy injection with Ninject

```<code>var kernel = new StandardKernel();
kernel.Bind<IActivityRepository>().To<ActivityRepository>();
</code>```

Title: Auto - incremental ID in Domain Object

Body:
My idea:

Domain Layer

public class Activity {
  public int Id {get; private set;}
  public string Description {get;set;}

  public Activity (string description){
    this.Description = description
    var activityRepository = kernel.Get<IActivityRepository>();
    this.Id = activityRepository .GetMaxId() + 1
  }
}

public interface IActivityRepository{
  public int GetMaxId();
}

Data Access layer

public class ActivityRepository
{
    pulic int GetMaxId()
    {
      // query for retriving max id from table
    }
}

Somewhere (where?) i define dependecy injection with Ninject

var kernel = new StandardKernel();
kernel.Bind<IActivityRepository>().To<ActivityRepository>();


问:
Is it ever a good idea to use the design pattern name in the implementing classes?
Recently I came across a moderately large python codebase with lots of MyClassAbstractFactory, MyClassManager, MyClassProxy, MyClassAdapter etc. classes.

While on the one hand those names pointed me to research and learn the corresponding patterns, they were not very descriptive of what the class does.

Also, they seem to fall within the forbidden list of words in programming: variable, process_available_information, data, amount, compute: overly broad names, that don't tell us anything about the function when used by themselves.

So should there be CommunicationManager or rather PortListener? Or maybe I do not understand the problem at all...?

答:
AbstractFactory is indeed a poor choice for a name. There is no way to know what is created by this factory, and when you'll look for an entity which creates Animals, you'll never find the corresponding factory by name.

AnimalAbstractFactory is not a wise choice neither, since in most languages, it would be redundant with the abstract keyword in the signature.

This being said, there are several good reasons, highlighted by the comments, to actually include Abstract in the name: not only there are several contexts where you don't have the full signature, but just the name, but also, keeping AnimalFactory for an interface may be a wise choice (unless, unfortunately, the convention of the language/framework is to prefix interfaces with I).

AnimalCreationUtility would also be a bad choice: if it's a factory, make things easier for people who will read code, and call it a factory.

abstract AnimalFactory is ok. It doesn't have redundancy, and is clear that it is an abstract factory which delegates the creation of animals to its children.

So yes, including the name of the design pattern is a good idea, but it should be only a part of the name, and shouldn't be redundant with the other parts of the signature.


答: The whole point of using pattern names in classes is to make it easy to understand what the class does. If you name the class AnimalFactory it's obvious that the class creates Animal instances. If the name of your class includes a name of a pattern and it does not describe what it does you've either chosen a wrong pattern or implemented it incorrectly.</p>

Title: Is it ever a good idea to use the design pattern name in the implementing classes?

Body:
Recently I came across a moderately large python codebase with lots of MyClassAbstractFactory, MyClassManager, MyClassProxy, MyClassAdapter etc. classes.

While on the one hand those names pointed me to research and learn the corresponding patterns, they were not very descriptive of what the class does.

Also, they seem to fall within the forbidden list of words in programming: variable, process_available_information, data, amount, compute: overly broad names, that don't tell us anything about the function when used by themselves.

So should there be CommunicationManager or rather PortListener? Or maybe I do not understand the problem at all...?


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

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

答:
I ask the candidate to design a solution to a problem I actually encountered in my day to day work. Doing so, I try to create a dialog between me and the candidate. I try to discuss about the design he is building as if I had never thought about the problem before.

What I try to evaluate is whether we are able to understand each other, and whether we can talk about a technical problem without confusion.

Concrete example

(For a java desktop developper)

Design an API to handle the navigation history of a web browser (previous page, next page, list the 10 previous pages), and that can be reusable in many parts of the application (here I give concrete examples in our app). Then, sketch up an implementation.

I like this one, because it's simple enough, it's easy to illustrate, it can be solved step by step (add additional behaviors without breaking everything), it allows to talk about edge cases and error handling, and it also allows to talk about data structures.


问:
What is the point of double check locking?
I have been reading the Wikipedia article on double check locking and one thing that's not clear from it (at least to me) is what the pattern achieves.  What is the reason for making the two checks below?  Why not have triple checked locking?  Wouldn't that be even better?</p>

```<code>if (mySingleton == null) { // 1st check
            lock (myLock) {
                if (mySingleton == null) { // 2nd (double) check
                    mySingleton = new MySingleton();
                }
            }
        }
</code>```

答:
The correct version without double check locking is:

```<code>lock (myLock) {
    if (mySingleton == null) { // 2nd (double) check
        mySingleton = new MySingleton();
    }
}
</code>```

However this requires the expensive operation of getting a lock each time you want to get the singleton, however the lock is actually only need once (during the first initialization).

So the double check was introduce where a thread will check mySingleton outside the lock and if it passes the first check (mySingleton is not null) then you don't need to bother with acquiring the lock at all.

The inner check remains to avoid the race condition when 2 threads reach the lock block to initialize mySingleton however this can cause a double initialization if the inner check is not there (2 threads go in the lock block on at the time).

Adding a third check is useless, there are only 2 real states here: outside the lock and inside the lock. Where would you put the third check?

Body:
The correct version without double check locking is:

lock (myLock) {
    if (mySingleton == null) { // 2nd (double) check
        mySingleton = new MySingleton();
    }
}

However this requires the expensive operation of getting a lock each time you want to get the singleton, however the lock is actually only need once (during the first initialization).

So the double check was introduce where a thread will check mySingleton outside the lock and if it passes the first check (mySingleton is not null) then you don't need to bother with acquiring the lock at all.

The inner check remains to avoid the race condition when 2 threads reach the lock block to initialize mySingleton however this can cause a double initialization if the inner check is not there (2 threads go in the lock block on at the time).

Adding a third check is useless, there are only 2 real states here: outside the lock and inside the lock. Where would you put the third check?


答:
Its worth noting that in C# there is a thread safe approach that avoids the need to use locking for creating the singleton instance.</p>

```<code>class MyClass
{
    //  Static constructor - Can only by called once per application domain.
    static MyClass()
    {
        //  We must be the only thread.
        MyClass.Instance = new MyClass();
    }

    static public MyClass Instance { get; private set; }

    protected MyClass()
    {
        //  Class constructor.
    }
}
</code>```

Title: What is the point of double check locking?

Body:
I have been reading the Wikipedia article on double check locking and one thing that's not clear from it (at least to me) is what the pattern achieves.  What is the reason for making the two checks below?  Why not have triple checked locking?  Wouldn't that be even better?</p>

```<code>if (mySingleton == null) { // 1st check
            lock (myLock) {
                if (mySingleton == null) { // 2nd (double) check
                    mySingleton = new MySingleton();
                }
            }
        }
</code>```

Body:
Its worth noting that in C# there is a thread safe approach that avoids the need to use locking for creating the singleton instance.

class MyClass
{
    //  Static constructor - Can only by called once per application domain.
    static MyClass()
    {
        //  We must be the only thread.
        MyClass.Instance = new MyClass();
    }

    static public MyClass Instance { get; private set; }

    protected MyClass()
    {
        //  Class constructor.
    }
}


问:
What's best practice for a SELECT * FROM SQL in PHP?
I need to make a "SELECT * FROM" Sql from PHP, that now returns about 10.000 records, that I insert in an Array and re-utilize in a page to show results in a table.

I need to have all that elements also in a hidden input fields, to connect via API to a SMS service to send SMS

```<code><input type="hidden" id="destinatariSMS" name="destinatariSMS" value="<?php echo htmlentities(serialize($destinatariSMS)); ?>" />
</code>```

Obviously, with 10k elements loading of page is about 10-15 seconds (in a VPS with 2GB ram).

I'm worrying because in about two months element will be 12-13k, about 1k elements at the month.

I cannot paginate elements because I need all together in that input...

In your opinion, what's best practice to no "destroy" VPS or browser?

Thank you very much

答:
The best practice in SQL is NOT to use "SELECT *".

Is there no way that you can bring logic from your PHP program to your query so you don't get 10.000 results?

I always cringe when I see programs filtering or making trivial calculations on data which the database server could easily do.


答: One of the philosophies suggested by Linus Torvalds is that creative programming should be like a series of experiments. You have an idea, and follow it. It doesn't always work out, but at least you tried it. You want to encourage developers to try creative ideas, and to do that, it must be cheap to try that experiment, and cheap to recover.  This is the true power of git commits being so cheap (fast and easy). It opens up this creative paradigm that empowers developers to try thing they might not have otherwise. This is the liberation of git.</p>

Title: Is it ever OK to commit non-working code?

Body:
Is it good idea to require to commit only working code?

This commit doesn't need to leave the repository in a working state as:

... we are in early design stages, the code is not yet stable.

... you are the sole developer on the project. You know why things aren't working. Furthermore, you are not stopping anyone's work by committing broken code.

... the code currently doesn't work. We are going to make a big change to it. Let's commit, in order to have a point to revert to if things get ugly.

... the chain is long, no trouble if broken code exists in the local branch. I.e.

local files

staging area

commits in local branch

commits in remote personal feature branch

merge with remote develop branch

merge with remote master branch

merge with remote release branch

... commit early,commit often.

So in the above-linked question, the majority of answers say that committing not-compilable code is no problem in local and feature branches. Why? What is the value of a broken commit?

Some of the highly voted comments say that on a local brach one can do whatever one wants. However, I am not interested in the technical side of the question. Rather I would like to learn the best practices - the habits that people who have worked many years in the industry have found most productive.

I am amazed at the vast amount of great answers! They lead me to the conclusion that I am not adept enough at using branches to organize my code.


答: You can use a sequence object and get the next value in your GenerateId method. Using a DB sequence means you don't have to use the Max of identity or using interlocked.increment which will not work in a load balanced multi-server scenario. SQL Server 2012 and Oracle support sequences.</p>

Title: Auto - incremental ID in Domain Object

Body:
I read a lot about auto-incremental id (guid, interlocked.increment, ObjectIdGenerator...) but don't find nothing for my situation.

In my domain model user ask to have an automatic progressive numeric Id for each Activity they create.

Since it's a user request I want to put it in my domain model, but the mode I usually do it in older application without good architecture ) is accessing database, retrieve the max and add 1; so I can't do it in my object since domain layer must not be aware of db.

Don't like db identity for lack of control (sometimes db administrator have to change the id for user error on creation of activity).

interlocked.increment look fine but my application is installed on every user machine so I can't use it

Since it must be intelligible and progressive I can't use guid

I find a good idea in Lev Gorodinski article about Service Domain in Domain-Driven-Design: define the interface of a GenerateActivityId in domain layer as a Domain Service, but I don't find a way to make a good implementation of it.

Any suggestion?

EDIT:
Lev Gorodinski idea:

```<code>public class Activity {
  public int Id {get; private set;}
  public string Description {get;set;}

  public Activity (string description){
    this.Description = description
    this.Id = generator.GenerateId()
  }
}

public interface IIdGenerator{
  int GenerateId()
}
</code>```

but i don't see where "generator" is defined and don't found IIdGenerator implementation: where should i put the implementation?
In ActivityRepository? If yes i can omit IIdGenerator for the IActiviryRepositoryInteface ?


答:
So, you want to build a form containing 10 000 mobile numbers, and submit it to an SMS service. The first questions you may ask yourself:

Would the SMS service accept so many numbers?

Isn't there a way to do the same task in steps, using only a subset of mobile numbers at each step?

Does it really make sense to generate the form, display it to the person behind a browser, and let this person submit it, given all the constraints?

If you consider just the last question, the answer would probably be negative. Displaying such form:

Is a disaster from the point of view of the privacy of your customers (unless the mobile numbers are not the numbers your customers gave you, and you're just a spammer). Why would you ever send to anyone an HTML code containing every number of every person who trusted you, ignoring how do you care protecting sensitive data?

It simply doesn't make sense to flush all this data to the client and let the client flush it somewhere else. Why not sending it directly to the final destination? Don't waste everyone's' bandwidth without need.

Browsers will uselessly suffer from such large amount of data on some low-end machines. You're wasting your servers' processor power, you're wasting clients' processor power, and you increase the risk of something going wrong. Like the client who submits the form once, waiting for a while, and, thinking that it wasn't submitted, resubmits it.

The SMS service probably uses an API key. Does that mean that you're publicly showing the key as well? Why?

What about input validation? Since you don't do any, it means that anyone may send anything to all of your customers' mobile phones. What a lucky day for a hacker. And it becomes even better since you let everyone see the list of mobile phones and the API key.

What you can do instead is to show to the user a simple, basic form with the text area itself to type the message (or any other form from which the message will be generated). When submitted, you validate the input, and, if correct, make one or several HTTP requests to the SMS service yourself, from the server. If SMS service is able to handle lots of mobile numbers at once, you'll still have your select MobileNumber from Customer. If not, MySQL limit clause can be used to paginate data.

See, no disclosure of sensitive data, no security issues, no wasted network bandwidth, and reduced impact on the CPU.

Title: What's best practice for a SELECT * FROM SQL in PHP?

Body:
I need to make a "SELECT * FROM" Sql from PHP, that now returns about 10.000 records, that I insert in an Array and re-utilize in a page to show results in a table.

I need to have all that elements also in a hidden input fields, to connect via API to a SMS service to send SMS

```<code><input type="hidden" id="destinatariSMS" name="destinatariSMS" value="<?php echo htmlentities(serialize($destinatariSMS)); ?>" />
</code>```

Obviously, with 10k elements loading of page is about 10-15 seconds (in a VPS with 2GB ram).

I'm worrying because in about two months element will be 12-13k, about 1k elements at the month.

I cannot paginate elements because I need all together in that input...

In your opinion, what's best practice to no "destroy" VPS or browser?

Thank you very much


问:
Planning relational database - one or two tables?
I'm currently planning the database structure of a used car's advertisements site. Each advert contains information about a vehicle, and a vehicle can be advertised multiple times over its lifespan (granted, quite unlikely). I'm unsure which approach to take - a single table, or two separate relational tables, each has their pros and cons.

Schema 1

```<code>Adverts Table:
-------------------
id            int
make          varchar(255),
model         varchar(255),
year          int,
transmission  varchar(255),
fuel_type     varchar(255),
body_type     varchar(255),
engine_size   int,
colour        varchar(255),
doors         int,
location      varchar(255),
price         int,
owners        int,
mileage       int,
description   longtext
</code>```

Schema 2

```<code>Adverts Table
-------------------
id            int
location      varchar(255),
price         int,
owners        int,
mileage       int,
description   longtext
vehicle_id    int

Vehicles Table
-------------------
id            int
make          varchar(255),
model         varchar(255),
year          int,
transmission  varchar(255),
fuel_type     varchar(255),
body_type     varchar(255),
engine_size   int,
colour        varchar(255),
doors         int
</code>```

Personally, I'm thinking taking the second approach will benefit in the future, but it's proving tricky to work with. I'm using Laravel, a PHP framework. Because most of the "search" options are applied to the vehicle (parent), rather than the advert (child), a lot more code is required, which is starting to seem counter-intuitive. Schema 1 is far simpler to work.

Am I missing any extensive benefits of going with schema 2? In a nutshell, the first approach requires much less code, but isn't relational. The second approach is relational, but it's requiring far more code (and time), reducing the brevity of my adverts controller in particular, which is actually querying the vehicle's attributes more than the advert's. It's also making "sorting" quite tricky, as user's can sort by "make", "model", "location", "price", etc - attributes which jump between model.

答: You should use a RDBMS, no question. Flat-file causes redundant data, and that is never a good thing. Access, MySQL, My-DB or even one on Sun's DB's would be fine. I assume your using an Oracle based DB for your table. Access would be the best and cheapest for desk top, and a Java based db for web-based.</p>


答:
Yes it is OK and its something I do a lot.

The point of committing non-compilable code (in branches at least) is that sometimes your code is a work-in-progress, but that the work done so far is worth saving and/or sharing with others

My Practices are:

write tests first

wip (work-in-progress) commits are good

commit often (multiple within a day) and early (save 'working' steps)

push after every commit (in case your hard drives crashes /  the bus hits you).

always work in branches first

when possible only merge in working code to master

interactive rebase in git to squash wips before master merge

The main issue and perhaps the one you are touching on is when you have a feature that basically works and is sorely needed by the business (and hence needs to be in 'master') but has some failing tests.  One option here may be to do a pending test that lets you move forward for now.  However this is fraught with danger as the test may never be fixed and it may set a pattern in other areas of simply 'pending out' broken tests instead of fixing them.

Another option would be to temporarily use and deploy the branch.  This can help in certain situations but is generally not recommended and is not sustainable.

Perhaps the best option is to basically take a more professional approach to software development and really require working tests for any committed code.  This is frequently the 'hard' part of software development, not the coding that many people imagine.  A better approach will likely require better initial estimates, resource allocation, priority setting, etc. plus, during Agile development, allowing enough time and using enough discipline to fix any issues both at the time they occur and during grooming - pointing sessions.

Focus on what 'done' means - it means the code AND the tests are written, have been refactored and work.  If you hear comments such as "mostly done, just need to write / fix / refactor tests, then it is NOT done.  Saying a feature is done without it being technically complete is one of the most common mistakes of junior programmers.


答:
I think it can work really well. For example:</p>

```<code>// Command for retrying card entry with CVN.
public class RetryCardEntryWithCVNCommand { ... }

// Query for getting expired accounts
public class GetExpiredAccountsQuery { ... }

// Decorator for logging exception. Implies that it's an additional
//mechanism for logging exceptions.
public class LogExceptionToDbDecorator { ... }

// Factory for creating account filters
public class AccountFilterFactory { ... }
</code>```

Body:
I think it can work really well. For example:

// Command for retrying card entry with CVN.
public class RetryCardEntryWithCVNCommand { ... }

// Query for getting expired accounts
public class GetExpiredAccountsQuery { ... }

// Decorator for logging exception. Implies that it's an additional
//mechanism for logging exceptions.
public class LogExceptionToDbDecorator { ... }

// Factory for creating account filters
public class AccountFilterFactory { ... }


答:
Depends on the specific example. The Builder pattern is almost always best served by naming your class *Builder, while a Singleton doesn't usually need to be named as such.

If you don't put the pattern name in your class name, and maybe even if you do, you should generally put a comment in the class which explains that it implements a specific pattern.


答:
I disagree with this answer.

I have found that pair programming, whether the same level or different to be very useful for many reasons.

I have definitely seen it used to train less experienced programmers (to directly answer the question).

I think that it works because:

passing on program knowledge and what the various parts mean and do is often best done through period of pair programming.

there's nearly always differences in skill and experience levels between programmers due to experience, background, etc.  So 'at roughly the same level' rarely applies in practice in my experience.

good programmers know to both learn from others and also teach and pass on their own knowledge through pairing.

good pairing often results in BOTH people spending tie at the keyboard.  My favorite person to pair with and I used used to call these the 'ach, I'm stuck (person 1)' paired with 'here, gimme the keyboard let me try, I've got an idea (or the energy to continue!).'

even the best programmers need to learn the domain that they are working in and how it is represented by code and data and pair programming is often a great way to do that.

Body:
I am familiar with Agile and Pair Programming (http://en.wikipedia.org/wiki/Pair_programming).  I thought Pair Programming was used if there was a complex requirement i.e. two sets of eyes is better than one.

Is Pair Programming also used to train less experienced developers and bring them up to speed?

Also, how often is it used e.g. all the time i.e. the two developers will work together at one screen permanently or perhaps one day per week? I have read an Agile book, which talks about this concept but it does not mention frequency of use.


答:
I don't remember the chapter, but the author of the working with legacy code but I think the book suggest the following workflow :

make sure you have tests. If you can't test your code without
modifying it, only perform the most basic/easy modifications needed.

code a test for the new functionality

code the functionality directly where you want the work to happen and make the test pass

refactor to remove duplication and make the code SOLID compliant.

Even without test, I tend to follow a similar pattern: first get the thing to work in the simplest and easiest way, then immediately refactor until you are satisfied with the code organization. If you wait, you (or your colleague) will pay a higher price of trying to understand messy code.

The fact that you first solve the problem in the most simple and straightforward way helps you to avoid over-engineering the solution. Focusing first on correctness then on readability/architecture really helps you to be productive.

Title: Refactorable God v.s. too many classe

Body:
So I have this problem: in order to structure my code hierarchically, for every new tiny thing, I create a separate sub-folder, file, class ... and in it one 10-line function. It is an anti-pattern.

Lately I have been trying to err on the opposite side. That is, when I need something new, instead of dreaming up grand hierarchies, I just type the code somewhere inside the existing classes.

This is beginning to look like another anti-pattern, and I wander which is the lesser evil.

So the pattern is the following: write everything here and now, and, when the need arises, refactor the code out to a separate class. Kind of refactorable God.

Am I using this as an excuse to write God classes? Or is there a pattern/worklfow, similar to this one, that I can adopt? What are the indicators that things are going well/terrible?


问:
how to model a connection to a resource, with rudimentary event processing
For my simple MUD client I'm using Apache Telnet (no, not ssh).  A mud client is a strange beast:

Generally, a MUD client is a very basic telnet client that lacks VT100 terminal emulation and the capability to perform telnet negotiations.
      ...
      Standard features seen in most MUD clients include ANSI color support, aliases, triggers and scripting.
      - Wikipedia

I would like for a not-yet-written Controller to have a reference to TelnetConnection and just use it for a higher level of abstraction for I/O, but all attempts to prise this class apart fail for me.  TelnetConnection seems to take on responsibility for everything, and then some, and just keep growing.

```<code>package telnet;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Deque;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Logger;
import org.apache.commons.net.telnet.TelnetClient;
import player.GameAction;
import player.DataFromRegex;
import player.Regex;

public class TelnetConnection implements Observer {

    private static Logger log = Logger.getLogger(TelnetConnection.class.getName());
    private TelnetClient telnetClient = new TelnetClient();
    private InputOutput inputOutput = new InputOutput();
    private Regex regexParser = new Regex();
    private DataFromRegex data = null;
    private Logic logic = new Logic();

    public TelnetConnection() {
        init();
    }

    private void init() {
        try {
            int port = 3000;
            InetAddress host = InetAddress.getByName("rainmaker.wunderground.com");
            telnetClient.connect(host, port);
            inputOutput.readWriteParse(telnetClient.getInputStream(), telnetClient.getOutputStream());
        } catch (SocketException ex) {
        } catch (IOException ex) {
        }
        inputOutput.addObserver(this);
    }

    private void sendAction(GameAction action) throws IOException {
        log.info(action.toString());
        byte[] actionBytes = action.getAction().getBytes();
        OutputStream outputStream = telnetClient.getOutputStream();
        outputStream.write(actionBytes);
        outputStream.write(13);
        outputStream.write(10);
        outputStream.flush();
    }

    private void sendActions(Deque<GameAction> gameActions) {
        while (!gameActions.isEmpty()) {
            GameAction action = gameActions.remove();
            try {
                sendAction(action);
            } catch (IOException ex) {
            }
        }
    }

    @Override
    public void update(Observable o, Object arg) {
        String line = null;
        if (o instanceof InputOutput) {
            line = inputOutput.getLine();
            log.fine(line);
            data = regexParser.parse(line);
            Deque<GameAction> gameActions = logic.getActions(data);
            sendActions(gameActions);
        }
    }

    public static void main(String[] args) {
        new TelnetConnection();
    }

}
</code>```

Part of the difficulty lies within the InputOutput class, which is adapted from IOUtil from Apache.  (For some reason, I cannot include the link to to the Apache source code.)

Once I send the InputStream to InputOutput there needs to be callback using Observable to then send the String data for matching and searching?  And then get back what after matching and searching the text?

The trick being, in terms of I/O:

capture console input

print remote output from the MUD server to the console like regular telnet

some regex/etc on the remote output, concurrent with open, unterminated streams.

This last requirement seems to make an odd beast for which I cannot envision the flow of control and data.

答:
If you wanted to simplify the nitty gritty implementation details into a class called TelnetConnection, I definitely think that would be a wise idea, however it may be that you cannot do it with simply one class.  You may need to have a secondary class which deals with the asynchronous aspect of this.  Lets call this class TelnetObserver which implements Observer.

Now in this way, it is still asynchronous, which makes your life difficult, so lets make it synchronous.  Make TelnetObserver implement Future<String>.  The idea is that you call "get()" whenever you're ready for the next line of input (waiting until input is available if necessary).

Of course this doesn't happen on its own, we must make it synchronous by using an instance of CountDownLatch.  The purpose of CountDownLatch is to make a thread wait for an asynchronous job to finish within a certain timeframe.  I found an excellent example of this implementation here.

Once you have this, TelnetConnection will handle the connection logic.  From there, TelnetConnection could also handle the parsing of the individual lines, but I wouldn't recommend it.  I would create another class TelnetParser which does that for you, given the input from TelnetObserver.  The resulting Object would then be returned to any listeners for input.  Alternatively on output, you use the same TelnetParser to convert from an Object to a String which TelnetObserver could send.

The basic interface for TelnetParser would likely look something like this:

```<code>public class TelnetParser {
    public Object parseFromString(String) {
        ...
    }
    public String parseToString(Object) {
        ...
    }
}
</code>```

The end result is that you have a model object which you can call upon to receive input or to send output.  This returns control back to the caller, or in this case your class Controller!  I hope that helps.  Good luck in your endeavor!

Body:
If you wanted to simplify the nitty gritty implementation details into a class called TelnetConnection, I definitely think that would be a wise idea, however it may be that you cannot do it with simply one class.  You may need to have a secondary class which deals with the asynchronous aspect of this.  Lets call this class TelnetObserver which implements Observer.

Now in this way, it is still asynchronous, which makes your life difficult, so lets make it synchronous.  Make TelnetObserver implement Future<String>.  The idea is that you call "get()" whenever you're ready for the next line of input (waiting until input is available if necessary).

Of course this doesn't happen on its own, we must make it synchronous by using an instance of CountDownLatch.  The purpose of CountDownLatch is to make a thread wait for an asynchronous job to finish within a certain timeframe.  I found an excellent example of this implementation here.

Once you have this, TelnetConnection will handle the connection logic.  From there, TelnetConnection could also handle the parsing of the individual lines, but I wouldn't recommend it.  I would create another class TelnetParser which does that for you, given the input from TelnetObserver.  The resulting Object would then be returned to any listeners for input.  Alternatively on output, you use the same TelnetParser to convert from an Object to a String which TelnetObserver could send.

The basic interface for TelnetParser would likely look something like this:

public class TelnetParser {
    public Object parseFromString(String) {
        ...
    }
    public String parseToString(Object) {
        ...
    }
}

The end result is that you have a model object which you can call upon to receive input or to send output.  This returns control back to the caller, or in this case your class Controller!  I hope that helps.  Good luck in your endeavor!


问:
Should user documentation include screenshots?
This question focuses on user documentation, not on code documentation.

I just finished my software project, and the people I work for are expecting me to write user documentation, describing everything the software does.

All the documentation they had until now (about the rest of the software they use) is full of screenshots, and sometimes barely contains any text. I think it's awful. I've been struggling for hours to understand how screenshots were connected, and most of the time I had to ask for help from someone else.

I wrote a Java desktop application, and its appearance is likely to depend on the current Windows theme and Java update. I don't think screenshots can form reliable, definitive reference.

Taking hundreds of screenshots and annotating them will take forever, and I don't believe it will help more than accurate, plain text documentation.

How should I approach putting the user documentation together?  What guidelines should I follow regarding the use of screenshots versus explaining in text with user documentation?

答:
Screenshots are an important aspect of the user guidance. However, they also need to be accompanied by clear and precise instructions. For example, having a screenshot showing the screen, a red arrow pointing to a button and the text reading 'Now that you have entered the filename, Click the Next button.' is much clearer than either the text or the screenshot alone.

Doing good click by click guides is time consuming, but worth it when it comes to supporting end users (even technical ones)


问:
Switch Parent Children relationship in C#
Using C# and WPF I have a situation where my data is organized hierarchically.
I am using a treeview to represent this :

Group_01

Object_01

Material_01

Texture

Material_02

Texture_02

Group_02

Object_02

Material_03

Texture_03

I would like to be able to switch the order of the hierarchy, for example be able to create the data starting from the Materials and know all the objects that use that particular material

Material_02

Object_01

Group_01

Object_02

Group_02

What is it the recommended data structure to organize the data? And how I could switch easily between any of these visualizations?

答:
I would focus on what each object is without focussing on how it will be displayed. What is a node? Looking at your treeview, it looks like a node is an item with various properties - would a filtering system based on numerous categories perhaps work better than a treeview?

Then a user could say I want "material x" with "texture y" but only in "group b" without needing to navigate through a hierachy?

It's hard to give you concrete advice without knowing what a node actually represents. Also, might be worth looking at ux.stackexchange.com for front end visualisation ideas.

OwnerDisplayName: Domenico Alessi


问:
Gerrit, git and reviewing whole branch
I'm now learning Gerrit (which is the first code review tool I use). Gerrit requires a reviewed change to consist of a single commit. My feature branch has about 10 commits.

The gerrit-prefered way is to squash those 10 commits into a single one. However this way if the commit will be merged into the target branch, the internal history of that feature branch will be lost. For example, I won't be able to use git-bisect to bisect into those commits. Am I right?

I am a little bit worried about this state of things. What is the rationale for this choice? Is there any way of doing this in Gerrit without losing history?

答:
What about Continues Integration? you made 10 commits on a feature branch and it will be "published" at once - that would be a huge impact on others who should review those commits/changes.

However it is worth to push 10 commits, if the commits contain separate code modifications. But in case the commits contain continuous modifications on a single feature (so most of the commits just corrections or middle status of an ongoing implementation of a function definition) then better to squash them into a single commit.

In general think with the reviewers mind - what is the size of a code modification which can be reviewed easily.

Note: Gerrit is not just for reviewing the code - changes should trigger several acceptance tests. (unit test, smoke test) So if you have those, then it is harder to publish faulty codes. So from this perspective a commit should contain such changes which is worth to test.

So Gerrit force you not to commit too small and too big changes. (you will use --amend not just to correct a change already pushed to Gerrit, instead of correcting a commit you want push for review)

Title: Gerrit, git and reviewing whole branch


问:
Using gerrit (or similar tool) on a team where multiple devs work on a single feature
We have a team of roughly ~8 devs who regularly work on the same feature over the course of a 3 week sprint. It isn't quite pair programming, but in our current workflow devs regularly push up incomplete code for a colleague to complete. This worked fine before we introduced Gerrit, but now our commits need to represent chunks of test-passing, complete, logical functionality, and so the model breaks.

My only idea is to have everybody push up to a separate, untracked branch up until the functionality is ready for review, then squash everything into commits that make sense and push up. Is there another Gerrit-ized workflow that could work?

I know this is a widely discussed topic on Google Groups, and that there has recently been some discussion of Gerrit topic reviews, but I wanted to see if there is anybody out there using Gerrit in this way, and what the suggested workflow would be.

答:
If you want to share a change over Gerrit without publishing it, then the following workflow might work:

(no1) push the change to refs/for/*

(no2) get the change by checking it out (command can be found at the patchet panel in Gerrit)

(no2) make code modification, amend it and push it back

After pushing any changes to Gerrit, the local branch can be reset, since every change can be checked out from Gerrit. Also consider keeping the local branch updated by resetting it:

git fetch

git reset --hard <remote_branch>

In this way merge commits will be eliminated easily (merge commits should not be pushed).

If the team is working on the same feature then the commit should be rebased more often before push. (Gerrit abandon the push if the commit needs rebase) use git rebase -p <remote_branch>'to resolve it.

This workflow has only one issue - each push will trigger several jenkins jobs (hope). I think by now it is hard to tell jenkins not to run tests for a particular change. Gerrit trigger plugin only consider files and branches.

If a trigger could examine the commit message or the topic name first, then it would be easy to force Jenkins not to run by adding tag to the commit message like [WIP]. If you agree with that please vote for the feature request: https://issues.jenkins-ci.org/browse/JENKINS-19019 and check this commit message template suggestion: https://softwareengineering.stackexchange.com/a/203484/91685


问:
MVVM application architecture, where to put dependency injection configuration class, BusinessLayer and Common interfaces?
Planning my architecture for an MVVM application I come to this:

MyApp.UI

View

MyApp.BusinessLayer

ViewModel

MyApp.DataAccessLayer

RepositoryImplEF

MyApp.DomainLayer

DomainObject

RepositoryInterface

MyApp.Common

Logging

Security

Utility (contains some reflection method used by many levels)

CustomException

MyApp.UnitTest

I was inspired by Domain-driven-desing, test-driven-development and onion architecture but not sure to have done all well.

I am not sure of a couple of things:

where to put dependency injection configuration class? In the common project?

where to put BusinessLayer interfaces? in Domain layer?

where to put Common interfaces? in Domain layer? But Common in referenced from domain (for some reflection utilities and for DI if the response to 1. is yes) and circular reference isn't good

答:
Common is your best bet as the information is independent of the responsibilities the MVVM layers represent.

Yes, domain layer / ViewModel.  That area owns the business logic, so it ought to have the interfaces.

Common interfaces for what?  Interfaces belong to the layer that owns the responsibility for the action represented by the classes.

The other layers will reference the common layer.  The common layer shouldn't need to reference anything within the other layers (otherwise, it wouldn't be common).  Think through what the responsibilities are for each component, and you should be able to more easily identify where things belong.

If the challenge is with your DI configuration class(es), then you made need to separate them out.  A master configuration class would live within the common layer.  Layer specific configuration may need to be created at each layer.


答:
To be able to do this, you will need to modify your data type classes so that the Material class has a collection of type Object and your Object class (which is a really bad name if this is a custom class) should have a collection of type Group. The Object class will also need a collection of type Material and the Material class will also need a collection of type Texture, etc.

Then you would need to design a function (with loads of Linq or loops) that reverses the hierarchy. The easiest way to do this is if you add properties into your data type classes that relate to each other. Therefore, they should all have some kind of Id property and then the relevant child classes would need to have ParentId properties.

With this setup, you can easily build your hierarchies:

```<code>Material material = new Material();
material.Id = theIdValue;
material.Textures = new ObservableCollection(allTextTures.Where(t => t.ParentId ==
material.Id).ToList());
</code>```

Title: Switch Parent Children relationship in C#

Body:
Using C# and WPF I have a situation where my data is organized hierarchically.
I am using a treeview to represent this :

Group_01

Object_01

Material_01

Texture

Material_02

Texture_02

Group_02

Object_02

Material_03

Texture_03

I would like to be able to switch the order of the hierarchy, for example be able to create the data starting from the Materials and know all the objects that use that particular material

Material_02

Object_01

Group_01

Object_02

Group_02

What is it the recommended data structure to organize the data? And how I could switch easily between any of these visualizations?

Body:
To be able to do this, you will need to modify your data type classes so that the Material class has a collection of type Object and your Object class (which is a really bad name if this is a custom class) should have a collection of type Group. The Object class will also need a collection of type Material and the Material class will also need a collection of type Texture, etc.

Then you would need to design a function (with loads of Linq or loops) that reverses the hierarchy. The easiest way to do this is if you add properties into your data type classes that relate to each other. Therefore, they should all have some kind of Id property and then the relevant child classes would need to have ParentId properties.

With this setup, you can easily build your hierarchies:

Material material = new Material();
material.Id = theIdValue;
material.Textures = new ObservableCollection(allTextTures.Where(t => t.ParentId ==
material.Id).ToList());

OwnerDisplayName: Sheridan


答:
Since here you have many to many relationships i.e group can have object list which inturn can have material list and the list of groups it belongs to... similarly material can have object list.. so your models should be like below:

```<code>    public class Group
    {
        ObservableCollection<Object> Objects { get; set; }
    }

    public class Object
    {
        ObservableCollection<Material> Materials { get; set; }
        ObservableCollection<Group> Groups { get; set; }
    }

    public class Material
    {
        ObservableCollection<Object> Objects { get; set; }
    }
</code>```

Now in order to show the hierarchical data you can use the TreeView to represent this and can define the HierarchicalDataTemplates depending on your number of visualization e.g for GroupHierarchy and MateraialHierarchy you can have templates like:

Group Hierarchy:

```<code><HierarchicalDataTemplate x:Key="GroupTemplate" ItemsSource="{Binding Objects}">
            <StackPanel>
                <TextBlock Text="{Binding GroupName}"/>
            </StackPanel>
            <HierarchicalDataTemplate.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Materials}">
                    <TextBlock Text="{Binding ObjectName}"/>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding MaterialName}"/>
                        </DataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
</code>```

Material hierarchy:

```<code><HierarchicalDataTemplate x:Key="MaterialTemplate" ItemsSource="{Binding Objects}">
            <StackPanel>
                <TextBlock Text="{Binding MaterialName}"/>
            </StackPanel>
            <HierarchicalDataTemplate.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Groups}">
                    <TextBlock Text="{Binding ObjectName}"/>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding GroupName}"/>
                        </DataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
</code>```

Now you can use ItemTemplateSelector to return the correct template for your TreeView when you switch the TreeView's ItemsSource

Body:
Since here you have many to many relationships i.e group can have object list which inturn can have material list and the list of groups it belongs to... similarly material can have object list.. so your models should be like below:

    public class Group
    {
        ObservableCollection<Object> Objects { get; set; }
    }

    public class Object
    {
        ObservableCollection<Material> Materials { get; set; }
        ObservableCollection<Group> Groups { get; set; }
    }

    public class Material
    {
        ObservableCollection<Object> Objects { get; set; }
    }

Now in order to show the hierarchical data you can use the TreeView to represent this and can define the HierarchicalDataTemplates depending on your number of visualization e.g for GroupHierarchy and MateraialHierarchy you can have templates like:

Group Hierarchy:

<HierarchicalDataTemplate x:Key="GroupTemplate" ItemsSource="{Binding Objects}">
            <StackPanel>
                <TextBlock Text="{Binding GroupName}"/>
            </StackPanel>
            <HierarchicalDataTemplate.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Materials}">
                    <TextBlock Text="{Binding ObjectName}"/>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding MaterialName}"/>
                        </DataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>

Material hierarchy:

<HierarchicalDataTemplate x:Key="MaterialTemplate" ItemsSource="{Binding Objects}">
            <StackPanel>
                <TextBlock Text="{Binding MaterialName}"/>
            </StackPanel>
            <HierarchicalDataTemplate.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Groups}">
                    <TextBlock Text="{Binding ObjectName}"/>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding GroupName}"/>
                        </DataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>

Now you can use ItemTemplateSelector to return the correct template for your TreeView when you switch the TreeView's ItemsSource

OwnerDisplayName: nit


问:
How to write "good" unit tests?
Triggered by this thread, I (again) am thinking about finally using unit tests in my projects. A few posters there say something like "Tests are cool, if they are good tests". My question now: What are "good" tests?

In my applications, the main part often is some kind of numerical analysis, depending on large amounts of observed data, and resulting in a fit function that can be used to model this data. I found it especially hard to construct tests for these methods, since the number of possible inputs and results are too large to just test every case, and the methods themselves are often quite longish and can not be easily be refactored without sacrificing performance. I am especially interested in "good" tests for this kind of method.

答:
The Art of Unit Testing has the following to say about unit tests:

A unit test should have the following
  properties:

It should be automated and repeatable.

It should be easy to implement.

Once it’s written, it should remain for future use.

Anyone should be able to run it.

It should run at the push of a button.

It should run quickly.

and then later adds it should be fully automated, trustworthy, readable, and maintainable.

I would strongly recommend reading this book if you haven't already.

In my opinion, all these are very important, but the last three (trustworthy, readable, and maintainable) especially, as if your tests have these three properties then your code usually has them as well.

Title: How to write "good" unit tests?


问:
How to Track File Uploads and Return Upload Status with REST?
The users for our software will want to upload potentially large amounts of files in bulk to our servers. It is then desired that we display the upload status any time the user views the upload screen. This doesn't have to be any more fancy than a progress bar with a percent status.

My question is, how can I keep track of the uploaded files and return them at any possible time with a simple GET request at '/upload/status'.

A first solutions aims to keep track of the uploads requested and those processed in a database table. That way, it is as easy as querying the database any time the user wants to see his upload status.

Is this a viable- and correct- solution to handling the state of file uploads in a REST service? Should I be looking for solutions elsewhere?

答:
The approach you have described will work, as long as you have a mechanism for identifying who the user is making the request.  e.g. /upload/status?uid=32343

Where this gets interesting is in how you return the information back to the user.  You can make it a single hit, as you described.  There are also possibilities based on redirect / refresh headers in the response as well.

However also consider using the mutli-part response.  You receive the HTTP request and issue a multi-part response and send the first response immediately back to the client.  you then maintain the connection and send additional partial responses back to the client every few seconds. you continue doing this until either the client closes the connection, or you identify that all the files have uploaded, at which point you send the last response finishing the multi-response HTTP response message to the client.


答:
One of the branching philosophies (section Developing Branching Strategy and Codeline Policy in Advanced SCM Branching Strategies - also read Perforce Best practices, its a pdf but goes into some other details) is that you branch on incompatabile policy.

A codeline policy
   specifies the fair use
  and permissible check-ins for the codeline,
  and is the essential user’s manual for
  codeline SCM. For example, the policy of
  a development codeline should state that
  it isn’t for release; likewise, the policy of a
  release codeline should limit changes to
  approved bug fixes. The
  policy can also describe
  how to document changes
  being checked in, what
  review is needed, what
  testing is required, and
  the expectations of
  codeline stability after
  check-ins. A policy is a
  critical component for a
  documented, enforceable
  software development
  process, and a codeline
  without a policy, from an
  SCM point of view, is out of control.

(from Perforce Best Practices)

Say you have the branches 'release' (or 'master') from which a release is built and 'trunk' (or 'dev') where developers check in working code.  These are the policies of the branches.  Noting the 'working code' is part of the 'dev' branch policy, one should never commit broken code to the dev branch.  Often there are things such as CI servers hooked up to these branches and checking in broken code into dev could mess up everyone's branch and break the build.

However, there are times when it is appropriate to check in partial code that doesn't work.  In these instances, one should branch - an incompatible policy with trunk.  In this new branch, one can decide the policy ('broken code is ok') and then commit code to it.

There is one simple rule to determine if a
  codeline should be branched: it should be
  branched when its users need different
  check-in policies. For example, a product
  release group may need a check-in policy
  that enforces rigorous testing, whereas a
  development team may need a policy that
  allows frequent check-ins of partially tested
  changes. This policy divergence calls for a
  codeline branch. When one development
  group doesn’t wish to see another

(from Perforce Best Practices)

Realize that this is coming from a central server based SCM with a strong corporate mindset. The core idea is still good.  These are often thought of implicitly - you don't check in untested dev code into the release branch.  Thats a policy.

So branch, say that this branch can have broken code and commit away.


答:
We have a fairly large MVVM application that I helped design. We have a single project known as the Host. this will be the main executable for the entire applicaton and contains the Bootstrapper for the Dependency Injection.

MyApp.Host

Bootstrapping

Configure container for all dependencies

Runs the main application

Also we had separate class libraries for all our interfaces so we would have:

MyApp.ViewModels.Interfaces

This will allow your application to have no circular references as it will only be the Host app that needs to know about the relationship between your viewmodels and the interfaces.

Title: MVVM application architecture, where to put dependency injection configuration class, BusinessLayer and Common interfaces?

Body:
Planning my architecture for an MVVM application I come to this:

MyApp.UI

View

MyApp.BusinessLayer

ViewModel

MyApp.DataAccessLayer

RepositoryImplEF

MyApp.DomainLayer

DomainObject

RepositoryInterface

MyApp.Common

Logging

Security

Utility (contains some reflection method used by many levels)

CustomException

MyApp.UnitTest

I was inspired by Domain-driven-desing, test-driven-development and onion architecture but not sure to have done all well.

I am not sure of a couple of things:

where to put dependency injection configuration class? In the common project?

where to put BusinessLayer interfaces? in Domain layer?

where to put Common interfaces? in Domain layer? But Common in referenced from domain (for some reflection utilities and for DI if the response to 1. is yes) and circular reference isn't good


答:
I don't think that it's OK to commit broken code.

What happens if

An urgent hot fix is required. Code base is in a broken state. You are forced to roll back, fix and deploy.

Somebody else starts working in the same branch not knowing that you have committed broken code. They might be chasing a 'red herring' thinking that their changes have broken something.

You decide to leave the company, go on holiday or can't come to work for any reason. Your colleagues will have to dig deep to find what's broken and why it has been committed in a broken state.

Somebody deploys your 'broken code'? This can be a 'game over' if you are working with personal data or on a payment provider.

Reply to @WarrenT

I agree with you that in an ideal world where everybody works in a feature branch, committing non working code might work. I have worked on large projects and even then there were cases where multiple people had to work in a single feature branch. I have also seen people commit 'not working' code to main branch because release was weeks away and they planned on fixing it next day. All these things are candidates for a disaster and I strongly believe that they should be avoided at all costs.


答:
Think about it this way.  As a developer one of the most disruptive things you an do is to stop other developers on your team from working on their tasks.

The philosophy of only committing working code comes from development teams working on the same single trunk in the repository. It may seem madness now, but 10 years ago, this was the normal way of working. A branch would appear when you wanted to create a stable release, but the thought of a developer working in a branch to implement a new feature was almost unheard of.

If your environment means that your commits do not immediately affect other developers, then commit often. it gives you more security in your code, making it easier to roll back a code mistake and many source control systems give you some code protection to committed code (although not all).

Now, making sure your merges with branches shared with other developers do work, and that any code you promote to this level compile, pass all unit tests and other team based sanity checks...  that's kind of essential if you don't want to keep buying the beer in the pub...


问:
Approach to use for user email address change in application?
As the title says, if the user wants change their email address in the application, in terms of programming, what approach (process) to use? Where do you store the new email address until the user will confirms it?</p>

答:
I think the best approach would be to create a new table called email_resets, where you will have a few fields:

```<code>id | new_email | old_email | hash | date_added
</code>```

Then send the user a reset email link on the old email address. Inform the user that his email will be changed to newemail@something.com, and then when he clicks the link, check the hash, email and the time when the request was made, then you can update your main user table, and delete the reset email entry. (you can replace old_email with user_id, and maybe remove the id field completely)

The advantages would be the following:

no alterations to the main table (neither database structure, nor the values stored)

you have full control over the time limit (ie reset email link will only be available for X hours), and you can make a cron job to clean up the table.

little extra memory needed - if the email reset requests are cleaned up every few hours/days

PS: A randomly generated hash is also needed (this is the reason behind the hash field), besides the expire time to make sure these requests cannot be forged.

Body:
I think the best approach would be to create a new table called email_resets, where you will have a few fields:

id | new_email | old_email | hash | date_added

Then send the user a reset email link on the old email address. Inform the user that his email will be changed to newemail@something.com, and then when he clicks the link, check the hash, email and the time when the request was made, then you can update your main user table, and delete the reset email entry. (you can replace old_email with user_id, and maybe remove the id field completely)

The advantages would be the following:

no alterations to the main table (neither database structure, nor the values stored)

you have full control over the time limit (ie reset email link will only be available for X hours), and you can make a cron job to clean up the table.

little extra memory needed - if the email reset requests are cleaned up every few hours/days

PS: A randomly generated hash is also needed (this is the reason behind the hash field), besides the expire time to make sure these requests cannot be forged.


问:
MVC Models instantiation
Where should the Models be instatiated in a MVC arhitecture? I understand the preferred way would be outside controllers, in a bootstrap file and injected using a Dependecy Injection Container. But most of the models I'm working with depend on run time parameters.</p>

```<code>//PHP Example
class UserController {
   protected $objUser;
   protected $objDictionary;

   public function Show() {
       $objUserMapper = new UserMapper();
       $this->objUser = $objUserMapper->FindById($_GET['id']);
       $this->objDictionary = new Dictionary($this->objUser->Language);
   }
}
</code>```

答:
View models are generally instantiated in controllers.

Domain models shouldn't be used in controllers unless project is really small.

Inversion of control containers are normally used to inject services that talk to the business layer. This becomes useful when you write your application using TDD as you would normally mock calls to your services.

General flow is:

Retrieve data from service in form of DTO or domain model

Automap from DTO or domain model to your view model (this can be done in controllers' actions)

Return view with a view model

Title: MVC Models instantiation


问:
Is it ever OK to commit non-working code?

Is it good idea to require to commit only working code?

This commit doesn't need to leave the repository in a working state as:

... we are in early design stages, the code is not yet stable.

... you are the sole developer on the project. You know why things aren't working. Furthermore, you are not stopping anyone's work by committing broken code.

... the code currently doesn't work. We are going to make a big change to it. Let's commit, in order to have a point to revert to if things get ugly.

... the chain is long, no trouble if broken code exists in the local branch. I.e.

local files

staging area

commits in local branch

commits in remote personal feature branch

merge with remote develop branch

merge with remote master branch

merge with remote release branch

... commit early,commit often.

So in the above-linked question, the majority of answers say that committing not-compilable code is no problem in local and feature branches. Why? What is the value of a broken commit?

Some of the highly voted comments say that on a local brach one can do whatever one wants. However, I am not interested in the technical side of the question. Rather I would like to learn the best practices - the habits that people who have worked many years in the industry have found most productive.

I am amazed at the vast amount of great answers! They lead me to the conclusion that I am not adept enough at using branches to organize my code.

答:
Committing some broken code-base is okay as long as it is local.

Why?

It is essential to use committing as a save point in your development

It shows you a pattern of thought used while developing the product.

It does not break collaboration.

However, when there is a team of programmers, the philosophy of the programming house is paramount and supersedes individual commit behaviours. Some programming houses decide to log all progress while others decide to only commit code that solves a feature. In this case, the value (cost, from a software management point of view) of a broken commit is dire:

time used to further features is now spent fixing errors...

the development cut is not met...

product is not shipped on time

Other points can be added to these three cascading their effects exponentially into a company meltdown ...of course, this has to be an effect of chronic habitual committing of bad code.


答:
In the MVC pattern, the Controller instantiates both Models and Views.

It can do so directly or via other means, typically some form of factory or a IoC container. In any case the "new instance" of the Model is held by the controller which passes it to the View.

Also, the view may have its own underlying class (this depends on which MVC framework you are using) and may not receive the model directly - it's OK if the controller translates the "Model language" (business concerns) to the "View language" (presentation concerns).

Title: MVC Models instantiation

Body:
Where should the Models be instatiated in a MVC arhitecture? I understand the preferred way would be outside controllers, in a bootstrap file and injected using a Dependecy Injection Container. But most of the models I'm working with depend on run time parameters.</p>

```<code>//PHP Example
class UserController {
   protected $objUser;
   protected $objDictionary;

   public function Show() {
       $objUserMapper = new UserMapper();
       $this->objUser = $objUserMapper->FindById($_GET['id']);
       $this->objDictionary = new Dictionary($this->objUser->Language);
   }
}
</code>```


答:
This is where UX is needed, I believe.

Understand your data and their use cases. You may not have to show all 10000 at once. There may be some grouping that can chunkify this data to speedup page loads. There can be other information you can get from the requester to understand which category he requests. Loading all 10000 at once should not be an option. Look to redesigning the user experience.


问:
TCP and UDP basics: connecting to a website
I am just learning computer networks so please forgive me if this question is naive. I know the TCP protocol binds itself to a port till the transfer of messages is over (port 80) and UDP is best effort (ie no binding). My question is if I try and access two websites at the same time (multiple tabs on my browser), assuming both websites are web servers, my questions are

Does my computer communicate with one webservice (website) first and then communicate with the other (serially). Also if this is the case is the time difference so small that I feel it loads simultaneously?

Suppose I have my own web server (tomcat) running on port 80, how can I communicate with other websites if it happens on the same port?

Do websites decide which protocol to use TCP or UDP?

答:
Each TCP connection has 4 values to identify it: IP1 (own IP address), port1 (the port on my end), IP2 (the other computer's address), port2 (the port on the other end).

As soon as any of these is different you are talking about a different connection. This creates a theoretical 4 billion TCP connections between any 2 computers. keeping this in mind:

computers can have multiple connections active at the time (most of the time they'll choose a different local port from the 65k available),

you can even connect twice to the same server on the same port as long a the locally chosen port is different

same as above, there is enough leeway in the local port range to open multiple connections, (though no-one will ever use 80 as the local port for outgoing connections)

http (like 90% of all internet traffic) is over TCP,

UDP is only used for specialist applications where you are allowed to lose some data


答:
Here are some basics for you to guide your learning.

Connections to Web servers are always TCP connections, and the port number is the port number on the server receiving the connection, not the client making the connection.

So:

It is common for web browsers to make multiple connections to web servers at the same time. It's considered good manners to not make more than 2 connections to the same server from the same client at any one time, but busy web servers will have hundreds (and even thousands) of simultaneous client connections.

The local port used to connect to a remote server is generated randomly by your OS. It is not the same port number as the remote port you are connecting to, so there are no problems connecting to multiple web servers at the same time as running a web server locally.

The protocol spoken by web servers are defined HTTP/1.0 and HTTP/1.1, and are specifically TCP connections.

Title: TCP and UDP basics: connecting to a website

Body:
I am just learning computer networks so please forgive me if this question is naive. I know the TCP protocol binds itself to a port till the transfer of messages is over (port 80) and UDP is best effort (ie no binding). My question is if I try and access two websites at the same time (multiple tabs on my browser), assuming both websites are web servers, my questions are

Does my computer communicate with one webservice (website) first and then communicate with the other (serially). Also if this is the case is the time difference so small that I feel it loads simultaneously?

Suppose I have my own web server (tomcat) running on port 80, how can I communicate with other websites if it happens on the same port?

Do websites decide which protocol to use TCP or UDP?