问:
How do I pass a variable's value from one class into another? (C++)
I have a class ("Class A", we'll call it) which calculates the value of a private variable (which we can call numLoaves) with a public function. I need to use the value of numLoaves in a public function in Class B.

What is the best and most efficient way to pass in this value? I'm new to programming and have been looking for a solution for hours with no luck. Note: The function in Class B is void and must be this way. I can't use global variables or objects, pointers, friend functions or friend classes. The variable must be private.

Thank you!

答:
In some way this will boil down to class A setting the value in class B.

Class B should have it's own private copy of numLoaves and use a setter to set it.

```<code>void ClassB::setNumLoaves(const NumLoaves_t& numLoaves)
{
    _numLoaves = numLoaves;
}
</code>```

Class A should have a method which will update class B.

```<code>void ClassA::updateClassB(ClassB& classB)
{
    classB.setNumLoaves(_numLoaves);
}
</code>```

Finally, in whatever way class A and class B are associated, class A updates class B.

```<code>classA.updateClassB(classB);
</code>```

Body:
In some way this will boil down to class A setting the value in class B.

Class B should have it's own private copy of numLoaves and use a setter to set it.

void ClassB::setNumLoaves(const NumLoaves_t& numLoaves)
{
    _numLoaves = numLoaves;
}

Class A should have a method which will update class B.

void ClassA::updateClassB(ClassB& classB)
{
    classB.setNumLoaves(_numLoaves);
}

Finally, in whatever way class A and class B are associated, class A updates class B.

classA.updateClassB(classB);


答:
Look at it this way. You have two objects and you need a kind of medium for them to communicate with each other.A can go and ask B what he ate for breakfast.

A can do this by saying B.WhatDidYouEatForBreakfast() or shorter B.Breakfast(). The nice thing about it is that it doesn't need to go and check it's plates and dumpster (those are private) but the question is allowed (it's public). B, on the other hand, can say what he wants (will probably say fruits and vegetables, when in fact was chips and cola), but it better be the info that you're looking for (makes sure of this in the method body).

So, basically, you'll just have to have a public method in one of the classes with a return type of the private variable. This method will return the value of the private variable. Anybody can now call that object and find out what is going on.

ContentLicense: CC BY-SA 3.0

Title: How do I pass a variable's value from one class into another? (C++)

Body:
I have a class ("Class A", we'll call it) which calculates the value of a private variable (which we can call numLoaves) with a public function. I need to use the value of numLoaves in a public function in Class B.

What is the best and most efficient way to pass in this value? I'm new to programming and have been looking for a solution for hours with no luck. Note: The function in Class B is void and must be this way. I can't use global variables or objects, pointers, friend functions or friend classes. The variable must be private.

Thank you!


问:
When subclassing is it better to "Copy Paste, then Refactor", or "Refactor, then Implement"
I currently have a class Foo,
i've decided I need a second type of Foo where I want to test out a significantly different implementation. It will no doubt share some functionality with Foo so I'll need to create a Abstract Class parent for both of them.

At the end of the process I want to have:

AbstractFoo: an abstract class

FooBoo: functionaly identical to the original Foo

FooBar: the new subclass of AbstractFoo I've created.

There are two ways I could go about this:

Copy Paste, then Refactor

Create a copy of Foo, and name it FooBar and rename Foo to FooBoo

Edit FooBar with the new implementation

Inspect, FooBar and FooBoo, move methods that are the same between them into a abstract class AbstractFoo, which both inherit from

Refactor, then Implement

Rename Foo, FooBoo

Consider what methods are not related to the part of the implementation that FooBoo and FooBaz are going to be different in. Move these to AbstractFoo

Create FooBaz and reimplement all the methods that remain within FooBoo

Which is to be preferred?
*Is there another method?*

Last time I had to do this, it was because the I decided that Foo had 2 different modes, that was determined by a boolean passed into the constructor.

This time (on a different class), it is because I want to try out using a different engine underneath that might be faster.
I want to keep FooBoo around because it has a subclass that I think will be much harder to implement for FooBaz, and I also want to be able to check that in the end they behave the same.

答:
I would go with the copy+paste approach as a starter, that gives you flexibility to do whatever you want with the new class without bringing any unintended side effects into existing code. This would sort of fall under the "tracer application" pattern since your main intent is to try out a completely new engine.

When you have your successful result(s) from your copy+pasted code you will follow the test driven pattern and refactor out the common bits into your abstract base class etc. This would come close to what is discussed in Kent Becks Test-Driven Development by example as well as the common work patterns discussed in the pragmatic programmer.

IMHO the above is how I would approach this problem most of the times since it leaves room for wild crazy experimentation without affecting the already working and tested code with the least amount of effort (eg. no current tests will be modified or broken etc and logic stays intact). The big effort comes when you have your working tracer to either throw it away and write a clean implementation based on your tracer code or to start integrate it with your actual code base.


问:
Who should do code reviews?
In my company mostly the architect does code reviews. He is a very experienced and smart software guy, so he is very good at it. When developers do the code reviews they don't do it half as well. We tried giving developers to do more code reviews, but the quality of the code reviews wasn't good.  We use Scrum for as development methodology.

However with the current system there are two problems:

The architect becomes a bottleneck

Developers don't take the responsibility for the quality of the code and the architecture (which leads to all sorts of problems).

How can we address these issues?  Should we change who does the code reviews?

答:
I agree, if just one person does reviews, the rest of the guys will probably just go with "I don't know, it seems to work, but let that smart guy figure it out if it's ok or not". I can think of the following:

make your code public so that everyone can see what everyone is working on; put out names at the start of each file that contains code; maybe print them out and stamp them in the, uhh, bathroom or wherever you feel it will catch some eyes

pair programming; with another brain beside you, you'll think twice before naming your variable i

pick up your janitor and explain him how that inheritance works (oh, yeah, it doesn't work). Explaining your code to someone else helps. Maybe it compiles, maybe it does the right stuff, but you didn't really understand why. Now is your chance

have a set of guidelines and make everyone follow them; whatever the guideline, it's better than no guideline

Title: Who should do code reviews?


问:
Efficient mixing of sync and async methods within a single method?
Okay, it sounds odd, but the code is very simple and explains the situation well.

```<code>public virtual async Task RemoveFromRoleAsync(AzureTableUser user, string role)
{
    AssertNotDisposed();
    var roles = await GetRolesForUser(user);
    roles.Roles = RemoveRoles(roles.Roles, role);
    await Run(TableOperation.Replace(roles));
}
</code>```

(I know I'm talking kind of in the abstract below, but the above is an actual method from what will be actual production code that is actually doing what I'm asking about here, and I'm actually interested in your actually reviewing it for correctness vis a vis the async/await pattern.)

I'm encountering this pattern more and more often now that I'm using async/await more.  The pattern consists of the following chain of events:

Await an initial call that gets me some information I need to work on

Work on that information synchronously

Await a final call that saves the updated work

The above code block is typically how I go about handling these methods.  I await the first call, which I have to because it is asynchronous.  Next, I do the work that I need to do which isn't IO or resource bound, and so isn't async.  Finally, I save my work which is also an async call, and out of cargo-cult I await it.

But is this the most efficient/correct way to handle this pattern?  It seems to me I could skip awaiting the last call, but what if it fails?  And should I use a Task method such as ContinueWith to chain my synchronous work with the original call?  I'm just at a point right now where I'm not sure if I'm handling this correctly.

Given the code in the example, is there a better way to handle this async/sync/async method call chain?

答:
Yes, I think this is the right way to do it.

You can't skip the second await. If you did, the method would seem to complete too early (before the removal was actually done), and you would never find out if the removal failed.

I don't see how would ContinueWith() or anything like that help here. You could use it to avoid using await, but it would make your code more complicated and less readable. And that's the whole point of await: making writing asynchronous code simpler, when compared with using continuations.

OwnerDisplayName: Will


答:
Developers should do code reviews.  They should do code reviews, because they should know the code, the company style standards and practices.  By having someone else do code reviews, you are telling your developers that it's not their responsibility to make sure the code meets the companies standards.

If you think they need training on doing code reviews, get it for them. Given your current situation, you could have a dev do the code review, and then have that commented by your architect -- have the dev submit the review to the architect for approval before sending it on to the submitter.

Title: Who should do code reviews?

Body:
In my company mostly the architect does code reviews. He is a very experienced and smart software guy, so he is very good at it. When developers do the code reviews they don't do it half as well. We tried giving developers to do more code reviews, but the quality of the code reviews wasn't good.  We use Scrum for as development methodology.

However with the current system there are two problems:

The architect becomes a bottleneck

Developers don't take the responsibility for the quality of the code and the architecture (which leads to all sorts of problems).

How can we address these issues?  Should we change who does the code reviews?


问:
Use of # in answers/documentation when referring to methods of a class
When looking through Java documentation or answers for Stack Overflow / programming forum questions, I often see people referring to methods like String#format, Object#clone etc, rather than String.format.

Is this something to do with it being a non-static method, or is this just some convention?

This is quite hard to search for due to most search engines ignoring the '#' symbol so I apologise if this is a duplicate question.

答:
The usage of String#format comes from the javadocs and is seen there as {@link package.class#member label} (docs on javadoc).

The generated link to the javadoc for String#format is format - the # being a link to an anchor within the page - in this case, the String.html page and the #format(java.lang.String,%20java.lang.Object...) anchor.  You can see an example of this at Oracle java docs for String#format (note the url and poke around the generated html too)

Nothing more than the leaking of the documentation format out into... other documentation.

Body:
The usage of String#format comes from the javadocs and is seen there as {@link package.class#member label} (docs on javadoc).

The generated link to the javadoc for String#format is <a href="../../java/lang/String.html#format(java.lang.String, java.lang.Object...)">format</a> - the # being a link to an anchor within the page - in this case, the String.html page and the #format(java.lang.String,%20java.lang.Object...) anchor.  You can see an example of this at Oracle java docs for String#format (note the url and poke around the generated html too)

Nothing more than the leaking of the documentation format out into... other documentation.


问:
How to write an optimal LAN messenger software?
I am asking this question as an extension to the following question:
https://superuser.com/questions/713409/how-to-message-any-user-on-your-lan

I don't think I have a real answer. I found it quite difficult to get the net send command working on Windows 7 and even if I could have it would have been enabled only for admin users.

So I have decided to write my own program to solve the problem. Using python I can write a program to check for messages on a common file (which I can store on a common harddrive which we have on our LAN). So the program will write from:192.168.23.44 to:192.168.23.45 Hello. Assuming the program is installed on both machines, I can ask the machines to poll this file every few seconds and pop-up a message if a message has been written for it, by searching for it in the to: field. If writing to a single file becomes an issue I will make multiple files which will act as inboxes for each of the computers on the LAN.

However, this approach is very inelegant. I don't suppose internet messengers, Google talk for instance, poll a server to check whether there are any new messages for the user. So my question is: what is the optimal way to write a LAN messenger program. Now that I think of it, I am looking for a minimalist approach. I will just put the program in the Startup folder of all the machines and it should come alive whenever any user logs in.

I was just able to configure the machine to respond to the ping command by making a new rule for the ICMPv4 protocol (ref: http://answers.microsoft.com/en-us/windows/forum/windows_7-networking/how-to-enable-ping-response-in-windows-7/5aff5f8d-f138-4c9a-8646-5b3a99f1cae6). I am guessing that answer lies in python and the ICMPv4 protocol, but I needed some direction.

答:
You could create your own chat protocol based on TCP/IP sockets.

There are two common ways to implement such an application. Either a client/server architecture or a peer-to-peer architecture.

In the client/server architecture, you run a central chat server on a machine which is always on. Each participant uses a separate client application. When a client goes online, it connects to the server. When a client want to send a message, it sends that message to the server. The server then relays it to the recipient(s).

When you don't have a server which is always online, you could instead go for a peer-to-peer architecture.

In that scenario your chat program is both client and server at the same time. To send a message to another user, the client of the sender connects directly to the client of the receiver. In order to be able to do this, you need to know the receivers IP address or at least its hostname so you can resolve the IP through DNS.


问:
Working with static constructor in Java
I didn't get a complete understanding of static constructors in Java. If it is allowed, why it is allowed? In what scenarios would you use it? What purpose would it serve? Can someone give me a simple example please?</p>

答:
it is used to initialize fields that is harder than simply assigning it:

```<code>public class Example{

    public final static Map<String, String> preFilledField;

    static{
        Map<String, String> tmp = new HashMap<>();
        //fill map
        preFilledField = Collections.unmodifiableMap(tmp);
    }
}
</code>```

it is not possible to fill a map on initialization (unless you use the anonymous subclass hack) so this is the best way to guarantee it is filled before first use

You can also do this to catch checked exceptions when initializing

Title: Working with static constructor in Java

Body:
it is used to initialize fields that is harder than simply assigning it:

public class Example{

    public final static Map<String, String> preFilledField;

    static{
        Map<String, String> tmp = new HashMap<>();
        //fill map
        preFilledField = Collections.unmodifiableMap(tmp);
    }
}

it is not possible to fill a map on initialization (unless you use the anonymous subclass hack) so this is the best way to guarantee it is filled before first use

You can also do this to catch checked exceptions when initializing


问:
If we close browser window without getting logout, what will happen when we provide same URL in the browser?
A few days ago, I appeared in an interview in a software company for .net developer. There I was asked the following question:

If we close browser window without getting logout, what will happen when
  we provide same URL in the browser?

My answer was that user will be able to view the home page with login details instead of being prompted to provide username and password as session of the user has not ended. Login information will actually be retrieved from cookies. But it depends upon the logic we have implemented for Login.

But the interviewer didn't seem be satisfied with my answer and didn't accept my answer. I am wondering what might be answer of this question. So, I need your kind guidance regarding correct answers. So please explain what I was supposed to reply.

答:
Happens the same thing that happens when the user hits the refresh button in the browser.

There are two typical methods for maintain session in http:

with cookies, the browser sends the same cookie to the browser because closing the browser don't delete cookies.

with url rewriting, in this case the url has the session info, if you close the browser, then open it and put the same url, that include the session info, the response from the server its the same.

Off course there are other scenarios, like Single Page Applications (or applications running in a browser plugin like flash or an ancient applet), and in this scenarios there is no general answser because all depends in the logic implemented by the application.


答: You can view the "static" section like a class level constructor use to initialize class properties (static in java). The same as the "normal" constructor its used to initialize instance level properties. </p>

Title: Working with static constructor in Java

Body: I didn't get a complete understanding of static constructors in Java. If it is allowed, why it is allowed? In what scenarios would you use it? What purpose would it serve? Can someone give me a simple example please?</p>


答:
Strictly speaking, Java does not have static constructors because a constructor, by definition, cannot be static.  What you are referring to is called a "static initialization block."  A constructor implies that you are constructing an object.  You cannot have  constructor for a class because a class is not an instance of itself.  It is simply a class.

All nit-picking aside, a static initialization block is used to initialize complex static (or class-level) fields for a class.  Usually these are used to initialize things that either cannot be initialized in one line, or require that some other object (which may or may not be in the class in which the static block is implemented) be initialized first.

Basically, one might use them to tell the class "Hey, set variable A to this value FIRST, then, once that's done, use A's value to initialize B."  Since Java requires that standard field initialization be done either within a constructor or method, or via the call of a constructor or method (unless it is a literal), these can be a convenient method for initializing complex, static objects.

Static initialization blocks are not needed all too often, and generally should be avoided unless they have a real use.  Don't get me wrong, they have their place in Java, but like many other things (such as break, return, switch, and goto statements) they can be easily over-used, which reduces their readability and the maintainability of the code-base they are used in.

A brief example of a static initialization block being used would be the following (as per the excellent explanation of static initialization blocks found here):

Code:

```<code>public class StaticExample{
    static {
        System.out.println("This is first static block");
    }

    public StaticExample(){
        System.out.println("This is constructor");
    }

    public static String staticString = "Static Variable";

    static {
        System.out.println("This is second static block and "
                                                    + staticString);
    }

    public static void main(String[] args){
        StaticExample statEx = new StaticExample();
        StaticExample.staticMethod2();
    }

    static {
        staticMethod();
        System.out.println("This is third static block");
    }

    public static void staticMethod() {
        System.out.println("This is static method");
    }

    public static void staticMethod2() {
        System.out.println("This is static method2");
    }
}
</code>```

Output:

This is first static block
This is second static block and Static Variable
This is static method
This is third static block
This is constructor
This is static method2
```

Some instances they list when static blocks can be useful:

If you’re loading drivers and other items into the namespace. For ex, Class class has a static block where it registers the natives.

If you need to do computation in order to initialize your static variables,you can declare a static block which gets executed exactly once,when the class is first loaded.

Security related issues or logging related tasks

Some reasons NOT to use static blocks (in other situations):

There is a limitation of JVM that a static initializer block should not exceed 64K.

You cannot throw Checked Exceptions.

You cannot use the this keyword since there is no instance.

You shouldn’t try to access super since there is no such a thing for static blocks.

You should not return anything from this block.

Static blocks make testing a nightmare.

I should note:  While some languages (such as C#) may have syntax for "constructors" that are static, those "constructors" function much the same way that static initialization blocks do in Java, and are seen by many (myself included) as misnomers in the language, given the basic concept of an OOP constructor.

Title: Working with static constructor in Java

Body:
Strictly speaking, Java does not have static constructors because a constructor, by definition, cannot be static.  What you are referring to is called a "static initialization block."  A constructor implies that you are constructing an object.  You cannot have  constructor for a class because a class is not an instance of itself.  It is simply a class.

All nit-picking aside, a static initialization block is used to initialize complex static (or class-level) fields for a class.  Usually these are used to initialize things that either cannot be initialized in one line, or require that some other object (which may or may not be in the class in which the static block is implemented) be initialized first.

Basically, one might use them to tell the class "Hey, set variable A to this value FIRST, then, once that's done, use A's value to initialize B."  Since Java requires that standard field initialization be done either within a constructor or method, or via the call of a constructor or method (unless it is a literal), these can be a convenient method for initializing complex, static objects.

Static initialization blocks are not needed all too often, and generally should be avoided unless they have a real use.  Don't get me wrong, they have their place in Java, but like many other things (such as break, return, switch, and goto statements) they can be easily over-used, which reduces their readability and the maintainability of the code-base they are used in.

A brief example of a static initialization block being used would be the following (as per the excellent explanation of static initialization blocks found here):

Code:

public class StaticExample{
    static {
        System.out.println("This is first static block");
    }

    public StaticExample(){
        System.out.println("This is constructor");
    }

    public static String staticString = "Static Variable";

    static {
        System.out.println("This is second static block and "
                                                    + staticString);
    }

    public static void main(String[] args){
        StaticExample statEx = new StaticExample();
        StaticExample.staticMethod2();
    }

    static {
        staticMethod();
        System.out.println("This is third static block");
    }

    public static void staticMethod() {
        System.out.println("This is static method");
    }

    public static void staticMethod2() {
        System.out.println("This is static method2");
    }
}

Output:

This is first static block
This is second static block and Static Variable
This is static method
This is third static block
This is constructor
This is static method2

Some instances they list when static blocks can be useful:

If you’re loading drivers and other items into the namespace. For ex, Class class has a static block where it registers the natives.

If you need to do computation in order to initialize your static variables,you can declare a static block which gets executed exactly once,when the class is first loaded.

Security related issues or logging related tasks

Some reasons NOT to use static blocks (in other situations):

There is a limitation of JVM that a static initializer block should not exceed 64K.

You cannot throw Checked Exceptions.

You cannot use the this keyword since there is no instance.

You shouldn’t try to access super since there is no such a thing for static blocks.

You should not return anything from this block.

Static blocks make testing a nightmare.

I should note:  While some languages (such as C#) may have syntax for "constructors" that are static, those "constructors" function much the same way that static initialization blocks do in Java, and are seen by many (myself included) as misnomers in the language, given the basic concept of an OOP constructor.

ContentLicense: CC BY-SA 4.0


问:
Correct alignment when outcommenting code
Suppose I have some code

```<code>void some_block(void)
{
    some_statement_1();
    some_statement_2();
    some_statement_3();
}
</code>```

Now I wish to out-comment statement #2, but here I never can find a way where it feels right. Usually I will do the following:

```<code>void some_block(void)
{
    some_statement_1();
//    some_statement_2();
    some_statement_3();
}
</code>```

But now we got what looks like extra indentation of statement #2, yet it is arguable whether the indentation is still "correct". Alternatively we could do:

```<code>void some_block(void)
{
    some_statement_1();
    //some_statement_2();
    some_statement_3();
}
</code>```

This looks a bit better, yet still somehow also wrong. However the following just looks misplaced:

```<code>void some_block(void)
{
    some_statement_1();
  //some_statement_2();
    some_statement_3();
}
</code>```

How do you outcomment code and keep "correct" indentation?

Update

It seems most people who have provided answers did not answer my question, but simply state that it is bad practice to leave dead code around. While I completely agree with that, that was not the point of the question.

Right now I am facing a case of example where I have 5 helper functions, that manage 5 similar but slightly different structs for me. I use these helper functions to make my code easier to read.

But, at the moment (and for the next month probably) one of the structs are not going to be used. And I cannot commit anything which causes compiler warnings, so I have to outcomment that part of the code and commit it like that.

Also I forgot this last variant, which I think just looks plain wrong:

```<code>void some_block(void)
{
    some_statement_1();
//  some_statement_2();
    some_statement_3();
}
</code>```

答: Format it so it sticks out and makes your code look so ugly that you'll be compelled to delete it. Comments are for comments and not for dealing with unnecessary code; that's the job of version control. </p>

ContentLicense: CC BY-SA 2.5


问:
What's the point of Continuous Integration services like Travis CI?
As far as I can tell, services like Travis CI and CircleCI take your project and run its test suite whenever you push a new change to your repository.

Assuming that it's also possible to either manually or automatically run such test suite locally before you commit or push your change, what's the point in using a service like this?

答:
The key idea with continuous integration is to always have a working build, that is, a build that completes successfully and passes unit tests in canonical build enviroment.  This is because it's much easier to ensure that the build always works than to fix a build that accidentally got broken a while ago, esp. when no one is quite sure who broke it and when.

With continuous integration, you will immediately know if:

Someone has accidentally committed code without including a new source file

Someone accidentally used an absolute reference path

Someone just plain screwed up

Which means that it will get fixed immediately while the memory of the changes is still fresh.


问:
What to do when you have exhausted all avenues to fix a bug
I am a Junior Programmer(4 months career experience so far) working on a Cross Platform Mobile Application (1 person team - so its just myself).

I have a bug in this program/app which is pretty large (30 different header files, each with their own cpp file too). I have been trying to track down exactly what is going on with the bug & also to fix it (even tried to use some hacks to just get it working) but of about a dozen or more solutions(ideas I have of whats causing the problem) I have come up with nothing has led me to track exactly what the bug is or fixed the bug.

Do you have any advice for a junior programmer of some broad techniques(go for a run, print all my code onto paper & go through it with a pen, etc.) I could use to assist me with this bug?

To give a little more context for my bug; it involves the cross platform API Mosync, when I perform a specific sequence of actions, the current screen does not redraw (& it appears) that the previously displayed screen is still receiving the pointer/key press events & not the current screen.

Specific sequence:

- Menu Screen Displayed - click "Show prev orders button"

- Prev Orders Screen Displayed - click "Load file" then click menu button & open Delivery Screen

- Delivery Screen Displayed - click menu button & open Purchase Screen

- Purchase Screen Displayed - Error here, input to this screen is not displayed/reacted to, ListViews dont scroll, buttons dont react to clicks, ListView cells dont respond to clicks

I will take the advice on board, the bug is reproducable 100% following the same steps each time, although it still very difficult to figure out how pointer events are being transmitted & to what screen due to fact thats a part of the API I cant reach(or dont know how to).

Also I would love to have a different pair of eyes go over my work & point out the bug, but as I said I am a team of 1, my boss directs me, he owns the company & has the ideas for an app but does not know c++ or any recent languages either (cobal? I think is all). Any advice on how to get a second pair of eyes without breaching/showing off the company's intellectual code/property?

...and no leaving this paid internship is not an option, the contract says if I leave before 6mnths of a 12mnth contract I maybe liable to pay 30% of my yearly salary

答:
Lots of good answers here. A few other tips:

UIs seldom live in isolation. Build up a test program with the minimal set of features required to reproduce the bug. If the UI is well-designed, you should be able to decouple the UI components which are failing, and run them in isolation in a test program. Can you still reproduce the problem? If so, the problem is likely in your UI structure or framework. Check your UI structure - especially watch out for invisible elements. Try to learn exactly what happens when you click on that ListView and it doesn't respond - what event handlers are invoked? Bear in mind, there may exist bugs in the UI framework itself - don't jump to that conclusion, but don't rule it out outright. A quick test is to upgrade your version of Mosync and check if the symptoms abide.

Failing that: What is left in your test program? Understand all the components of what remains, particularly any running threads. Something doing database maintenance in the background? A file spooler of some kind? NSA user behavior monitoring code? Is the UI working with some of these components (possibly behind the scenes)? What background operations does the UI depend on?

While you're reading the code - which you should be spending considerable time doing, given the difficulty in the bug - watch out for some bad practices that could be obscuring your bug. Specifically, do you see any of this?

```<code>try {
    SaveTheWorld();
} catch (std::exception& ex) { /* oh it didn't work, let's just ignore it */ }
</code>```

That's incredibly poor practice and as such, is fairly commonplace (hey look it didn't crash!). Make sure you upgrade any code that's doing that to at least log it - preferably remove the false exception handling entirely. (A rule of thumb is that if you don't know what the exception is, you're not prepared to handle it.) If it's interacting with C-style APIs, watch for dropped error-code return values, and be sure that you're checking error status information from whatever tools you're interacting with.

Seeing as how your test program is now properly handling failures, and you've read the log you've thus produced, but still nothing highlights the bug, look for interfaces you can probe. Is there a network transaction that should be happening under the covers? If so, hit it with Wireshark. Database transaction? Try some query logging, or checking the database server status. Filesystem or network shares being hit? Check the intermediate files, or use a debugger to trace I/O. Hardware I/O? Monitor and probe. Be empirical. The UI could well be hung up on some background operation you haven't anticipated.

Lastly: Don't panic. Keep cool, and keep track of what you've tried. If you still can't find it, it'll have to become a "known issue" to be tracked down on a rainy day. You'll want lots of material to justify that decision if it has to go that way.

Body:
Lots of good answers here. A few other tips:

UIs seldom live in isolation. Build up a test program with the minimal set of features required to reproduce the bug. If the UI is well-designed, you should be able to decouple the UI components which are failing, and run them in isolation in a test program. Can you still reproduce the problem? If so, the problem is likely in your UI structure or framework. Check your UI structure - especially watch out for invisible elements. Try to learn exactly what happens when you click on that ListView and it doesn't respond - what event handlers are invoked? Bear in mind, there may exist bugs in the UI framework itself - don't jump to that conclusion, but don't rule it out outright. A quick test is to upgrade your version of Mosync and check if the symptoms abide.

Failing that: What is left in your test program? Understand all the components of what remains, particularly any running threads. Something doing database maintenance in the background? A file spooler of some kind? NSA user behavior monitoring code? Is the UI working with some of these components (possibly behind the scenes)? What background operations does the UI depend on?

While you're reading the code - which you should be spending considerable time doing, given the difficulty in the bug - watch out for some bad practices that could be obscuring your bug. Specifically, do you see any of this?

try {
    SaveTheWorld();
} catch (std::exception& ex) { /* oh it didn't work, let's just ignore it */ }

That's incredibly poor practice and as such, is fairly commonplace (hey look it didn't crash!). Make sure you upgrade any code that's doing that to at least log it - preferably remove the false exception handling entirely. (A rule of thumb is that if you don't know what the exception is, you're not prepared to handle it.) If it's interacting with C-style APIs, watch for dropped error-code return values, and be sure that you're checking error status information from whatever tools you're interacting with.

Seeing as how your test program is now properly handling failures, and you've read the log you've thus produced, but still nothing highlights the bug, look for interfaces you can probe. Is there a network transaction that should be happening under the covers? If so, hit it with Wireshark. Database transaction? Try some query logging, or checking the database server status. Filesystem or network shares being hit? Check the intermediate files, or use a debugger to trace I/O. Hardware I/O? Monitor and probe. Be empirical. The UI could well be hung up on some background operation you haven't anticipated.

Lastly: Don't panic. Keep cool, and keep track of what you've tried. If you still can't find it, it'll have to become a "known issue" to be tracked down on a rainy day. You'll want lots of material to justify that decision if it has to go that way.


问:
"Clean Code": How to organize named queries?
Few days ago I started to read Robert C. Martin "Clean Code" book and it encouraged me to look more detailed at my code. After I opened eclipse I saw this:

```<code>entityManager.createNamedQuery("CarriageRouteEntity.listCarriageDirections");
</code>```

and I decided to move string CarriageRouteEntity.listCarriageDirections to constant string. After quick fix I created something like this:

```<code>@NamedQueries({
        @NamedQuery(name = CarriageRouteEntity.LIST_CARRIAGE_DIRECTIONS, query = "just query ...") })
public class CarriageRouteEntity {
    public static final String LIST_CARRIAGE_DIRECTIONS = "CarriageRouteEntity.listDirections";
    // ...
}
</code>```

so now I call it like this:

```<code>entityManager.createNamedQuery(CarriageRouteEntity.LIST_CARRIAGE_DIRECTIONS);
</code>```

And here I started to wondering where should I put named queries constants. Is entity class good place for this? Maybe I should create new class with these constants like

```<code>public class CarriageRouteEntityNamedQuery {
        public static final String LIST_CARRIAGE_DIRECTIONS = "CarriageRouteEntity.listDirections";
}
</code>```

but if another programmer will try to create named query will he knew where to look at it? What are your opinions? How to organize these constants? Maybe instead of creating CarriageRouteEntityNamedQuery class I should create enum and add method to entity CarriageRouteEntity called getNamedQuery() which will tell another programmer in which enum he/she should look for constants?

答:
I've done both of the approaches you've mentioned and both are equally as useful.  Depending on how your architecture is set up, there are some conditions you might want to consider:

1.) If you have less than 7 or 8 named queries, I would consider putting them as constants in the same class as your data access methods if and only if the named queries are used in that class.

2.) If you have more than 8 named queries or you have multiple named queries spread across multiple entity classes that you'd like to store in a single location, I would definitely put those in a separate class as constants.

Be sure to place your named query classes as close to your entity classes as possible.


问:
Why develop free, open source programs?
Why would someone use his own time to develop an open-source project for free and without compensation?</p>

答:
For small projects, reasons might be "hobby", "getting some experience", "fame", "joy" etc. but that's not how the big open source projects like Mozilla, OpenOffice, Linux work.

Why did Sun buy StarDivision and made StarOffice an open source program (called OpenOffice.org)? Why does Mozilla create a top-notch browser and give it away as open source? Why are there people creating Linux, writing drivers and whatnot, and make it available to everyone for free? Why does Microsoft create opensource drivers for Linux so it can run better in MS's virtualisation?

Because it makes some business sense for them. They make money that way, or at least plan to.

In some cases, the dominance of MS's products, i.e. Windows, Office, Internet Explorer, was the reason the create a competing product, so it would be harder for MS to use their desktop dominance to conquer other domains, i.e. servers, internet services, too. This explains, to some extend, OpenOffice.org and Mozilla.

In other cases, open source software is meant to drive sales of hardware, other software or services. Open Source drivers obviously help to sell hardware components to Linux users. RedHat sells support for their Linux distro, and they sell the fact that their Linux is genuine RedHat. Other products, e.g. Oracle, are certified for use on Redhat, but not on CentOS, even though it probably runs just-as-well. Server hardware is certified for Redhat, even though other linux distros probably run just-as-well. Big-money-clients don't care about the price, they want the certificate.

Some companies, e.g. Google, sponsor many open source projects, because it helps their business. They don't do it for altruism. They want a free internet, a pervasive internet, a widespread internet, where people use Google's services so Google generates revenue.

Title: Why develop free, open source programs?


问:
Is saving SQL statements in a table for executing later a bad idea?
Is saving SQL statements in a MySQL table for executing later a bad idea? The SQL statements will be ready for execution, i.e. there will be no parameters to swap or anything, for example DELETE FROM users WHERE id=1.

I guess I'm being lazy, but I thought of this idea because I'm working on a project that will require quite a few cron jobs that will execute SQL statements periodically.

答:
There are valid reasons to store SQL in a table. Software I work with at work now includes a system for generating documents and the documents need to include fairly complex calculations using data in a database. The documents are updated frequently, are often significantly different in terms of the data needed, and the calculations that need to be performed. SQL is being used, basically, as a scripting language for performing these calculations and that SQL is stored in tables that also store other info for these documents. The people that maintain those documents are not programmers or DBAs, but they're familiar with the database schema and they're proficient with SQL. It would be significant overhead for them to maintain that SQL code in the form of stored procedures.

For what you described – "... a project that will require quite a few cron jobs that will execute SQL statements periodically" – the other answers are probably correct in suggesting that you used store procedures, or the equivalent, for the DBMS you're using.

A good criteria for deciding whether it's sensible to store SQL in a table versus in a stored procedure is determining who will be maintaining that SQL. If users maintain that SQL, i.e. they write it and change it whenever they want, then it may be perfectly fine, and indeed best, to store that SQL in a table. If developers will be maintaining that SQL, then it should be stored in a form that can be updated by your (hopefully automated) build and deployment procedures, e.g. stored as an object like a stored procedure in the database itself.


问:
Is TCP message order still guaranteed when using async IO
Here the scenario I'm imagining. Two messages are transferred, both will require 2 packets each (I know you don't deal with packets directly with TCP, but on the IP level each message will consist of 2 packets [or segments as they're called in TCP])

The problem I'm imaging is buffering the first packet of the first message, but a router dumps the second packet for some reason. Being TCP, the second packet is guaranteed to be resent, and I know that TCP will hand these two packets up to the application layer in order. But while being handled asynchronously, this first packet will still be handed up to the application which will not block during the period in which the underlying TCP layer handles the retransmission of the second packet.
What will happen if the first packet of the second transmission arrives before the last packet of the first transmission? Will TCP not hand these packets up until the first transmission is handled in full? Will an async client not send the second message before the first has been handled in full?

I know that TCP will guarantee the order of packets for each message. My confusion is whether it will fully complete one transmission before processing the second transmission when being handled asynchronously.

答:
TCP is a stream protocol (not packets as you clearly said). The TCP stack layer will only deliver the data in stream order. Async or not, the data will not be handed to the client out of order.

TCP would not be a very good streaming protocol if it did deliver data out of order. That's kind of the point of the protocol. :-)


问:
What programming language generates fewest hard-to-find bugs?
What language, in your opinion, allows the average programmer to output features with the least amount of hard-to-find bugs? This is of course, a very broad question, and I'm interested in very broad and general answers and wisdoms.

Personally I find that I spend very little time looking for strange bugs in Java and C# programs, while C++ code has its distinct set of recurring bugs, and Python/similar has its own set of common and silly bugs that would be detected by the compiler in other languages.

Also I find it hard to consider functional languages in this regard, because I've never seen a big and complex program written in entirely functional code. Your input please.

Edit: Completely arbitrary clarification of hard-to-find bug: Takes more than 15 minutes to reproduce, or more than 1 hour to find cause of and fix.

Forgive me if this is a duplicate, but I didn't find anything on this specific topic.

答:
What language, in your opinion, allows
  the average programmer to output
  features with the least amount of
  hard-to-find bugs?

In my opinion, Delphi.  Being based on Pascal, the language is simple and intuitive enough for the average programmer (or even inexperienced coders) to pick up easily, and its rich tool and library support make most bugs easy to find.

Strong typing and a strict compiler that catches many common errors.

Intuitive syntax that doesn't encourage common errors.  ("The World's Last Bug," if (alert = RED) {LaunchNukes;}, will not compile, for example.)

A well-designed object model that eliminates many of the common C++ OOP errors.

Bounds checking and range checking built in to the language, drastically reducing the chances of security problems.

Probably the fastest compiler known to man, which increases your productivity and makes it harder to lose your train of thought while waiting on a build.

The debugger Visual Studio's debugger wants to be like when it grows up.

Leak tracking built directly in to the memory manager, making finding and fixing memory leaks trivial.

A large, mature standard library providing prebuilt and pre-tested ways to accomplish common tasks without having to build your own, possibly buggy implementations.

Ships with useful tools, such as a powerful logging system and a profiler, to make tracking down problems easier.

Strong community support for common issues that aren't in the standard library, including a powerful third-party concurrency library.


问:
How far to go when standardizing code
My small team and I have created a decent sized web application (~50k lines), with a fully featured API, all in Perl. As us perl hackers know.. it is easy to get sloppy. We had to port over a lot of legacy code.. thus perl whale guts code ensued.

Long story short, we were under a fairly tight time constraint which now has been pushed back, so we have some time to go back in and standardize code.

We quickly found out how nonstandard our code was as our contractor was developing an iOS app where we have account numbers of length 10 some places, 12 in others with prepended data, etc.

As I'm going through fixing date formats and data formatting, I'm noticing a ton of really non descriptive variable and hash key naming which came from legacy code - not nice down the road maintaining it.

Basically, my question is - given the scenario above or your own experience, how far do you go when cleaning up and standardizing? Is it worth going in and replacing hash key names with longer camel cased ones, and variable names, the way data is handled in results - etc.

I know lot more pain can come from breaking working code, and it may not be worth it.. but how do you know how far to go? Get it over with now and then it pays off later, or just live with a bit of "code debt"?

答:
TL;DR: Use automated linting and a commit hook code reformatter.

When I was doing Perl we decided to put a lint checker in our test suite, and a commit hook that automatically reformatted the code.  We did this so that going forward we would not incur more technical debt from lack of code consistency and linting issues.

We didn't want to pay the time cost to bringing the entire code base up to the new standard all at once so we grandfathered them in with explicit exceptions based on the precise error the linter threw (including line number).  The exception were purposely fragile so that the next time someone touched the file they would need to bring it up to the standards set by the linter.

Overtime we extended our linter and code reformatter with customizations based on our teams standards.  This allowed us to use the automated tests and continuous integration to help drive out linting bugs.  When the reformatter changed we would just run it en masse and commit the changes.  For as many things as possible we created automated drivers to either force the change (reformat the code) or catch issue (linting).  We ended driving to a fairly complete standard for ourselves.  Certainly enough that we never really had a problem after to any related issue on standardization or consistency.  Perhaps some on idioms to use and not use, but even some them made it into the lint extensions.

Title: How far to go when standardizing code


问:
Using error numbers which only work on 64 bit servers: a bad idea?
In an attempt to solve one problem I encountered another. I would like to have an easy and memorable way of creating unique error numbers, across projects and across developers. The scheme I came up with was to use the initials of the developer, find their position in the alphabet, and append the date and time.
Example: lets say the developer Mark Elliot Zuckerberg (initials MEZ) writes code that throws an exception on Feb 8th 2014 at 12:54AM. The error code would be: 8526020820140054

This works brilliantly on 64 bit machines, but the resulting integer is too large for 32 bit computers. Does that make this a bad idea? How common are 32 bit servers, and do we expect them to slowly disappear completely?

答: Let a database create your unique number for you -- log the error to a sql db, and your problem is solved.  Include application info (ie what app encountered the error) and Bob's your uncle.</p>


答:
While I can see the point in having the system/software architect sign off all changes/commits, the software developers should be able to do reviews without involving the architect - except for arbitration.

My preferred[*] review procedures are:

Group changes by requirement/issue.

Invite all developers, the software architect and the author of the requirement/issue to review.  (They are not all required to do a review.)

Consider a review finished when:

Two developers have reviewed.

All comments are responded to.  (Possibly by having the software architect make a decision.)

One working day has passed without further discussion (or all invited parties have reviewed).

So my short answer to your question is:  The developers should do change reviews.

[*] Unfortunately this is not always how the projects I participate in operate.

Title: Who should do code reviews?


答:
In this situation, what you need is for the knowledge of this experienced developer to help the rest of the team grow. The quality of a team is not defined by the skills of the best developer; it's defined by the skills of the worst. You can try things like:

Collaborative reviews. This worked really great in my last team. We put the whole team in a room with a projector and started reviewing some items. Perhaps at the beginning the architect is the one that guides the review, but in a few weeks (we reserved one or two hours every Friday) the whole team starts to talk and understand the key concepts that currently only the architect seems to know.

Pair programming. For me this is the best tool for spreading knowledge in a team.

Title: Who should do code reviews?


问:
algorithm to extract "possibilities" from a tree
From a given tree, subsequent trees have to be generated. Nodes can be marked as "variant" in the given tree (the example uses an asterisk to mark the node). All possible combinations between the variants form the resulting trees.

From the following tree:

```<code>- Product
    - Packaging *
        - Small box
        - Heavy box *
            - Eco
            - Non-eco
    - Delivery *
        - Standard
        - Express
</code>```

The following 6 trees should be generated:

```<code>- Product
    - Packaging
        - Small box
    - Delivery
        - Standard

- Product
    - Packaging
        - Small box
    - Delivery
        - Express

- Product
    - Packaging
        - Heavy box
            - Eco
    - Delivery
        - Standard

- Product
    - Packaging
        - Heavy box
            - Eco
    - Delivery
        - Express

- Product
    - Packaging
        - Heavy box
            - Non-eco
    - Delivery
        - Standard

- Product
    - Packaging
        - Heavy box
            - Non-eco
    - Delivery
        - Express
</code>```

Is there an elegant algorithm for this (recursive solution)?

答:
To start with, here is a function to count to total amount of possible new trees. Input is the node at the root of the tree.</p>

```<code>function CountPossibilities(node)

    _result = 0

    if node.isvariant then

        _result = 0

        for each _child in node.childnodes

            _result += CountPossibilities(_child)

        next

    else

        _result = 1

        for each _child in node.childnodes

            _result *= CountPossibilities(_child)

        next

    end

    return _result

end function
</code>```

Body:
To start with, here is a function to count to total amount of possible new trees. Input is the node at the root of the tree.

function CountPossibilities(node)

    _result = 0

    if node.isvariant then

        _result = 0

        for each _child in node.childnodes

            _result += CountPossibilities(_child)

        next

    else

        _result = 1

        for each _child in node.childnodes

            _result *= CountPossibilities(_child)

        next

    end

    return _result

end function


答:
What about this?</p>

```<code>void some_block(void)
{
    some_statement_1();
    some_statement_3();
}
</code>```

Title: Correct alignment when outcommenting code

Body:
Suppose I have some code

```<code>void some_block(void)
{
    some_statement_1();
    some_statement_2();
    some_statement_3();
}
</code>```

Now I wish to out-comment statement #2, but here I never can find a way where it feels right. Usually I will do the following:

```<code>void some_block(void)
{
    some_statement_1();
//    some_statement_2();
    some_statement_3();
}
</code>```

But now we got what looks like extra indentation of statement #2, yet it is arguable whether the indentation is still "correct". Alternatively we could do:

```<code>void some_block(void)
{
    some_statement_1();
    //some_statement_2();
    some_statement_3();
}
</code>```

This looks a bit better, yet still somehow also wrong. However the following just looks misplaced:

```<code>void some_block(void)
{
    some_statement_1();
  //some_statement_2();
    some_statement_3();
}
</code>```

How do you outcomment code and keep "correct" indentation?

Update

It seems most people who have provided answers did not answer my question, but simply state that it is bad practice to leave dead code around. While I completely agree with that, that was not the point of the question.

Right now I am facing a case of example where I have 5 helper functions, that manage 5 similar but slightly different structs for me. I use these helper functions to make my code easier to read.

But, at the moment (and for the next month probably) one of the structs are not going to be used. And I cannot commit anything which causes compiler warnings, so I have to outcomment that part of the code and commit it like that.

Also I forgot this last variant, which I think just looks plain wrong:

```<code>void some_block(void)
{
    some_statement_1();
//  some_statement_2();
    some_statement_3();
}
</code>```

Body:
What about this?

void some_block(void)
{
    some_statement_1();
    some_statement_3();
}


问:
Returning null or a empty value/throw exception?
Various programming books suggest that methods should not return null values (Clean Code for example). Instead of returning null default values (0 or empty string or empty object) should be returned or an exception should be thrown. This is recommended in order to avoid many != null checks or to avoid NullPointerException.

I really don't understand how this helps. If you return a default value you have to make != DEFAULT checks; more over, the default value might mean something (like 0 for a credit amount). Throwing a specific exception is not worth with, because if you don't handle your code well, an exception is thrown anyway - NullPointerException.

I've thought about  this when I found a bug caused by a method which returned an empty object (e.g. new MyBean()) instead of returning null. The code didn't worked functionally and the logs didn't warn anything, so detection and fixing was not that easy; with null a NullPointerException would have been thrown so spotting and fixing the bug would have been trivial.

The only case where it makes sense to me to return a default value instead of returning null is when returning arrays/collections; here they are usually consumed for each element in collection so if its empty nothing happens but if it's null NPE is thrown.

答:
I like the idea of throwing an exception instead of returning null or other error-value. Let's say I'm designing a new class that parses an XML of a certain format. I would like my class to have just one entry point, that is, a constructor that specifies the path to a valid XML file. In return, I get an object with a bunch of properties and methods that holds the content of my XML file and gives me some information about it.

Now, for example, how can I make sure that my path to the XML file was valid? I can have, say, a Load(string xmlPath) function in my class. What should be its return type? Should it return a bool or int or what? And, most interesting, how can I check that? Ideally I should make the Load function private, and don't even care that it exists. But if I want to check the result of Load, then the function should be made public. Or, pass a bool loadSuccesful variable to my constructor and fill that with the result of loading the file. But wait, what if I want to check my XML file against an XSD? I'll have to have another function, parseXmlSchema(string xmlPath) or something like that. What should it return on failure? And how can you get the information out of your class while keeping a clean interface at the same time? Other validations could also be necessary.

While, if you make these kinds of methods private, and throw an exception when something goes wrong (there really is no point in parsing your XML file if it's not valid), you can have a clean interface an use your class in a try/catch statement. You can have your class constructor with only one string parameter (or two, if you count the XSD schema). If all is well in the try statement, if nothing went wrong, no exceptions thrown, paths exists, etc. your program is happy. If you're currently in the middle layer of your app and get an FileNotFoundException from your lower layers, you can rethrow that and pass it to your user (GUI) to do something about it. The GUI layer could catch it at this moment and alert the user, through a messageBox, for example, and log it as a bonus. The user then tries another XML file, and on goes the story. If you catch all possible exceptions and display meaningfull information to the user or take the appropriate measures in the background, there is no need for your application to freeze (you've likely seen that), if that's what you're afraid of.

As a bonus, you can pass all kind of meaningful information at the point your exception was thrown, like messages, parameter names, line numbers, function name, etc. If you document your code (as you should), document the exceptions that a class/method can throw.


答:
Various programming books suggest that methods should not return null
  values (Clean Code for example). Instead of returning null default
  values (0 or empty string or empty object) should be returned or an
  exception should be thrown. This is recommended in order to avoid many
  != null checks or to avoid NullPointerException.

It is worth mentioning and a common misunderstanding, that Mr. Martin did not claim that you should always throw an exception and should never return an error value. In fact, the relevant passage reads quite different if you read it carefully (I don't have the english version here, so I have to translate it back, sorry):

If you are about to return a null pointer, you should consider throwing an exception instead.

Note that it says "consider", not "thou shalt".

Another good read are these two:

Larry Osterman: Structured Exception Handling Considered Harmful

Joel on Software: Exceptions

PS: Original text from my german edition:

Wenn Sie versucht sind, einen Nullzeiger zu liefern, sollten Sie stattdessen erwägen, eine Exception zu werfen.

Title: Returning null or a empty value/throw exception?

Body:
Various programming books suggest that methods should not return null values (Clean Code for example). Instead of returning null default values (0 or empty string or empty object) should be returned or an exception should be thrown. This is recommended in order to avoid many != null checks or to avoid NullPointerException.

I really don't understand how this helps. If you return a default value you have to make != DEFAULT checks; more over, the default value might mean something (like 0 for a credit amount). Throwing a specific exception is not worth with, because if you don't handle your code well, an exception is thrown anyway - NullPointerException.

I've thought about  this when I found a bug caused by a method which returned an empty object (e.g. new MyBean()) instead of returning null. The code didn't worked functionally and the logs didn't warn anything, so detection and fixing was not that easy; with null a NullPointerException would have been thrown so spotting and fixing the bug would have been trivial.

The only case where it makes sense to me to return a default value instead of returning null is when returning arrays/collections; here they are usually consumed for each element in collection so if its empty nothing happens but if it's null NPE is thrown.


问:
Binary Search seems superior, why did the committee of C++ still have Find in the algorithm library?
I wish to search for an integer in a vector of integer. I have two candidates for the job:

Binary Search

Find

It seems that Binary Search is the best candidate for the job as although I have to sort the vector, the total running time will be O(NLog2N) assuming quicksort take O(NLog2N) and searching takes O(Log2N).

The running time for Find will be O(N).

It seems such clear cut that Binary Search is superior to Find, why did the committee of C++ still have Find in the algorithm library?

I am sure the C++ committee had their reasons for including Find, what benefits of Find am I missing or how is Find superior to Binary Search?

EDITED : Changed running time of quicksort to NLog2N

答:
Not every list is sorted, yet sometimes there are things we'd like to find.

Also quicksort is O(n log n), which means it takes longer than O(n).


答:
Find is meant to operate on any generic STL container, some of which are expensive to sort. There are faster ways to find an item with the right data structure, such as with std::set, and that class has a find member function.

Furthermore, the premise of your question is false. The asymptotic complexity of quicksort is O(n^2), not O(log 2n) or O(n log n). Many people seem to confuse that with the average complexity of quicksort.

Quicksort, or partition-exchange sort, is a sorting algorithm
  developed by Tony Hoare that, on average, makes O(n log n) comparisons
  to sort n items. In the worst case, it makes O(n^2) comparisons, though
  this behavior is rare.

Title: Binary Search seems superior, why did the committee of C++ still have Find in the algorithm library?

Body:
I wish to search for an integer in a vector of integer. I have two candidates for the job:

Binary Search

Find

It seems that Binary Search is the best candidate for the job as although I have to sort the vector, the total running time will be O(NLog2N) assuming quicksort take O(NLog2N) and searching takes O(Log2N).

The running time for Find will be O(N).

It seems such clear cut that Binary Search is superior to Find, why did the committee of C++ still have Find in the algorithm library?

I am sure the C++ committee had their reasons for including Find, what benefits of Find am I missing or how is Find superior to Binary Search?

EDITED : Changed running time of quicksort to NLog2N


答:
I made a litle concept script with sockets.

See.

The server:

```<code># Sockets server.
import socket

s = socket.socket()
s.bind(("localhost", 44000))
s.listen(1)

print("Connection Waiting...")
sc, addr = s.accept()
print("Connection Matched!")

while True:
    print("Waiting message...")
    received = sc.recv(128)
    print(type(received))
    a = received.decode('utf-8')
    print(type(a), len(a))
    if a == "quit":
        break
    print("Received Message:", a)
    sc.send(received)

print("Good bye!")

sc.close()
s.close()
a = input("Enter key to End:")
</code>```

And this is the client script:

```<code># Sockets client script
import socket, time

s = socket.socket()
print("Connecting to server...")
while True:
    try:
        s.connect(("localhost", 44000))
        break
    except:
        print("Retrying connection to server...")
        time.sleep(1)

print("Connection Matched!")

while True:
      keyboardInput = input("Enter the message: ")
      # s.send(bytes(message, 'UTF-8'))
      message = keyboardInput.encode('utf-8')
      s.send(message)
      print("Message sent!")
      r = s.recv( 128)
      a = r.decode('utf-8')
      print("Confirmation received message: ", a)
      if keyboardInput == "quit":
         break

print("Good bye")

s.close()

a = input("Enter key to End:")
</code>```

Edit: to implement multi-threads.  In order to avoid the server blocks the flow while is waiting for incoming message.

```<code># Example script with sockets and multi-threads
import socket, threading, time

a = ""
s = socket.socket()
s.bind(("localhost", 44000))
s.listen(1)

sc, addr = s.accept()

class MiThread(threading.Thread):   # Defines the class MiThread, subclass of Thread
    def __init__(self, sc):
        threading.Thread.__init__(self)

    def run(self):  # this method is the code of the thread, it will works when be called by .start() method
        received = sc.recv(128)
        print(type(received))
        a = received.decode('utf-8')
        print(type(a), len(a))
        print("Received Message:", a)
        return a

t = MiThread(sc)     # creates an object of class MiThread, subclass Thread
t.start()       # method start() calls to .run() method as a thread

# this code is for debugging, change it and put your own code
# I'll works in the main proccess while the thread is waiting for messages
for i in range(0, 60):
    time.sleep(1)
    print("Seconds: ",i)
    #sc.send(received)

print("Time out. Good bye!")

sc.close()
s.close()
a = input("Enter key to End:")
</code>```

If you want to code a litle chat, you might to use this two utils: sockets and multi-threading.

Title: How to write an optimal LAN messenger software?

Body:
I am asking this question as an extension to the following question:
https://superuser.com/questions/713409/how-to-message-any-user-on-your-lan

I don't think I have a real answer. I found it quite difficult to get the net send command working on Windows 7 and even if I could have it would have been enabled only for admin users.

So I have decided to write my own program to solve the problem. Using python I can write a program to check for messages on a common file (which I can store on a common harddrive which we have on our LAN). So the program will write from:192.168.23.44 to:192.168.23.45 Hello. Assuming the program is installed on both machines, I can ask the machines to poll this file every few seconds and pop-up a message if a message has been written for it, by searching for it in the to: field. If writing to a single file becomes an issue I will make multiple files which will act as inboxes for each of the computers on the LAN.

However, this approach is very inelegant. I don't suppose internet messengers, Google talk for instance, poll a server to check whether there are any new messages for the user. So my question is: what is the optimal way to write a LAN messenger program. Now that I think of it, I am looking for a minimalist approach. I will just put the program in the Startup folder of all the machines and it should come alive whenever any user logs in.

I was just able to configure the machine to respond to the ping command by making a new rule for the ICMPv4 protocol (ref: http://answers.microsoft.com/en-us/windows/forum/windows_7-networking/how-to-enable-ping-response-in-windows-7/5aff5f8d-f138-4c9a-8646-5b3a99f1cae6). I am guessing that answer lies in python and the ICMPv4 protocol, but I needed some direction.

Body:
I made a litle concept script with sockets.

See.

The server:

# Sockets server.
import socket

s = socket.socket()
s.bind(("localhost", 44000))
s.listen(1)

print("Connection Waiting...")
sc, addr = s.accept()
print("Connection Matched!")

while True:
    print("Waiting message...")
    received = sc.recv(128)
    print(type(received))
    a = received.decode('utf-8')
    print(type(a), len(a))
    if a == "quit":
        break
    print("Received Message:", a)
    sc.send(received)

print("Good bye!")

sc.close()
s.close()
a = input("Enter key to End:")

And this is the client script:

# Sockets client script
import socket, time

s = socket.socket()
print("Connecting to server...")
while True:
    try:
        s.connect(("localhost", 44000))
        break
    except:
        print("Retrying connection to server...")
        time.sleep(1)

print("Connection Matched!")

while True:
      keyboardInput = input("Enter the message: ")
      # s.send(bytes(message, 'UTF-8'))
      message = keyboardInput.encode('utf-8')
      s.send(message)
      print("Message sent!")
      r = s.recv( 128)
      a = r.decode('utf-8')
      print("Confirmation received message: ", a)
      if keyboardInput == "quit":
         break

print("Good bye")

s.close()

a = input("Enter key to End:")

Edit: to implement multi-threads.  In order to avoid the server blocks the flow while is waiting for incoming message.

# Example script with sockets and multi-threads
import socket, threading, time

a = ""
s = socket.socket()
s.bind(("localhost", 44000))
s.listen(1)

sc, addr = s.accept()

class MiThread(threading.Thread):   # Defines the class MiThread, subclass of Thread
    def __init__(self, sc):
        threading.Thread.__init__(self)

    def run(self):  # this method is the code of the thread, it will works when be called by .start() method
        received = sc.recv(128)
        print(type(received))
        a = received.decode('utf-8')
        print(type(a), len(a))
        print("Received Message:", a)
        return a

t = MiThread(sc)     # creates an object of class MiThread, subclass Thread
t.start()       # method start() calls to .run() method as a thread

# this code is for debugging, change it and put your own code
# I'll works in the main proccess while the thread is waiting for messages
for i in range(0, 60):
    time.sleep(1)
    print("Seconds: ",i)
    #sc.send(received)

print("Time out. Good bye!")

sc.close()
s.close()
a = input("Enter key to End:")

If you want to code a litle chat, you might to use this two utils: sockets and multi-threading.


问:
How do you respond to "Tell me a little bit about yourself." question in interviews?
I've been asked this in a few interviews. And it always catches me off guard.My professional and academic background are already in the resumé, which the interviewer has obviously looked at. What more to tell him/her? Should I start with my hobbies? I like gardening, or looking at NSFW pictures on reddit in my free time?

What and how do you answer to this specific question? Do you have a prepared answer for it? Am I wrong if I think this question is a bit silly?

UPDATE There have been a lot of great answers to this question. I'm in pickle which to choose as the 'correct' answer, because most of them are very insightful. I found a great writing on this subject matter. It's a bit crazy for my taste, but it's interesting:

How To Introduce Yourself… I Mean Practically

答:
Don't assume the interviewer knows your resumé inside out. Often, they'll be interviewing several people for the position and may have just had a cursory glance over your resumé before starting the interview.

With that in mind, and assuming this question comes early on in the interview, use this question as an opportunity to give a brief history of your career and why you are applying for the job, as well as what your stand-out skills or attributes are.

Your answer can effectively steer the course of the interview, giving the interviewer some "jumping off" points that could change what questions you get asked next. Focusing on your strengths with this answer means that it will be more natural to talk about what makes you great in answers to subsequent questions and not as something you have to try to shoehorn in to some other answer.


问:
Can someone explain the V Model process? Why is it different than the Waterfall model?
It seems the V Model is just the Waterfall Model with the bottom half of the Waterfall bent upwards to form a V. I don't see how it adds anything new.

From the diagrams, I also don't understand the flow. There are arrows pointing in all directions and I can't understand what comes first. Do we follow the V from the upper left, down to the bottom center then back up to the upper right? Or do we progress down the V doing everything higher before the item lower?

The internet is lacking a sufficient explanation of this model. It would be awesome if someone can explain it in true StackExchange form :)

答:
V-model is an extension of Waterfall model, so don't expect it to be hugely different.

Basically, you follow V-model from left to right, just like in Waterfall model. In Waterfall, you do requirements, design, implementation, verification and finally maintenance. In the same way, in V-model, you do requirements, design, implementation, verification and maintenance: same steps in both cases.

The major differences with Waterfall are the way it is presented and the emphasis on testing.

Representing the flow as V-shape helps making the difference between everything which comes prior to coding (requirements, architecture and design) and everything which follows coding (essentially testing). While tests are just one of five steps in Waterfall, it looks like practically half of the process in V-model.

The diagram in your question is a bit more complicated. What it tries to show is that, for example, system design step leads not only to the system design document, like Waterfall model would suggest, but also the system tests design, which will later help writing system tests. The diagram just puts even more emphasis on testing. Finally, doing system test design helps in architecture design (it would be awkward to do architecture design regardless system test design).

Searching what other explanations on the internet, I can't avoid quoting the following article by Bhakti Satalkar:

The main difference between waterfall model and V model is that in waterfall model, the testing activities are carried out after the development activities are over. On the other hand in V model, testing activities start with the first stage itself. In other words, waterfall model is a continuous process, while the V model is a simultaneous process. As compared to a software made using waterfall model, the number of defects in the software made using V model are less. This is due to the fact, that there are testing activities, which are carried out simultaneously in V model. Therefore, waterfall model is used, when the requirements of the user are fixed. If the requirements of the user are uncertain and keep changing, then V model is the better alternative.

This explanation is misleading. It would be true only if you replace “V-model” in the quote by any Agile method.

Unlike the article states, in V-model, testing is done after the coding; for example, see Wikipedia:

a common practical criticism of the V-Model is that it leads to testing being squeezed into tight windows at the end of development when earlier stages have overrun but the implementation date remains fixed.

While, in V-model, system test design follows system design without waiting until product implementation is done, this doesn't mean that tests themselves are performed before coding. The author confounds V-model with Agile approaches like Test Driven Development (TDD) in Extreme Programming (XP).


答: Keep in mind that from a theoretical perspective it's impossible to let sorting and finding be quicker than finding. To sort, you need to look at every element at least once to determine its place. To find, in the worst case scenario, you need to look at every element once (provided they are not sorted). Only when you're doing repeated searches, it may make sense to sort the elements first (a "startup fee") to have "cheaper" searches after that.</p>


答:
As others have said, binary search provides you with a high performance solution when your data is sorted, while find is slower but does not have that presorted constraint.

In addition it is important to note that to sort a vector you must either copy it and mutate it or simply mutate it. This is not only expensive but has side effects which may not match the semantics of your algorithm.

Additionally C++11 defines the new collections std::unordered_set and std::unordered_map which are by definition not compatible with binary search algorithms.


答:
In my opinion, for single value returning methods, null is far superior to returning an empty or default instance of a type.

Not only can default values mask errors but, depending on the complexity of the types in question, they can create complex, hard to document, and tightly coupled dependencies between functions. API producers and API consumers must maintain a consistent notion of which values represent erroneous results.

On the other hand, when it comes to collections, returning an empty collection is far superior to returning null, because the expectation of the caller of the method is that a variable number of results may be yielded, so an empty collection represents a conceptually valid result and is symmetric with the concept of the empty set in mathematics.

All that said, however, exceptions have their place, especially when a method returns void or unit or a collection or iterator.


答:
It is critically important to distinguish between methods that are expected to encounter error conditions, and those that are not. It is also just as important to have a clear understanding as to the contract for that method.

If the method is one that routinely encounters failure (such as say retrieving data from a database), then it needs a way to return success/failure as well as a way to return the data. My preference usually is to return true/false for the operation, use a separate call to retrieve the data and/or the status.

If the method is one that is not expected to encounter failure (such as returning an item from a collection by index), it should never return null. It should return a valid item, or raise an exception, or assert. Callers should never check the return result, because it will always be valid.

It may be convenient to return a default value rather than assert, but this should be reflected in the method contract, and there could be two methods (GetXxx and GetXxxOrDefault).

Widespread checking of return values against null is often symptomatic of deeper problems in the code. Advice found in more recent programming books is sound.

In response to comments, consider the case where a method is required to perform a lookup, computation, parse etc and failure is a routine occurrence. I dislike exceptions and the TryParse() form, because they break the flow of the code, while the FindOrDefault() form is a pain if default is a legal return value. I tend to prefer this wrapper:

```<code>public static U SafeLookup<T, U>(this Dictionary<T, U> dict, T key, U missing = default(U)) {
  U ret;
  if (dict.TryGetValue(key, out ret)) return ret;
  return missing;
}
</code>```

A value is always returned, and the value to return on error can optionally be specified.

Body:
It is critically important to distinguish between methods that are expected to encounter error conditions, and those that are not. It is also just as important to have a clear understanding as to the contract for that method.

If the method is one that routinely encounters failure (such as say retrieving data from a database), then it needs a way to return success/failure as well as a way to return the data. My preference usually is to return true/false for the operation, use a separate call to retrieve the data and/or the status.

If the method is one that is not expected to encounter failure (such as returning an item from a collection by index), it should never return null. It should return a valid item, or raise an exception, or assert. Callers should never check the return result, because it will always be valid.

It may be convenient to return a default value rather than assert, but this should be reflected in the method contract, and there could be two methods (GetXxx and GetXxxOrDefault).

Widespread checking of return values against null is often symptomatic of deeper problems in the code. Advice found in more recent programming books is sound.

In response to comments, consider the case where a method is required to perform a lookup, computation, parse etc and failure is a routine occurrence. I dislike exceptions and the TryParse() form, because they break the flow of the code, while the FindOrDefault() form is a pain if default is a legal return value. I tend to prefer this wrapper:

public static U SafeLookup<T, U>(this Dictionary<T, U> dict, T key, U missing = default(U)) {
  U ret;
  if (dict.TryGetValue(key, out ret)) return ret;
  return missing;
}

A value is always returned, and the value to return on error can optionally be specified.


问:
Auxiliary space complexity of map vs map!
I'm curious about the difference in space complexity between map and map! in ruby.

If I have the methods:

```<code>def mult_by_two(arr)
  arr.map {|i| i * 2 }
end

def mult_by_two!(arr)
  arr.map! {|i| i * 2 }
end
</code>```

While there's no explicit assignment in the first method, it's implicitly collecting the result of the map somewhere and is not operating in-place like the second method.

Would it be correct to say that the first has O(n) auxiliary space complexity while the second is O(1)? How should I represent them when looking at the auxiliary space complexity of a method?

答:
The answer is hidden in the source of the page Ruby-doc: Core Array

If one goes to Ruby-doc: Core Array#map or Ruby-doc: Core Array#map! and mouses over the block, they will see

Clicking the 'click to toggle source' then gives us the C source code that implements the method in the interpreter.

For map the code is:

collect = rb_ary_new2(RARRAY_LEN(ary));
for (i = 0; i < RARRAY_LEN(ary); i++) {
    rb_ary_push(collect, rb_yield(RARRAY_AREF(ary, i)));
}
```

<p>For <code>map!</code> the code is:</p>

<pre class="lang-c prettyprint-override"><code>rb_ary_modify(ary);
for (i = 0; i < RARRAY_LEN(ary); i++) {
    rb_ary_store(ary, i, rb_yield(RARRAY_AREF(ary, i)));
}
</code>```

One can clearly then see that map allocates a new array of the length of the original array and pushes the values that are used into this array while map! stores the value in the initial array.

Thus, you are correct - map uses O(n) auxiliary space while map! uses O(1) (none at all).

Body:
The answer is hidden in the source of the page Ruby-doc: Core Array

If one goes to Ruby-doc: Core Array#map or Ruby-doc: Core Array#map! and mouses over the block, they will see

Clicking the 'click to toggle source' then gives us the C source code that implements the method in the interpreter.

For map the code is:

collect = rb_ary_new2(RARRAY_LEN(ary));
for (i = 0; i < RARRAY_LEN(ary); i++) {
    rb_ary_push(collect, rb_yield(RARRAY_AREF(ary, i)));
}

For map! the code is:

rb_ary_modify(ary);
for (i = 0; i < RARRAY_LEN(ary); i++) {
    rb_ary_store(ary, i, rb_yield(RARRAY_AREF(ary, i)));
}

One can clearly then see that map allocates a new array of the length of the original array and pushes the values that are used into this array while map! stores the value in the initial array.

Thus, you are correct - map uses O(n) auxiliary space while map! uses O(1) (none at all).


答:
array.map: "Invokes the given block once for each element of self. Creates a new array containing the values returned by the block.".

array.map!: "Invokes the given block once for each element of self, replacing the element with the value returned by the block.".

The first allocates a new array of the same size, the second does not. The "space complexity" of both are exactly the same: O(1). The "auxiliary space usage" of map is O(N), for map! is O(1).

The main reason to use map! is to avoid the extra allocation which eventually has to be garbage collected.

Title: Auxiliary space complexity of map vs map!

Body:
I'm curious about the difference in space complexity between map and map! in ruby.

If I have the methods:

```<code>def mult_by_two(arr)
  arr.map {|i| i * 2 }
end

def mult_by_two!(arr)
  arr.map! {|i| i * 2 }
end
</code>```

While there's no explicit assignment in the first method, it's implicitly collecting the result of the map somewhere and is not operating in-place like the second method.

Would it be correct to say that the first has O(n) auxiliary space complexity while the second is O(1)? How should I represent them when looking at the auxiliary space complexity of a method?


问:
Updating an Entity through a Service
I'm separating my software into three main layers (maybe tiers would be a better term):

Presentation ('Views')

Business logic ('Services' and 'Repositories')

Data access ('Entities' (e.g. ActiveRecords))

What do I have now?

In Presentation, I use read-only access to Entities, returned from Repositories or Services, to display data.

```<code>$banks = $banksRegistryService->getBanksRepository()->getBanksByCity( $city );

$banksViewModel = new PaginatedList( $banks ); // some way to display banks;
                                               // example, not real code
</code>```

I find this approach quite efficient in terms of performance and code maintanability and still safe as long as all write operations (create, update, delete) are preformed through a Service:

```<code>namespace Service\BankRegistry;

use Service\AbstractDatabaseService;
use Service\IBankRegistryService;
use Model\BankRegistry\Bank;

class Service
    extends AbstractDatabaseService
    implements IBankRegistryService
{
    /**
     * Registers a new Bank
     *
     * @param string $name                  Bank's name
     * @param string $bik                   Bank's Identification Code
     * @param string $correspondent_account Bank's correspondent account
     *
     * @return Bank
     */
    public function registerBank( $name, $bik, $correspondent_account )
    {
        $bank = new Bank();

        $bank
            -> setName( $name )
            -> setBik( $bik )
            -> setCorrespondentAccount( $correspondent_account );

        if( null === $this->getBanksRepository()->getDefaultBank() )
            $this->setDefaultBank( $bank );

        $this->getEntityManager()->persist( $bank );

        return $bank;
    }

    /**
     * Makes the $bank system's default bank
     *
     * @param Bank $bank
     * @return IBankRegistryService
     */
    public function setDefaultBank( Bank $bank )
    {
        $default_bank = $this->getBanksRepository()->getDefaultBank();

        if( null !== $default_bank )
            $default_bank->setDefault( false );

        $bank->setDefault( true );

        return $this;
    }
}
</code>```

Where am I stuck?

I'm struggling about how to update certain fields in Bank Entity.

Bad solution #1: Making a series of setters in Service for each setter in Bank; - seems to be quite reduntant, increases Service interface complexity and proportionally decreases it's simplicity - something to avoid if you care about code maitainability. I try to follow KISS and DRY principles.

Bad solution #2: Modifying Bank directly through it's native setters; - really bad. If you'll ever need to move modification into the Service, it will be pain. Business logic should remain in Business logic layer. Plus, there are plans on logging all of the actions and maybe even involve user permissions (perhaps, through decorators) in future, so all modifications should be made only through the Service.

Possible good solution: Creating an updateBank( Bank $bank, $array_of_fields_to_update) method; - makes the interface as simple as possible, but there is a problem: one should not try to manually set isDefault flag on a Bank, this operation should be performed through setDefaultBank method. It gets even worse when you have relations that you don't want to be directly modified.

Of course, you can just limit the fields that can be modified by this method, but how do you tell method's user what they can and cannot modify? Exceptions?

答:
The decision I've come up with

I've made setDefaultBank a protected method and removed it from IBankService public interface. I've also created an updateBank( $bank, array $fields ) method that filters the $fields array and calls corresponding setters on Bank. If a default field is encountered, it is checked to be equal to true and setDefaultBank is called. Any invalid elements in $fields cause an \InvalidArgumentException to be thrown.

```<code>/**
 * Updates Bank fields
 *
 * @param int|Bank $bank    Bank ID or instance
 * @param array    $fields  Associative array of Bank fields
 *
 * @return IBankRegistryService
 * @throws \InvalidArgumentException
 */
public function updateBank( $bank, array $fields )
{
    if(    false === $bank instanceof Bank
        && 0 < intval( $bank ) )
    {
        /** @var $bank Bank */
        $bank = $this->getBanksRepository()->find( $bank );
    }
    else
        throw new \InvalidArgumentException( '$bank should be either an ID or a Bank instance.' );

    foreach( $fields AS $key => $value )
    {
        switch( $key )
        {
            case 'bik':
                $bank->setBik( $value );
                break;

            case 'name':
                $bank->setName( $value );
                break;

            case 'correspondent_account':
                $bank->setCorrespondentAccount( $value );
                break;

            case 'default':
                if( !$value )
                    throw new \InvalidArgumentException( 'Property "default" can only be equal to true' );

                $this->setDefaultBank( $bank );

                break;

            default:
                throw new \InvalidArgumentException( 'Cannot change "' . $key . '" property of a Bank' );
        }
    }

    return $this;
}
</code>```

Title: Updating an Entity through a Service

Body:
The decision I've come up with

I've made setDefaultBank a protected method and removed it from IBankService public interface. I've also created an updateBank( $bank, array $fields ) method that filters the $fields array and calls corresponding setters on Bank. If a default field is encountered, it is checked to be equal to true and setDefaultBank is called. Any invalid elements in $fields cause an \InvalidArgumentException to be thrown.

/**
 * Updates Bank fields
 *
 * @param int|Bank $bank    Bank ID or instance
 * @param array    $fields  Associative array of Bank fields
 *
 * @return IBankRegistryService
 * @throws \InvalidArgumentException
 */
public function updateBank( $bank, array $fields )
{
    if(    false === $bank instanceof Bank
        && 0 < intval( $bank ) )
    {
        /** @var $bank Bank */
        $bank = $this->getBanksRepository()->find( $bank );
    }
    else
        throw new \InvalidArgumentException( '$bank should be either an ID or a Bank instance.' );

    foreach( $fields AS $key => $value )
    {
        switch( $key )
        {
            case 'bik':
                $bank->setBik( $value );
                break;

            case 'name':
                $bank->setName( $value );
                break;

            case 'correspondent_account':
                $bank->setCorrespondentAccount( $value );
                break;

            case 'default':
                if( !$value )
                    throw new \InvalidArgumentException( 'Property "default" can only be equal to true' );

                $this->setDefaultBank( $bank );

                break;

            default:
                throw new \InvalidArgumentException( 'Cannot change "' . $key . '" property of a Bank' );
        }
    }

    return $this;
}


问:
Alternative to SIP, voice communication in Android
Is it exists any alternative to SIP protocol? I want implement voice & video chat option in my application. I don't want use SIP, because I need only simple communication without call for landlines etc. It seems to me, it maybe doing with sockets, and audio records, but I'm not sure. I care about the fact that many people (for example 1000) could simultaneously carry on a conversation. Is it possible on regular server? Is it at all possible without a server?

Best regards.

答:
The SIP protocol only deals with letting two communication partners find each other and negotiate audio/video capabilities. Once the communication partners know how to find each other, other protocols (like RTP) take over for the actual audio/video transfer.

So, if instances of your application can already reach each other, you can use those existing communication facilities to negotiate audio/video capabilities and establish a communication channel for the audio/video transfer.

If instances of your application can't reach each other, then you need to implement SIP or roll your own variant of it.

One of the ideas behind SIP is that, once communication has been established, the server does not have to remain in the communication path. This allows for a relatively lightweight server to serve a large number of calls.


问:
Concerning JavaScript prototype and the initial constructor function
I am going through a tutorial on OOP in JavaScript (javascriptissexy.com using OOP in JS: What you Need to know).

The instructor is explaining the Constructor/Prototype pattern of object creation. I understand what is going on, but I have a burning question that he doesn't answer!

We begin like this:

```<code>function User(name, email) {
    this.name = name,
    this.email = email,
    this.scores = [],
    this.etc = etc
}
</code>```

I get it, and now every var xxx = new User("name", "email") will have an xxx.name, xxx.email, xxx.scores, etc.

But now, we overwrite the prototype:

```<code>User.prototype = {
    constructor: User;
    saveScore: function(...){...},
    changeEmail: function(...){...},
    showNameAndScore: function(...){...}
}
</code>```

Now every var xxx = new User(...) will inherit saveScore, changeEmail, and showNameAndScore methods.

I am brand new, but from what I understand, I could have included these functions in the begining:

```<code>function User(...) {
    this.name = name,
    this.saveScore = function(...) {...},
    ...
}
</code>```

Instead of editing the prototype right away.

I am waiting for the author to tell me that we include these functions in the prototype because they will be exact carbon copies which the user can't edit, and therefore only need to define them once (in the prototype) rather than on every instance of a User.

Or is he just trying to demonstrate the different flavors of inheritance?

Thank you ahead of time!

答:
The constructor is used to create a different state for each new object. You want a different state for each User object, but you want methods like saveScore to be shared among the User objects. Placing the saveScore method in the prototype is one way to share the method between objects.

An aside, one should not override the prototype: User.prototype = {...}, one should add to the prototype: User.prototype.saveScore = function(...){...}.