问:
The importance of Design Patterns with Javascript, NodeJs et al
With Javascript appearing to be the ubiquitous programming language of the web over the next few years, new frameworks popping up every five minutes and event driven programming taking a lead both server and client side:

Do you as a Javascript developer consider the traditional Design Patterns as important or less important than they have been with other languages / environments?.

Please name the top three design patterns you, as a Javascript developer use regularly and give an example of how they have helped in your Javascript development.

答:
Design patterns are taught in design classes for CS. They aren't essential, but really helpful if you can find analogous situations to have a solution that has been thought through.

It also allows programmers to communicate more easily. You can talk to your coworker in terms of the patterns as well. If you say here I have my Observer, then it is pretty well understood what is kind of going on.

People will naturally come up with solutions that will fit into a design pattern on their own, but the design patterns help to define terminology and standard ideas that can be helpful.

There's nothing super remarkable about the patterns, the nicest thing is that they are ideas that are canonized and defined in ways that are repeatedly useful.

OwnerDisplayName: Lewis


问:
Can the user not manipulate html elements which are disabled for non-permitted user
With todays browser extensions/tools is it not easily possible for a user to edit the html/css settings of a website and so enable some disabled buttons etc... to gain access to not permitted areas?</p>

答:
Assuming that your statement of enabling previously disabled buttons or links through the browser dev tools means that the user then gets access to an area of the application they otherwise wouldn't have, you're referring to what's known as an authorization vulnerability.  In this case, the security is reliant on the presentation layer to enforce it, which as you know, is easy to circumvent.

The best defense against this is to perform your authorization in both the presentation layer (browser) and the business layer (server).  Always validate and authorize user requests on the server.  Doing so in the browser is usually recommended to improve the user experience (i.e., don't show me links to functions I can't do because it's just visual noise to parse through) and it hides functionality that would otherwise be inadvertently communicated.  Only show what you have to, but validate and authorize everything on the server.

ContentLicense: CC BY-SA 3.0


问:
TDD: Am I doing it right?
I'm a new programmer (only been learning for about a year) and in my goal to become better at it I have just recently learned about TDD. I wanted to get into the habit of using it since it seems very helpful. I wanted to check and make sure I'm using it correctly.

What I'm doing:

Think of a new method I need.

Create a test for that method.

Fail test.

Write method.

Pass test.

Refactor method.

Repeat.

I'm doing this for EVERY method I write, are there some I shouldn't bother with? Later on I usually think of a way to test my already existing methods in a different way or situation. Should I make these new tests I think of, or since each method already has a test of their own should I not bother? Can I be OVER testing my code I guess is my main concern in asking this.

EDIT

Also, this was something I was just wondering. When doing something like making a GUI, would TDD be necessary in that situation? Personally, I can't think of how I would write tests for that.

答:
My opinion on TDD is that the tooling has create a world of 'point and click' style developers. Just because the tools create a test stub for each method doesn't mean you should be writing tests for every method. Some people are 'renaming' TDD as BDD (behaviour driven development) where the tests are much larger-grained and intended to test the behaviour of the class, not each fiddly little method.

If you design your tests to test the class as its intended to be used, then you start to gain some benefits, especially as you start to write tests that exercise a bit more than each method, especially when you start to test the interaction of those methods. I suppose you could think of it as writing tests for a class, rather than methods. In any case, you must still write 'acceptance tests' that exercise the combination of methods to make sure there are no contradictions or conflicts in how they are used together.

Don't get TDD confused with testing - it's not. TDD is designed so that you write code to exercise your requirements, not to test the methods. Its a subtle but important point that's often lost on people who blindly write test code for every method. Its that you should be writing tests that make sure your code does what you want it to do, not that the code that you wrote works like its supposed to.

There's some good links to the right about BDD v TDD. Check them out.

Title: TDD: Am I doing it right?


答:
What you are describing as a workflow isn't in my opinion the Spirit of TDD.

The synopsis of Kent Becks book on Amazon says:

Quite simply, test-driven development is meant to eliminate fear in
  application development. While some fear is healthy (often viewed as a
  conscience that tells programmers to "be careful!"), the author
  believes that byproducts of fear include tentative, grumpy, and
  uncommunicative programmers who are unable to absorb constructive
  criticism. When programming teams buy into TDD, they immediately see
  positive results. They eliminate the fear involved in their jobs, and
  are better equipped to tackle the difficult challenges that face them.
  TDD eliminates tentative traits, it teaches programmers to
  communicate, and it encourages team members to seek out criticism
  However, even the author admits that grumpiness must be worked out
  individually! In short, the premise behind TDD is that code should be
  continually tested and refactored.

Practical TDD

Formal automated Testing, especially Unit Testing every method of every class is just as bad an anti-pattern and not testing anything. There is a balance to be had. Are you writing unit tests for every setXXX/getXXX method, they are methods as well!

Also Tests can help save time and money, but don't forget that they cost time and money to develop and they are code, so they cost time and money to maintain. If they atrophy from lack of maintenance then they become a liability more than a benefit.

Like everything like this, there is a balance which can't be defined by anyone but yourself. Any dogma either way is probably more wrong that correct.

A good metric is code that is critical to the business logic and subject to frequent modification based on changing requirements. Those things needs formal tests that are automated, that would be a big return on investment.

You are going to be very hard pressed to find many professional shops that work this way either. It just doesn't make business sense to spend money testing things that will for all practical purposes never change after a simple smoke test is preformed. Writing formal automated unit tests for .getXXX/.setXXX methods is a prime example of this, complete waste of time.

It is now two decades since it was pointed out that program testing
  may convincingly demonstrate the presence of bugs, but can never
  demonstrate their absence. After quoting this well-publicized remark
  devoutly, the software engineer returns to the order of the day and
  continues to refine his testing strategies, just like the alchemist of
  yore, who continued to refine his chrysocosmic purifications.

-- Edsger W. Djikstra.  (Written in 1988, so it's now closer to
  4.5 decades.)

See also this answer.

Title: TDD: Am I doing it right?

Body:
I'm a new programmer (only been learning for about a year) and in my goal to become better at it I have just recently learned about TDD. I wanted to get into the habit of using it since it seems very helpful. I wanted to check and make sure I'm using it correctly.

What I'm doing:

Think of a new method I need.

Create a test for that method.

Fail test.

Write method.

Pass test.

Refactor method.

Repeat.

I'm doing this for EVERY method I write, are there some I shouldn't bother with? Later on I usually think of a way to test my already existing methods in a different way or situation. Should I make these new tests I think of, or since each method already has a test of their own should I not bother? Can I be OVER testing my code I guess is my main concern in asking this.

EDIT

Also, this was something I was just wondering. When doing something like making a GUI, would TDD be necessary in that situation? Personally, I can't think of how I would write tests for that.


答:
You're very close. Try thinking in this slightly different way.

Think of a new behaviour I need.

Create a test for that behaviour.

Fail test.

Write new or extend existing method.

Pass test.

Refactor code.

Repeat.

Don't automatically create getters and setters for every property. Don't think of a whole method and write the test(s) to cover all functionality. Try to encapsulate the properties inside the class and write methods to provide the behaviour that you need. Let your methods evolve into a good design instead of trying to plan them up-front. Remember that TDD is a design process, not a testing process. The advantage it has over other design processes is leaving a stream of automated regression tests behind, rather than a piece of paper you throw in the bin.

Also, remember Uncle Bob's three rules of TDD.

You are not allowed to write any production code unless it is to make a failing unit test pass.

You are not allowed to write any more of a unit test than is sufficient to fail; and compilation failures are failures.

You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

Title: TDD: Am I doing it right?


问:
Making an internship most effective, useful and fun for both parties
We're currently interviewing few candidates for an internship, which is a really new experience for us as a company and for me personally as a team lead/manager. </p>

<p>What would be the most effective and useful, yet fun approach for both sides here? How do we 'integrate' an intern into our development team and workflow without much disruption in such a way that he or she could be learning and yet be helpful? </p>

答:
If they are in college (junior going to senior year), treat them like an entry-level employee in regards to work and challenges.

Give them real work with clear objectives that have tangible results.

Whether this means having them work on documentation, bug fixes or something else make sure you're getting something in return.  If you can afford it, have someone mentor this intern.  They are going to most likely be really green - show them the ropes/give them experience they won't get in the classroom/etc.

Include them in design reviews , so they can see how the process works.  Include them in code-reviews so they see how that goes.  And most importantly have code reviews on their stuff.


问:
Origin of structures and classes
What design and implementation issues did programmers have to solve when they decided first to use structures and classes?

When did this happened and who were the pioneers behind these ideas?

Note, this is double question, because structures and classes are related. I realize that structures are quite older than classes. It would be great if the answer would talk separately about both of them and cite some sources.

答:
The idea of a structure is to group together a collection of variables into a single container. E.g. if you have three coordinates

```<code>int x;
int y;
int z;
</code>```

you might want to see them as a unit of data and group them together:

```<code>struct point
{
    int x;
    int y;
    int z;
};
</code>```

You can see this as a way to modularize your data.
Now you can define variables containing all three values in one unit:

```<code>struct point p1, p2;
</code>```

In procedural programming, you have procedures or functions that manipulate data and, in particular, structures, e.g.

```<code>void shiftX(struct point *p, int offset);
</code>```

You can call the function on a struct by passing it as an argument:

```<code>shiftX(&p1, -10);
</code>```

The step from structs to classes is to say that procedures / functions should be grouped together with data into units: like structs classify entities that have the same structure, classes classify entities that have the same structure and operations.

So now you can write:

```<code>class Point
{
  public:
    void shiftX(int offset);

    int x;
    int y;
    int z;
 };
</code>```

and then:

```<code> Point p;

 ...

 p.shiftX(-10);
</code>```

In this way it is easier to group together operations that work on the same kind of data. E.g. you can group together all operations that act on points
in the class definition, instead of having them scattered over your code as
functions that have one or more parameters of type point.

Additionally, you can refine both structure and behaviour by using inheritance.

Summarizing: structs are a concept that allows to organize / modularize data. Classes allow to organize / modularize both data and operations.

Title: Origin of structures and classes

Body:
The idea of a structure is to group together a collection of variables into a single container. E.g. if you have three coordinates

int x;
int y;
int z;

you might want to see them as a unit of data and group them together:

struct point
{
    int x;
    int y;
    int z;
};

You can see this as a way to modularize your data.
Now you can define variables containing all three values in one unit:

struct point p1, p2;

In procedural programming, you have procedures or functions that manipulate data and, in particular, structures, e.g.

void shiftX(struct point *p, int offset);

You can call the function on a struct by passing it as an argument:

shiftX(&p1, -10);

The step from structs to classes is to say that procedures / functions should be grouped together with data into units: like structs classify entities that have the same structure, classes classify entities that have the same structure and operations.

So now you can write:

class Point
{
  public:
    void shiftX(int offset);

    int x;
    int y;
    int z;
 };

and then:

 Point p;

 ...

 p.shiftX(-10);

In this way it is easier to group together operations that work on the same kind of data. E.g. you can group together all operations that act on points
in the class definition, instead of having them scattered over your code as
functions that have one or more parameters of type point.

Additionally, you can refine both structure and behaviour by using inheritance.

Summarizing: structs are a concept that allows to organize / modularize data. Classes allow to organize / modularize both data and operations.


问:
Logic required to solve a problem relating to location of objects
I have raised a question on dba.stackexchange.com but as the heart of my question is in fact to do with logic I have raised a more general representation of my issue here. I think it is the right place, apologies if not.

I have a number of objects that are read and written to in a set sequence. I also have four locations in which I can store these objects. These objects vary in size but for the purposes of simplicity I have rated them 1 to 3 with 3 being the largest. Location of objects is fixed e.g. objects can not be moved in between sequence steps

I have a table which details the sequence of the process. It has three columns: Sequence, Source, Destination. Processes can and do run in parallel and therefore sequence is not a unique identifier however should one be required it can be considered to be in place.

In an ideal world no object should be located in a way that would result in no object required for a sequence step being co-located with another. Of course this is highly unlikely and instead I am looking for a best solution as opposed to a perfect one.

I have therefore considered that the potential locations may be best ranked as followed.

All objects for a sequence located separately.

Source and destination objects for sequence located separately.

Objects located anywhere

Given that each object has a size I also considered perhaps multiplying the location rank by the size and therefore giving the locations a score. Then based on this I could find the best solution by looking at it's total score.

Does anyone have any suggestions or perhaps addressed a similar problem in the past?

Any help input is greatly appreciated.

答:
So, I'm still not sure that you have enough constraints to force a particular solution, but here's my best guess.  From the follow-up comment on the DBA post, I think your real constraint is trying to minimize IO for any particular step of the operation and maximize overall IO throughput.

Starting out, I'll presume we only have Object (table) A on volume 1.

Future steps will generate:

A => B on vol 2

A + B => C on vol 3

A + C => D on vol 4

It's trivial to assign Objects A -> D to volumes 1 -> 4, and they'll never need to move.  I suspect you've got a number of sets like this, so it's the scale that's complicating things.

Since you're using size of the object as your score, I would recommend you assign each volume a maximum score that it can handle at once.  Size of the object will be coupled to the time of IO.  For the sake of my solution, A & B = 1, C = 2, D = 3.

Allocate the sets with the simple mapping until you hit a volume that is completely IO bound.  The 4th volume handling Ds will max out first, with the Cs volume coming in pretty close behind.  At that point, rework the ordering of the volumes to objects.  For this "fill-in" objects, Ds will go to vol 1 or 2, Bs & Cs will end up going to the other of vols 1 or 2, and reads from A will be on vol 3.  I didn't add the numbers up, so my allocation on the fill-ins may be off.

At this point, you've pretty much maxed out the capacity of as many drives as you can.  If you had more volumes, you could extend the model out so you would work the Nth, N-1, N-2 cases.  That's more of an academic exercise for your case, I think.

I'm assuming you have more to move than you have IO bandwidth available, otherwise I'm not sure why you'd worry about this sort of round-robin allocation.


问:
Means for (legit) cross-site scripting
Are there good means for allowing scripts from two or more domains to collaborate in the same browser page? I want to create an extensible platform, where I provide the model and some views, but also allowing third parties to create their own views as well. The idea is that all model manipulation will be done through its API, and only the model will communicate to the (main) server, but users will be allowed to include scripts from other domains that also use that API (those scripts might "call home" if they want to though).

I know many sites already do that, for instance when they use a CDN to provide libraries like jQuery. However, I also recall reading that those libraries had to be "tweaked" somehow so they won't be mistaken by XSS attacks, though I couldn't find more info on the subject. I have only superficial knowledge of how browsers isolate contents for different domains, and to what extent that isolation occurs, so some pointers in that direction would be very welcome.

I'm also aware of the method of using iframes to load "less-than-trusted" contents, and it seems that communication between the main page and its iframes is quite straightforward. I'd rather not use that method, but will do if there are good security benefits of doing so. However, I'm unsure if that's the case, since the iframe can call arbitrary methods on the parent page... (Edit: from what I understood of Florian Margaine's comment, the method in the linked question only works for same-origin iframes, is that correct? In that case, I can see the security benefits now) Can anyone with experience on the subject tell me how it works?

These are the only options I know of, other suggestions are welcome too. I'd also like to note that, while there must be some level of trust between the user and the third party providing the script (since its very purpose is manipulating the model owned by that user), each user will be free to choose extensions at his leisure (i.e. the available scripts won't be restricted to ones I previously evaluated and endorsed), so any means to mitigate security problems to the users are also welcome.

Edit: Let me clarify the question a bit. The goal here is not to make HTTP requests to other domains, merely to have a better control of what the different scripts do to the same page. From what I understood so far of the same origin policy, different pages can not communicate to each other unless they come from the same domain, but scripts in the same page but coming from different domains can do whatever they want. Is that correct? (if it is, then I guess my question is moot...)

答:
You can use JSONP. Its not so hard to write a little function yourself, here is a little example from one of my sites;</p>

```<code>function ecbCreateScript(url, callback) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    script.onreadystatechange = loadEcbForm;
    script.onload = loadEcbForm;

    // fire the loading
    head.appendChild(script);
}
</code>```

Title: Means for (legit) cross-site scripting

Body:
You can use JSONP. Its not so hard to write a little function yourself, here is a little example from one of my sites;

function ecbCreateScript(url, callback) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    script.onreadystatechange = loadEcbForm;
    script.onload = loadEcbForm;

    // fire the loading
    head.appendChild(script);
}


问:
When to use shared libraries for a web framework?
tl;dr:

I've found myself hosting a bunch of sites running on the same web framework (symfony 1.4). Would it be helpful if I moved all of the shared library code into the same directory and shared it across the sites?

more

I see some advantages to this:

Each site takes up less disk space

Library updates (an unlikely scenario) can take place across all sites

I also see some disadvantages, mostly in terms of a single point of failure and the inability to have sites using different versions of the framework.

My real concern, though, is performance. I hypothesize that I will see a performance increase, since the PHP code will already be cached for all sites when they call the framework. Is this a correct hypothesis?

答: My guess is that the loss in flexibility could exceed the benefit of performance increase, if any. The need of a sudden upgrade or downgrade of some components can happen at any time and with common libraries you'd be greatly limited in this sense. Moreover, any site has its own life and should then be kept completely separate from others (through chroots, virtual machines, jails) for security reasons.</p>


问:
How do I determine if my code is optimized?
I am only developer working on a project. The functionality that I have coded works to expectations(desired result) but since I am the only one I don't know if I can do anything better to it. How do I determine if my code is optimized (I want to increase the performance of some features)?

One thing that comes into mind is Code Review but there is no one free over here to review my code. I just keep on trying with alternate logic but at times things get stagnant and really dirty. Is there any other possible way?

答:
There hardly exists any code that can't be made faster.
As this post shows, no matter what you do to speed up the code, there is almost always something more you could do.
That's because changes that initially would not have been much help become a lot more significant after other sources of slowness have been removed.

Where did you get the idea that code reviewers could tell you how to make code faster?
I often get asked how to make code fast, but that's like asking a doctor to diagnose without examining the patient. Even eyeballing the code is of little use.

The fundamental skill of performance tuning is diagnosis.
Anybody who suggests otherwise is giving you a WAG.
Here's how I do it.


问:
What is the acceptable error margin when estimating a project duration?
The company where I work is aiming to have a 10% maximum error margin.They expect analysts to not miss the estimate by more or less than 10%.

I don't know what to think about it, since I got nothing to compare it to.

What could be a good baseline to measure if we are estimating too wrong, for more or less?
How much (in %) do you think is okay to to miss?

答:
I'd be very hesitant about any sort of "target error margin" because it really depends on the project.  If you are trying to estimate how long it is going to take to install, configure, and customize a new CRM system where no one is quite sure what sorts of customizations are going to be necessary and what sort of business process changes will be needed and the company has no history of similar large projects, your error margin ought to be pretty large (i.e. you might guess that it will take 18 months +/- 50% and quote 9-27 months).  As the project goes forward, the specifications get clearer, decisions get made about business processes, your developers get more comfortable, etc. those error margins should get tighter.  If you are trying to estimate how long it is going to build the 101st basic ecommerce site when you've got a good history from the first 100, you would expect to be able to give a much more accurate estimate.  Most projects, though, are going to fall somewhere in the middle.

Now, if you are quoting a single number rather than a range, the answer is probably to start quoting the range so that the person doing the estimating can specify how accurate they expect their estimate to be.


答:
You should test every public method.

The catch here is that if your public methods are very small you are probably exposing too much information. The common practice of exposing every property as getXXX() actually breaks encapsulation.

If your public methods are actually behavior of the class, then you should test them. If not, they are not good public methods.

EDIT:
pdr's answer is much more complete than mine.

Title: TDD: Am I doing it right?


答:
Unless you are estimating something very similar to that which you and your co-workers have done before, +/-10% is ridiculously optimistic.  Your management either doesn't have a lot of experience with software, or they're not aware of Large Limits to Software Estimation.  That paper has some accompanying supporting material, and a lot of punditry can be found.

Let's examine a far simpler system than a typical software project: Rubik's Cube. You can solve any position in 20 moves, max.  But since you're estimating, you can only look at a given cube for a few minutes before giving the solution.  Can you give a good estimate? No, sometimes estimating a process takes longer than doing the process.

Another simple system: Pinocchio.  A wooden automaton, his nose-piece grows when he utters a lie.  What happens when Pinocchio is at rest, and then says "My nose is growing"? Some systems aren't amenable to prediction, they're undecidable.

These two problems are built-in to most software systems.  Because of that, you'll never get estimates close to +/-10%.

My advice is to give a heavily padded estimate, work like a slave to get the project done as fast as you can, and then look busy until you're within 10% under or over.  At that point, announce a spectacular success.

Title: What is the acceptable error margin when estimating a project duration?

Body:
The company where I work is aiming to have a 10% maximum error margin.They expect analysts to not miss the estimate by more or less than 10%.

I don't know what to think about it, since I got nothing to compare it to.

What could be a good baseline to measure if we are estimating too wrong, for more or less?
How much (in %) do you think is okay to to miss?


问:
Should the most recent date be named 'start' or 'end'?
So I have a function that takes two dates.  The SQL query gets all the results between the two dates.  I currently have my function setup as such:

```<code>function myFunc(start, end)
</code>```

Where start is the most recent date and end is the oldest date.

Is this intuitive/correct or is there another naming/ordering convention I should be using?

答:
You can create a wrapping type (class or structure) called DateInterval. A DateInterval is something that is defined by a start date (earliest) and an end date (latest).

Then, you change your original function to receive a single argument: the DateInterval.

I would say this leads to a more natural design - those two dates to not make sense without each other. It also reduces function argument count. Also, I think it reduces the ambiguity, since most people will probably recognise a DateInverval as a  pair.


答:
Few things to add to other's responses:

There is such a thing as over testing. You want to make sure your unit tests overlap as little as possible. There's no point of having multiple tests verify the same conditions in the same piece of code. On the other hand, when you refactor your production code and you have many tests that overlap that section, you will have to go back and fix all those tests.  Whereas if they do not overlap, then one change will at most break only one test.

Just because you thought of a better way of writing a test, I would not go back there and start rewriting it. This is going back to the individuals who keep writing and rewriting the same class/function because they try to make it perfect.  It will never be perfect, so move on.  When you discover a better method, keep it in the back of your mind (or add to comments of the test). Next time you are in there, and you see immediate benefit of switching to the new way, that's the time to refactor.  Otherwise, if the feature is done and you moved on and everything works, leave it working.

TDD focuses on delivering immediate value, not simply making sure every function is testable. When you add functionality, start by asking "what does the client need". Then define an interface to give the client what it needs.  Then implement whatever it takes to make the test pass. TDD is almost like testing use case scenarios (including all the "what-ifs"), rather than simply coding up public functions and testing each one.

You asked about testing GUI code. Look up "Humble Dialog" and "MVVM" patterns. The idea behind both of these is that you create a set of "view model" classes, that don't actually have UI-specific logic.  However, these classes will have all the business logic that typically is part of your UI and these classes should be 100% testable. What's left is a very thin UI shell and yes, typically that shell is left without test coverage, but at that point it should have almost no logic.

If you have a large portion of existing code, as few others suggested, you shouldn't start adding unit tests absolutely everywhere. It'll take you forever and you won't get benefit from adding unit tests to 80% of classes which are stable and will not change in the near (or not so near) future.  However, for new work, I do find using TDD development with ALL code to be extremely beneficial. Not only do you end up with a suite with automated tests when you are done, but actual development has huge benefits:

By considering testability, you will write code which is less coupled and more modular

By considering your public contract before anything else, you will end up with public interfaces which are much cleaner

As you are writing code, verifying new functionality takes milliseconds compared to running your entire application and trying to force execution down the right path.  My team still releases error handling code which has not been even executed ONCE just because they couldn't get the right set of conditions to happen. It is amazing how much time we waste when later on in QA those conditions do happen. And yeah, a lot of this code is what someone would've considered "not area for a lot of change in the future once smoke testing is done".

Title: TDD: Am I doing it right?


问:
Better use on the name of variables
I have a method that looks like this:

```<code>Public Function NormalizeStreetAddress(country As Namespace.Country,
                                       streetAddress As Namespace.StreetAddress) _
                                   As Namespace.StreetAddress

        Dim _streetAddress As New Namespace.StreetAddress = streetAddress

        If My.Settings.Streeteable = True Then
            Dim _AddressCustom As New Namespace.AddressCustom
            _streetAddress = _AddressCustom.NormalizeStreetAddress(country, streetAddress)
        End If
        Return _streetAddress
End Function
</code>```

I receive a streetAddress object, but inside the method I need to use another streetAddress object which I called _streetAddress — is that following the standard? A friend of mine told me that object names such as _yourNameObject are for global variables, but I can't find info about this and I want to make this method more readable.

答:
The names of the variables must be explicit, i.e., when possible, the reader must know what is the variable just by looking at its name.

If you have both streetAddress and _streetAddress in the same code, there is a huge problem. Since the two variables are referring to something different, they should have different names.

Keeping both names is not only confusing, but extremely error prone. Would you be able to immediately make the difference between those two variables in six months when modifying some code in the middle of the method? If you type the wrong name and the program fails, would you be able to immediately see in the debugger where the error comes from?

What about:

```<code>Public Function NormalizeStreetAddress(country As Namespace.Country,
                                       streetAddress As Namespace.StreetAddress) _
                                       As Namespace.StreetAddress

    If My.Settings.Streeteable = True Then
        Dim _AddressCustom As New Namespace.AddressCustom
        Return _AddressCustom.NormalizeStreetAddress(country, streetAddress)
    Else
        Return streetAddress
    End If
End Function
</code>```

Title: Better use on the name of variables

Body:
The names of the variables must be explicit, i.e., when possible, the reader must know what is the variable just by looking at its name.

If you have both streetAddress and _streetAddress in the same code, there is a huge problem. Since the two variables are referring to something different, they should have different names.

Keeping both names is not only confusing, but extremely error prone. Would you be able to immediately make the difference between those two variables in six months when modifying some code in the middle of the method? If you type the wrong name and the program fails, would you be able to immediately see in the debugger where the error comes from?

What about:

Public Function NormalizeStreetAddress(country As Namespace.Country,
                                       streetAddress As Namespace.StreetAddress) _
                                       As Namespace.StreetAddress

    If My.Settings.Streeteable = True Then
        Dim _AddressCustom As New Namespace.AddressCustom
        Return _AddressCustom.NormalizeStreetAddress(country, streetAddress)
    Else
        Return streetAddress
    End If
End Function


答:
A good baseline would be one based upon real data you have collected.

The first step to doing this is recording all estimates. The second step is recording the actual results. Be honest, don't be tempted to 'self-adjust' the actual. Gather enough of this information and you have some data to statistical base how good your estimates are. Note, this can/will vary wildly based upon who did the estimation and who the work. Only by doing this can you be reasonably expected to give a 'margin of error' that is anything other pure rubbish.

It doesn't stop there either; analyzing what causes estimates to be off can help improve the accuracy of your future estimates. Note: They still remain estimates, and as such, are only estimates.

Estimation also doesn't finish after the first estimate; this is something that can be adjusted as the project progresses as more knowledge is gained, this reducing the possible margin of error as you go along. The more open you are with communication, the earlier surprises are discussed - leading to people been less surprised and allow more time to make adjustments in either the project or customers expectations.

Second, perhaps a better way of handling error margin is 'confidence internals' rather than merely % margins of error. You than based you estimated delivery date on a confidence interval, rather than a singular date.

PERT is one example of a framework to handle estimation based upon statistical reasoning. For example:

"Based upon what I know now, we have a 90% confidence level we can deliver in 8 months. 95% confidence in 10 months, 99% confidence in 2 years, etc"

Note here: The more confident they want you, the larger the estimate will be. Depending on upon the complexity (aka, how accurate you could possibly be), it could be a small difference between 80% and 90%, or it could be huge!

Lastly - Good luck ;) If you ever solve 'maximum error margin' in software estimation whereby you can specify something like 'all our estimates will be +/- 10%', be sure to commission a box-office movie for the rest of us in the software industry. I'm thinking something like a cross between Office Space and The Matrix :D


答:
It actually depends a lot on the size and complexity of the project.

If your project estimate is say 1 week - 10% is reasonable. It means +/- 1/2 day.

If it is 1 month 10% is shaky - from my experience it is impossible to  forecast what you will discover in 1 month.

More than one month - all bets are off :).

These are per developer - so for a 4 developer team 1week == 1 month.

For a 4 developer team, mostly its good to come up with a list of features that can be done in  1 month, and be within 10% for those feature. Then, re-estimate for the next month.

I have made some naive assumptions here

All developers can do work in parallel.

Haven't considered tester - they should have some time to test

All developers are equal - Frontend, Backend, Designers etc...

You have to factor those in.. but this is the general idea.


答:
There are lots of variables:

How long is the project?

How will the project be managed? Waterfall? Agile? SCRUM?

I would assume from the question Waterfall. If that is the case you are pretty much expected to fail by some percentage given the request for a margin.

If the answer is some Agile methodology, especially something like SCRUM. It doesn't really matter what the margin percentage is. A 50% margin of error on a 2 week Sprint is 1 week, on a 1 week Sprint it is 2.5 days, both extremely worst case scenarios. This is because the delivery date is re-estimated every Sprint, and it will get to be more and more accurate over time, instead of less and less.

With Waterfall 50% margin of error isn't un-heard of either, but over a 12 month project that is 6 months, and it doesn't really get discovered / admited it is that bad until 10 months into the 12.


问:
What's the difference between Entry Level/Jr/Sr developers?
Other than title and pay, what is the difference?

What different responsibilities do they have.

How knowledgeable/experienced are they?

What is the basic measure to determine where a developer fits into this basic structure?

答:
Entry Level - must give them explicit instructions, check everything they do, little or no design responsibility, no analysis responsibility

Junior - less explicit instructions, less checking, some minor design and analysis responsibility; helps the entry-level people find the compiler and use the repository

Senior - major design and analysis responsibility, is expected to correct oversights on his/her own, little/no checking, little/no instructions; helps the junior-level people learn/improve analysis and design skills

ContentLicense: CC BY-SA 2.5


问:
How do asserts and other error avoidance checks fit into TDD?
http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd

You are not allowed to write any production code unless it is to make a failing unit test pass.

So where do asserts fit into this?  If you followed this rule you'd never write an assert without a unit test.  But how would you test for the existence of an assert?  The very nature of assert seems to make this idea impossible as the test would explode.

And what about code meant to handle absurd conditions that are difficult or impossible to replicate?  Some sort of FUBAR from a system call for example...  You need to handle the error but the condition that causes the error is pretty rare and comes from the OS.  How do you write a unit test to make that fail?

Or say you're writing a template library and want to do some concept checks before going too deep into template vomit land?  I don't know of any framework that supports compile time failure as a test PASS.

I've tried to live by some of these TDD edicts, but at some point I've always run into walls I can't get around.  These are some.

I guess I should say that I'm talking about assert in the C/C++ sense in which a program, built without NDEBUG, will fault out if the assertion fails.  Not some exception throwing mechanism that's called assert.  Didn't even realize someone would use that name for throwing exceptions.

答:
It looks to me like you're experiencing cognitive dissonance, trying to believe two contradictory ideas and accept both as valid.  The way to resolve it is to understand that one (or possibly both) must be incorrect, and find out which it is. In this case, the problem is that those edicts are based on a false premise, which Uncle Bob repeats several times a few lines further down:

However, think about what would happen if you walked in a room full of
  people working this way. Pick any random person at any random time. A
  minute ago, all their code worked.

Let me repeat that: A minute ago all their code worked! And it doesn't
  matter who you pick, and it doesn't matter when you pick. A minute ago all their code worked!

That's the shining promise of TDD: test everything, make it so all your tests pass, and all your code will work.

Problem is, that's a blatant falsehood.

Test everything, make it so all your tests pass, and all your tests will pass,  nothing more, nothing less.  That doesn't mean anything particularly useful; it only means that none of the error conditions that you thought to test for exist in the codebase.  (But if you thought to test for them, then you were paying enough attention to that possibility to write the code carefully enough to get it right in the first place, so that's less helpful than it might be.)

It doesn't mean that any error you didn't think of is not present in the codebase.  It also doesn't mean that your tests--which are also code written by you--are bug-free.  (Take that concept to its logical conclusion and you end up caught in infinite recursion.  It's tests all the way down.)

To give an example, there's an open-source scripting library that I use whose author boasts of over 90% unit test coverage and 100% coverage in all core functionality.  But the issue tracker is almost up to 300 bugs now and they keep coming.  I think I found five from the first few days of using it in real-world tasks.  (To his credit, the author got them fixed very quickly, and it's a good-quality library overall.  But that doesn't change the fact that his "100%" unit tests didn't find these issues, which showed up almost immediately under actual usage.)

The other major problem is that as you go on,

every hour you are producing several tests. Every day dozens of tests.
  Every month hundreds of tests. Over the course of a year you will
  write thousands of tests.

...and then your requirements change.  You have to implement a new feature, or change an existing one, and then 10% of your unit tests break, and you need to manually go over all of them to discern which ones are broken because you made a mistake, and which are broken because the tests themselves are no longer testing for correct behavior.  And 10% of thousands of tests is a lot of unnecessary extra work.  (Especially if you're doing it 1 test at a time, as the three edicts demand!)

When you think of it, this makes unit testing a lot like global variables, or several other bad design "patterns": it may seem to be helpful and save you some time and effort, but you don't notice the disastrous costs until your project becomes big enough that their overall effect is disastrous, and by that time it's too late.

It is now two decades since it was pointed out that program testing
  may convincingly demonstrate the presence of bugs, but can never
  demonstrate their absence. After quoting this well-publicized remark
  devoutly, the software engineer returns to the order of the day and
  continues to refine his testing strategies, just like the alchemist of
  yore, who continued to refine his chrysocosmic purifications.

-- Edsger W. Djikstra.  (Written in 1988, so it's now closer to
  4.5 decades.)


答:
Not sure why you say that "the test would explode". In this example I am testing an assertion:

```<code>public int methodUnderTest() {
    int i = resultOfACalculationThatShouldNeverBeZero();
    assert (i != 0);
    return 5 / i;
}

private int resultOfACalculationThatShouldNeverBeZero() {
    return 0;
}

@Test(expected = AssertionError.class)
public void shouldAssertBeforeDividingByZero() {
    methodUnderTest();
}
</code>```

In a real world scenario the resultOfACalculationThatShouldNeverBeZero would have to be mocked somehow.

Having said that, I don't think assertions (at least in Java) are too useful. It's more like a crutch when debugging, to validate your own assumptions, but probably indicates an overly complex method. One point of the assertion is to document the intent. A unit test does that as well.

Having said all this, I would take what uncle Bob says with a big grain of salt. I have read Clean Code and Agile Software Development and those books contain lots of very very bad code (breaking almost every one of his own rules) and examples where he actually makes the "fixed" code worse than the original..

Title: How do asserts and other error avoidance checks fit into TDD?

Body:
http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd

You are not allowed to write any production code unless it is to make a failing unit test pass.

So where do asserts fit into this?  If you followed this rule you'd never write an assert without a unit test.  But how would you test for the existence of an assert?  The very nature of assert seems to make this idea impossible as the test would explode.

And what about code meant to handle absurd conditions that are difficult or impossible to replicate?  Some sort of FUBAR from a system call for example...  You need to handle the error but the condition that causes the error is pretty rare and comes from the OS.  How do you write a unit test to make that fail?

Or say you're writing a template library and want to do some concept checks before going too deep into template vomit land?  I don't know of any framework that supports compile time failure as a test PASS.

I've tried to live by some of these TDD edicts, but at some point I've always run into walls I can't get around.  These are some.

I guess I should say that I'm talking about assert in the C/C++ sense in which a program, built without NDEBUG, will fault out if the assertion fails.  Not some exception throwing mechanism that's called assert.  Didn't even realize someone would use that name for throwing exceptions.

Body:
Not sure why you say that "the test would explode". In this example I am testing an assertion:

public int methodUnderTest() {
    int i = resultOfACalculationThatShouldNeverBeZero();
    assert (i != 0);
    return 5 / i;
}

private int resultOfACalculationThatShouldNeverBeZero() {
    return 0;
}

@Test(expected = AssertionError.class)
public void shouldAssertBeforeDividingByZero() {
    methodUnderTest();
}

In a real world scenario the resultOfACalculationThatShouldNeverBeZero would have to be mocked somehow.

Having said that, I don't think assertions (at least in Java) are too useful. It's more like a crutch when debugging, to validate your own assumptions, but probably indicates an overly complex method. One point of the assertion is to document the intent. A unit test does that as well.

Having said all this, I would take what uncle Bob says with a big grain of salt. I have read Clean Code and Agile Software Development and those books contain lots of very very bad code (breaking almost every one of his own rules) and examples where he actually makes the "fixed" code worse than the original..


问:
Can neural network discover rng patterns
Can neural network find connections beetween numbers generated by random number generator without knowing about it's seed and predict this rng's next numbers with more sucess then randomly guessing? I really couldn't find any data about this. Thanks</p>

答:
If the random number generator is reasonably good, it is impossible to predict the Nth number given only the prior N-1 numbers.  Any random number generator that is used for cryptographic purposes, for example, will be sufficiently random that you won't be able to predict the next number.

If you've got a poor random number generation, on the other hand, it may be possible to predict the Nth number so it should be possible for a neural net to predict the next number (depending, of course, on the weakness of the random number generator).


答:
Depends heavily on how you are trying to make the prediction.

Most PRNGs that I've used usually operate on a ring of numbers within a finite range. The seed decides what number you start on, and you progress around the ring one number at a time. The order of the numbers appears random, but their order is actually very deterministic.

For  example, lets say that your prng generates numbers on the ring 0-6. If your seed is 1, then it might cycle through numbers in this way:

```<code>1 -> 6 -> 2 -> 4 -> 0 -> 3 -> 5 -> 1 -> 6 -> ...
</code>```

Some important things to note:

Once you reach the seed again, the values repeat.

Apparent randomness is achieved by generating a ring that appears to "scatter" numbers around and choosing a different seed every time you run the generator.

When looking at it in this respect, it is actually quite easy to predict the next random number that comes from a typical prng--all you need to know is the function that generated the ring of numbers and the last number that was pulled from the sequence.

After reading this, it might be tough to understand why the numbers appear random in the first place (especially when looking at the sequence above). The thing to understand is that the range of numbers is usually enormous (on the scale of 2^31-ish), and therefore it is EXTREMELY unlikely that you will land in the same section of the ring on subsequent runs of the program.

So depending on your situation, what you are doing could be quite easy--if you know the function that is generating the sequence of numbers, then all you need is the last number pulled and you're done! No neural network needed.

If you don't know the function that generates the ring of numbers, then it is very unlikely that a neural network will help. The function that generates the cycle of numbers is designed to be a one-way function (a.k.a., you can't invert the function to figure out the values used within the function).

If you're interested in pursuing this further, I highly recommend that you study PRNG's in depth. The math is fairly simple, and knowing how they work will give you a better idea of what their strengths and limitations are.

Title: Can neural network discover rng patterns

Body: Can neural network find connections beetween numbers generated by random number generator without knowing about it's seed and predict this rng's next numbers with more sucess then randomly guessing? I really couldn't find any data about this. Thanks</p>

Body:
Depends heavily on how you are trying to make the prediction.

Most PRNGs that I've used usually operate on a ring of numbers within a finite range. The seed decides what number you start on, and you progress around the ring one number at a time. The order of the numbers appears random, but their order is actually very deterministic.

For  example, lets say that your prng generates numbers on the ring 0-6. If your seed is 1, then it might cycle through numbers in this way:

1 -> 6 -> 2 -> 4 -> 0 -> 3 -> 5 -> 1 -> 6 -> ...

Some important things to note:

Once you reach the seed again, the values repeat.

Apparent randomness is achieved by generating a ring that appears to "scatter" numbers around and choosing a different seed every time you run the generator.

When looking at it in this respect, it is actually quite easy to predict the next random number that comes from a typical prng--all you need to know is the function that generated the ring of numbers and the last number that was pulled from the sequence.

After reading this, it might be tough to understand why the numbers appear random in the first place (especially when looking at the sequence above). The thing to understand is that the range of numbers is usually enormous (on the scale of 2^31-ish), and therefore it is EXTREMELY unlikely that you will land in the same section of the ring on subsequent runs of the program.

So depending on your situation, what you are doing could be quite easy--if you know the function that is generating the sequence of numbers, then all you need is the last number pulled and you're done! No neural network needed.

If you don't know the function that generates the ring of numbers, then it is very unlikely that a neural network will help. The function that generates the cycle of numbers is designed to be a one-way function (a.k.a., you can't invert the function to figure out the values used within the function).

If you're interested in pursuing this further, I highly recommend that you study PRNG's in depth. The math is fairly simple, and knowing how they work will give you a better idea of what their strengths and limitations are.


问:
Difference between a CMS and a Web Development Framework
The web world is flooded with CMSes. Some tout their CMS as Web Development Framework. Some say it as Content Management Solution and nowadays i m hearing Content Management Framerowk.
When we hear "Framework", it sort of sounds like more complex and sophisticated.
Is there any specific difference between these two i.e. CMS and Web Development Framework?
Or Is it that a Web Development Framework can be a CMS and vice versa?

Thanks

答:
The short answer is no.

A CMS or content management system is basically an application built ( maybe/most likely on top of a web application framework ) for the purpose of providing rich tools to maintain, organize and add content dynamically to a website. Good examples would be Drupal, Joomla, DotNetNuke etc.

A framework is different in that it is far more generic. It's almost like the saying "Every square is a rectangle but not every rectangle is a square" in that most commonly every CMS comes built on top of a popular or in-house framework making it useful to extend but it lacks the true genericism to actually make it a framework.

Take expression engine. Expression engine is built on top of CodeIgniter but adds far more libraries, helper and functionality mostly geared towards content management. It would be hard to do the extra work to dumb down expression engine to create a new product that isn't a CMS compared to just using CodeIgniter ( The framework ).


答:
CMS and Web Frameworks are not the same thing however CMS is on top of the framework and can form a standard of its own as well as integrate to the framework. The important difference between the two can be in for example Drupal is CMS as CMF that can easily break if you install a badly coded module. Even getting to understand or work with a pre defined naming convention for example theming is a dirty job in cms. Leave it for quick information or marketing based website. You must know one theme and customize it to suit. However WF are more flixible and programmers oriented. Why will learn to hard code drupal api if you can do much cleaner output with the framework. You can define your own functions and you don't have to install a load of rubbish that you don't need.
ref:cms-or-web-framework-when-to-use-which</p>

Title: Difference between a CMS and a Web Development Framework

Body:
The web world is flooded with CMSes. Some tout their CMS as Web Development Framework. Some say it as Content Management Solution and nowadays i m hearing Content Management Framerowk.
When we hear "Framework", it sort of sounds like more complex and sophisticated.
Is there any specific difference between these two i.e. CMS and Web Development Framework?
Or Is it that a Web Development Framework can be a CMS and vice versa?

Thanks


问:
Developing the Domain Model alone
In DDD examples it seems the common method for developing the domain model is to sit with domain experts and iterate over versions of the model, say on a whiteboard, continually modifying it and changing it until presumably an agreement is made on how the model looks.

On my project I've spent a couple of days with a domain expert, discussing the domain, and now I want to lock myself away and produce a draft model based on my understanding, rather than producing the model collaboratively with the domain expert. He could then review it, and I could update it according to our subsequent discussions.

Has anyone else worked like this, or does anyone think its a good / bad idea? I think maybe I just find it easier to think creatively when alone.

答:
I would probably minimize the amount of "locking myself away" if I were you as you'll want feedback sooner rather than later.  A major point of DDD is developing a ubiquitous vocabulary (UV) so that the developers and the users are speaking the same language and describing thing the same way.  You cannot possibly do this on your own--you have to talk to the domain experts and users to do so.

The UV is the basis of your domain model, so if you've all gotten a grip on the vocabulary, it might be reasonable to develop one (or more) models yourself and present them back to the domain expert to ensure that you are on the same page.  It is riskier than simply talking through and building the model together.

Bear in mind that this is really a logical model--you may well need to do a lot of stuff to make it a viable implemented physical model, and the domain expert probably won't care much about that aspect, as long as the physical model still is logically equivalent to your logical domain model.

So, I'd say for the initial logical model, you probably are best off working closely with the DE.  If you really can't think with others, try meeting with him for an hour or two a day, and spend the rest of the time writing up what you've agreed upon and any new ideas you have for the model, then revise at the next meeting.  But meet daily, to avoid the risk of going too far down the wrong path.  Once your logical model is healthy, you might be able to reduce the meetings to a couple a week.

The collaboration between users and the development team is almost always a key factor in successful projects.

Title: Developing the Domain Model alone


问:
Why is there still case sensitivity in some programming languages?
I don't see any use for case sensitivity in a programming language, apart from obfuscating code.

Why implement this in a programming language?

Update:

It looks like someone you know made a statement on this.

答:
"Case sensitive" is always better for technical persons to reduce ambiguity.
Take filename as an example. Dealing with Windows filename is more trouble than Unix filename because filename in Windows is case-insensitive while filename in Unix is case-sensitive.

Back to programming. For class name, method name, variable name, most language do not enforce the naming style rule. Sometimes for the sake of simplicity to do "reflection", we can simply use the "Case sensitive" name to bind to other data source without conversion, or handling the problem of same name but in different case.


答:
In times of bad economics (e.g. 2009), hiring interns is the best way for a company to continue its business. It is easy to hire them with very low costs. At that time, over 50% of staff in software department were intern students.
What you need is a team leader to lead the interns towards software development. The leader should ensure the quality of work the interns produced and see if they follow the styles and traditions.

time: work time may be a little bit longer, but less costly

projects: we do real projects to deliver to clients

management: treat them as employees, also have same annual leaves as permanent staff

Title: Making an internship most effective, useful and fun for both parties

Body:
We're currently interviewing few candidates for an internship, which is a really new experience for us as a company and for me personally as a team lead/manager. </p>

<p>What would be the most effective and useful, yet fun approach for both sides here? How do we 'integrate' an intern into our development team and workflow without much disruption in such a way that he or she could be learning and yet be helpful? </p>


问:
What's the least intrusive method for creating a backup of a couchdb database?
We're looking to create regular backups of a couchdb database, to ship offsite. What's the least intrusive way to obtain these - ideally without interrupting or significantly slowing down performance on the existing database server?</p>

答:
If you want to take a more programmatic approach just use the _all_docs URI, from wiki.apache.org

```<code>GET somedatabase/_all_docs HTTP/1.0
</code>```

The response will get you a list of all the documents in the database.

Using replication to backup the database is another possibility.

Just post the source/target database names to the _replicate URI.

Body:
If you want to take a more programmatic approach just use the _all_docs URI, from wiki.apache.org

GET somedatabase/_all_docs HTTP/1.0

The response will get you a list of all the documents in the database.

Using replication to backup the database is another possibility.

Just post the source/target database names to the _replicate URI.


问:
Algorithm for finding overlapping times
Part of our ERP system is a sub-system for running background jobs.  We track a variety of meta-data about our jobs in a table including timestamps for submitted, started, and end times.

I'm creating a report showing the performance of our job system, detailed by day. One KPI is maximum # of jobs running at once.  The algorithm I'm currently using is:

```<code>dim cnt as integer    'number of overlapping jobs
dim max as integer    'maximum number of jobs running at one time

for each Job where
         Job.SubmitTs = today

  'bJob is a 2nd instance of Job
  for each bJob where
           bJob.SubmitTs =  today and
           bJob.StartTs  <= Job.EndTs and
           bJob.EndTs    >= Job.EndTs
    cnt = cCnt + 1
  next

  if cnt > max then max = cnt
next
</code>```

The problem with this algorithm is that it is very slow due to all the looping.  I was wondering if there is a faster way to implement this?

Edit
I cannot use SQL queries to access the data.

答:
SQL knows how to sort stuff, and I'd bet your engine uses the most efficient algorithm it can (i.e. O(n log(n))), while still working if the result set doesn't fit in RAM (in contrast with K.Steff's answer which will fail if the array doesn't fit in RAM). In python :

```<code>import sqlite3
connection = sqlite3.connect("database.db")
cursor = connection.cursor()
cursor.execute("SELECT isStart from (" +
               "  SELECT startTime AS time, 1 AS isStart FROM myTable " +
               "  UNION ALL " +
               "  SELECT endTime as time, -1 AS isStart FROM myTable " +
               "  ORDER BY time ASC, isStart ASC" +
               ")")
maxOverlap = 0
currentOverlap = 0
for (isStart,) in cursor:
    currentOverlap += isStart
    maxOverlap = max(maxOverlap, currentOverlap)
print maxOverlap
</code>```

Note the isStart ASC order is necessary so the intervals [10,15] and [15,23] are not considered overlapping.

For further improvement, it is probably the case that the columns startTime and endTime have an index, so the SQL engine should efficiently merge the two already sorted tables, resulting in an O(n) operation (the O(log(n)) factor then happens at insertion time for each row, when it is added to the index, but you already have it anyway). If your SQL engine isn't smart enough to do an efficient merge, do it yourself on the fly (still in python) :

```<code>import sqlite3
connection = sqlite3.connect("database.db")
cursorStart = connection.cursor()
cursorStart.execute("SELECT startTime FROM myTable ORDER BY startTime ASC")
cursorEnd = connection.cursor()
cursorEnd.execute("SELECT endTime FROM myTable ORDER BY endTime ASC")
maxOverlap = 0
currentOverlap = 0
currentStart = cursorStart.fetchone()
currentEnd = cursorEnd.fetchone()
while currentStart is not None and currentEnd is not None:
    if currentStart < currentEnd:
        currentOverlap += 1
        currentStart = cursorStart.fetchone()
    else:
        currentOverlap -= 1
        currentEnd = cursorEnd.fetchone()
    maxOverlap = max(maxOverlap, currentOverlap)
print maxOverlap
</code>```

Title: Algorithm for finding overlapping times

Body:
SQL knows how to sort stuff, and I'd bet your engine uses the most efficient algorithm it can (i.e. O(n log(n))), while still working if the result set doesn't fit in RAM (in contrast with K.Steff's answer which will fail if the array doesn't fit in RAM). In python :

import sqlite3
connection = sqlite3.connect("database.db")
cursor = connection.cursor()
cursor.execute("SELECT isStart from (" +
               "  SELECT startTime AS time, 1 AS isStart FROM myTable " +
               "  UNION ALL " +
               "  SELECT endTime as time, -1 AS isStart FROM myTable " +
               "  ORDER BY time ASC, isStart ASC" +
               ")")
maxOverlap = 0
currentOverlap = 0
for (isStart,) in cursor:
    currentOverlap += isStart
    maxOverlap = max(maxOverlap, currentOverlap)
print maxOverlap

Note the isStart ASC order is necessary so the intervals [10,15] and [15,23] are not considered overlapping.

For further improvement, it is probably the case that the columns startTime and endTime have an index, so the SQL engine should efficiently merge the two already sorted tables, resulting in an O(n) operation (the O(log(n)) factor then happens at insertion time for each row, when it is added to the index, but you already have it anyway). If your SQL engine isn't smart enough to do an efficient merge, do it yourself on the fly (still in python) :

import sqlite3
connection = sqlite3.connect("database.db")
cursorStart = connection.cursor()
cursorStart.execute("SELECT startTime FROM myTable ORDER BY startTime ASC")
cursorEnd = connection.cursor()
cursorEnd.execute("SELECT endTime FROM myTable ORDER BY endTime ASC")
maxOverlap = 0
currentOverlap = 0
currentStart = cursorStart.fetchone()
currentEnd = cursorEnd.fetchone()
while currentStart is not None and currentEnd is not None:
    if currentStart < currentEnd:
        currentOverlap += 1
        currentStart = cursorStart.fetchone()
    else:
        currentOverlap -= 1
        currentEnd = cursorEnd.fetchone()
    maxOverlap = max(maxOverlap, currentOverlap)
print maxOverlap


答:
In a well planned piece of code, all these issues need to be adressed:

Dates only in the past.

Dates only in the future.

Dates that bridge the current time.

Requests with only one value:. From then to now, or now to then.

Requests out of order

Requests with string input: yesterday

Requests with only partial values: just a year, or just a month and year; Second Quarter of fiscal 2012.

Not all will make sense for your application, but they should be thought about during design. Some will throw errors, some will auto correct. How you label the inputs will depend on the business logic, is this an API, or are you labeling the fields on the GUI.

Also remember to document so it is clear the the developer or user what is happening.

Title: Should the most recent date be named 'start' or 'end'?

Body:
So I have a function that takes two dates.  The SQL query gets all the results between the two dates.  I currently have my function setup as such:

```<code>function myFunc(start, end)
</code>```

Where start is the most recent date and end is the oldest date.

Is this intuitive/correct or is there another naming/ordering convention I should be using?


答:
Back when I used to lead software teams, roughly around the Cretaceous/Tertiary boundary, we actually came close to achieving +/- 10% on estimation. It was about +/- 15% if my very dodgy memory serves. But this was because we were estimating for things we'd already done: relatively simple real-time communications firmware which took bytes from A and moved them to B using a language that we were familiar with, in a real-time environment designed by us, talking to hardware designed in-house by guys a few offices away. Lots of slight variants on the above theme, for literally years.

Expecting to achieve this kind of error rate in normal software project estimation is, frankly, ludicrous. When you see it apparently achieved, it's because either people over-estimated and padded (doing extra stuff and pet projects to use up the budget), or under-estimated and worked like dogs at evening and weekends to make up time.


答:
It depends on how you're using it in your app and/or business rules. If they think of these date ranges as "Start with this date and go back in time to another date", you're all set. Programmers or dbas who are going to use this function will consider the start date as the earliest date and the end to be most recent. I would think this would be chronological.

You indicated the function will run a sql query with a date range "between" these two dates. The BETWEEN operator would look for a date range: >= the begin date AND <= the end date. Users may not know how you're doing this in the function code, but that just seems consistent/standard.


问:
Should I refactor single letter variables for constructs like pointer/structure names?
And No, i am not referring to single variables in loops or exceptions. Lets say pointer/struct names in large c ,c++ programs . Are there any languages where this type of naming is acceptable or is the norm. Or any constructs in c/c++ ( not iterators,loops) where it is implicit.

what is the general practice in handling such naming conventions ?  would you change it? if so how would you change it?

If you are a team-project lead and some one raises an issue with regards to the naming convention how would you view it?

答: If the name of a variable is a problem, either because it's not sufficiently descriptive, confusing, or for some other reason, then change it. It's that simple. Many IDE's provide refactoring tools that make such renaming operations a 10-second operation. If yours doesn't, you may have to spend some time with a global find-and-replace operation.


问:
If I drop cookies with JavaScript will it still be compliant with the EU ICO Cookie Law?
The challenge proposed to me as to create a widget to apply in other sites that makes a website compliant with the cookie law[1].

Can I do this without changing server code?

I mean, if there's code on server-side that writes an affiliate cookie to the response and my JavaScript widget deletes it after on window.load event: will the site still be cookie law compliant?

Then comes the Google Analytics and share buttons cookies. How would I stop those scripts and iframes from being executed in JavaScript?

[1] The Information Commissioner's Office (ICO) : New ICO Cookie Law

答:
One thing to keep in mind is that your script may be rendered useless if the server sets the HttpOnly flag when the cookie is created.

http://en.wikipedia.org/wiki/HTTP_cookie#HttpOnly_cookie

There may also be domain origin issues for accessing/manipulating cookies set from other domains due to security (XSS). I'm not 100% on this as I rarely use javascript when it comes to cookies for the same purpose of minimizing exposure to XSS.

While your concept sounds like a great idea, I suggest looking into these possible issues further before investing too much of your time into this project.


答:
First of all, ANY code change risk introducing new errors, and hence the advantage of the change must be weighed against the cost of doing the change.   This may even be downright vetoed by your superior for production software, if the module in question has worked correctly for years or even decades.

I agree that single character identifiers may require more effort to understand, but is it hard enough to warrant changing?

That said, refactoring is a good way to rename variables to something more telling.  Most modern IDE's can do this for you.  Be sure that the new name conforms to your local conventions, so the next maintainer after you do not have to repeat your efforts.

Title: Should I refactor single letter variables for constructs like pointer/structure names?

Body:
And No, i am not referring to single variables in loops or exceptions. Lets say pointer/struct names in large c ,c++ programs . Are there any languages where this type of naming is acceptable or is the norm. Or any constructs in c/c++ ( not iterators,loops) where it is implicit.

what is the general practice in handling such naming conventions ?  would you change it? if so how would you change it?

If you are a team-project lead and some one raises an issue with regards to the naming convention how would you view it?


问:
Naming classes, methods, functions and variables
There are 3 important naming conventions:

with_underscores

PascalCased

camelCased

Other variants are not important because they are not commonly used.

For variables it seems that the one with underscores is the most used by developers so I'll stick with that. I think it's the same for functions.

But what about class, and method names? Which of these 3 is the most used by developers for such constructs? (personally, it's 3. for methods and 2. for classes)

Please do not post things like "use what you feel is right", because the code I'm writing is API for other developers, and I'd like to adopt the most popular coding style :)

答:
There is no such thing as "the most popular coding style", it's strictly a matter of your team's conventions and personal preferences. Since you are targeting developers, you should research popular conventions for your platform and follow the one you feel is more convenient, readable and, well, closer to your personal style. For PHP a popular set of naming conventions is Zend Framework's.

Being consistent with the naming convention you choose is more important than the convention itself.


答:
Absolutely i would change them.

How to know if it breaks any existing functionality?

Just run your test suite after the change.

Ahh, no test suite.  ok in that case add this reason to the list on the big board titled "why we need to have tests".  Don't change anything, you're likely to break stuff (and in the process possible lose the chance to convince people that the stuff should be changed).  It's kinda like wearing a seat belt.  You don't have to... but I wouldn't recommend driving without it... something might break ;)


问:
Visualizing temperature levels across a city
I have a list of temperature levels (0 - 30 degrees) in different parts of a city. I would like to visualize the different temperature levels in the different parts of the city. Hot places should be displayed in red and cold ones blue. If the user zoom out he will get the avarage temperature color of the city and if zoomed in he will get the average color of the temperate color of that place.

I think that what I need is referred to as heatmaps. Is that the correct?

I am not too expert in visualization techniques and would appreciate explanatory pseudocode to illustrate the internal workings and main building blocks for heatmap algorithms, and how I could handle the zooming.

答:
That sort of thing is exactly what a heatmap is for.  As to how to build one, think about a collection of points on the map laid out in a grid.  Each point has a temperature associated with it; you then map each temperature value to a color, say with

```<code>Red:    80
Orange: 70
</code>```

and so on.  That's your basic heatmap.

Now, in the real world you don't generally have exactly rectangular grids, so you have to interpolate.  That means finding the nearest points for which you have data and computing an assumed temperature based on some rule.  Usually this would be linear -- that is, if you want to compute the value for a point halfway between two other points, you would assign it half the difference in temperatures.

This looks like a decent article here: http://www.spatialanalysisonline.com/Output/ContentsFiguresAndTables.html?n=GridInteAndCont.html

Now, when you do the zooming, all you do is compute a new matrix of numbers for the new grid, map the old vertices to the new grid vertex and average the values.

Body:
That sort of thing is exactly what a heatmap is for.  As to how to build one, think about a collection of points on the map laid out in a grid.  Each point has a temperature associated with it; you then map each temperature value to a color, say with

Red:    80
Orange: 70

and so on.  That's your basic heatmap.

Now, in the real world you don't generally have exactly rectangular grids, so you have to interpolate.  That means finding the nearest points for which you have data and computing an assumed temperature based on some rule.  Usually this would be linear -- that is, if you want to compute the value for a point halfway between two other points, you would assign it half the difference in temperatures.

This looks like a decent article here: http://www.spatialanalysisonline.com/Output/ContentsFiguresAndTables.html?n=GridInteAndCont.html

Now, when you do the zooming, all you do is compute a new matrix of numbers for the new grid, map the old vertices to the new grid vertex and average the values.

OwnerDisplayName: Charlie Martin


问:
Seperable Kernel, MMX/SSE and TCP Transmittal of them?
So I was reading about Java Convolve and someone said that it may be faster than the MMX / SSE implementation. In it one of the comments had a kernal array and said it was seperable.

What is a seperable kernel? How is this useful for image processing?

What is MMX/SSE? The wikipedia page lists them as instruction sets. Are they specificially designed for image processing?

How would you transmit a MMX/SSE format (I assume) data set through TCP?

Thanks.

答:
MMX/SSE is a set of instructions built into Intel processors for applying a single operation simultaneously to several numbers. In other words it is a form of parallelism. I don't think the statement "Java Convolve is faster than MMX/SSE" implementation" makes any sense as a general statement. You'd have to compare a specific Java implementation to a specific MMX/SSE implementation. Heck, there's nothing to keep the Java Virtual Machine on a chip supporting MMX/SSE from using MMX/SSE instructions, so it isn't an either/or situation. It also doesn't make sense to ask about an MMX/SSE format. MMX/SSE operates on integers and floating point numbers.

A 2-dimensional kernel is separable if it can be split into two independent, one-dimensional kernels. This can be used to speed up the calculations involving the kernel.


答:
Names of variables should be expressive. You, or anyone else on your team should be able to understand what the variable is used for from its name. If another developer on your team looks at your code, and asks you what this variable is for, that is a good indication that you should change its name.

From this follows that single letter names are generally a bad idea, unless it is something obvious like

```<code>struct Point
{
  int x, y;
};
</code>```

or

```<code>struct Pixel
{
  uint8 R, G, B;
};
</code>```

Remember, you spend much more time reading code than writing it, so saving keystrokes should not be your priority.  This is especially true with modern IDE's, which auto-complete names for you.

And IMHO, making a variable name more understandable is a very good reason to change code. And you absolutely need a good suite of automated unit tests to be able to refactor without fear. See "Clean Code" by Robert C. Martin for details.

Body:
Names of variables should be expressive. You, or anyone else on your team should be able to understand what the variable is used for from its name. If another developer on your team looks at your code, and asks you what this variable is for, that is a good indication that you should change its name.

From this follows that single letter names are generally a bad idea, unless it is something obvious like

struct Point
{
  int x, y;
};

or

struct Pixel
{
  uint8 R, G, B;
};

Remember, you spend much more time reading code than writing it, so saving keystrokes should not be your priority.  This is especially true with modern IDE's, which auto-complete names for you.

And IMHO, making a variable name more understandable is a very good reason to change code. And you absolutely need a good suite of automated unit tests to be able to refactor without fear. See "Clean Code" by Robert C. Martin for details.


答:
While it may not be as ubiquitous as the Java version, following the Apache PHP Style Guide certainly won't hurt.  For naming conventions:

Naming: FunctionNamesLike, $localVariableName, $objectVariable,
  ClassNamesLike, MethodNamesLike, CONSTANTS_LIKE_THIS. Global names
  (classes, functions, variables, defines) must be prefixed to prevent
  naming clashes with PHP itself. This approach includes preventing
  prefixes that clash with PHP or are likely to. Apart from constants,
  prevent underscores in your names unless you simulate namespaces and
  are sure you can switch to real namespaces once PHP has them (and of
  course for object variables).

Following this, class and method names would be PascalCased.

There are a number of other reasonable style guides out there as well, as listed here. Most seem to agree that class names should be PascalCased but some, including the MIT style guide, indicate methods should be camelCased.

So, four years after I originally answered this question, I would say go with the accepted answer above.

Title: Naming classes, methods, functions and variables

Body:
There are 3 important naming conventions:

with_underscores

PascalCased

camelCased

Other variants are not important because they are not commonly used.

For variables it seems that the one with underscores is the most used by developers so I'll stick with that. I think it's the same for functions.

But what about class, and method names? Which of these 3 is the most used by developers for such constructs? (personally, it's 3. for methods and 2. for classes)

Please do not post things like "use what you feel is right", because the code I'm writing is API for other developers, and I'd like to adopt the most popular coding style :)


问:
mysql fulltext search table design
I have been working on a Mysql db design which keyword based search seems to be necessary. Main table has two columns:

```<code>id | Title
</code>```

For each entry, users will be required to enter 4 or 5 keywords. I think using a seperate table for keywords would be better. I would like to learn if there is any difference between these two designs in terms of performance, scalability and  management. There will be millions of rows in the main table.

```<code>id | keywords
1  | 1kword1, 1kword2, 1kword3
2  | 2kword1, 2kword2, 2kword3
</code>```

Or

```<code>id | keyword
1  | 1kword1
2  | 1kword2
3  | 1kword3
4  | 2kword1
5  | 2kword2
6  | 2kword3
</code>```

答:
If you do a comma delimited keyword set you will be forced to using a full text search solution to find records, in this case adding them to the main table would be beneficial.  In the second case, if you are searching for exact keyword matches your performance will be faster and you can use a standard string based index rather than a full text one.

Using a dedicated search engine would be even better.  There is a build (if it's not standard already) of Sphinx Search that works nicely with MySQL.  Solr is also a nice solution.

Depends on your front end which might be easier to implement and manage.

Title: mysql fulltext search table design


问:
Should you fix preexisting defects while working on something else?
Conundrum:  During the course of working on a new feature or fixing a defect, you find a legacy problem in code.  What should you do?  Fix it and risk altering the behavior of the code. It has either been working up until now by some fluke, or else the defect has not been detected or worth anyone's time to report.  Should you leave it alone and allow the problem to make the code harder to work with later?  Fixing the problem will only add to the time of your original task and force you to regression test. Few will appreciate the work. Fixing it, however, seems right somehow. Code with fewer problems is easier to refactor and build upon.

I've been finding myself in this situation time and time again as we work to modernize a web application. I can't tell if I'm being obsessive or honorable when I go off-tangent working on these old bugs.  How do you handle these situations?

Thanks,
Corey

答: If it's an obvious bug, such as something that will violate security, corrupt data, or raise an exception that gets displayed to the user, then fix it.  Otherwise, ask someone who knows the codebase better than you.</p>


答:
I had the same question about a year ago so I looked at some code myself. Here is what I found (constants were ALL_CAPS in every project, by the way):

╔═══════════════════════╦═════════════╦════════════╦══════════════╦════════════╦════════════╗
║      PHP Project      ║   Classes   ║  Methods   ║  Properties  ║ Functions  ║ Variables  ║
╠═══════════════════════╬═════════════╬════════════╬══════════════╬════════════╬════════════╣
║ Akelos Framework      ║ PascalCase  ║ camelCase  ║ camelCase    ║ lower_case ║ lower_case ║
║ CakePHP Framework     ║ PascalCase  ║ camelCase  ║ camelCase    ║ camelCase  ║ camelCase  ║
║ CodeIgniter Framework ║ Proper_Case ║ lower_case ║ lower_case   ║ lower_case ║ lower_case ║
║ Concrete5 CMS         ║ PascalCase  ║ camelCase  ║ camelCase    ║ lower_case ║ lower_case ║
║ Doctrine ORM          ║ PascalCase  ║ camelCase  ║ camelCase    ║ camelCase  ║ camelCase  ║
║ Drupal CMS            ║ PascalCase  ║ camelCase  ║ camelCase    ║ lower_case ║ lower_case ║
║ Joomla CMS            ║ PascalCase  ║ camelCase  ║ camelCase    ║ camelCase  ║ camelCase  ║
║ modx CMS              ║ PascalCase  ║ camelCase  ║ camelCase    ║ camelCase  ║ lower_case ║
║ Pear Framework        ║ PascalCase  ║ camelCase  ║ camelCase    ║            ║            ║
║ Prado Framework       ║ PascalCase  ║ camelCase  ║ Pascal/camel ║            ║ lower_case ║
║ SimplePie RSS         ║ PascalCase  ║ lower_case ║ lower_case   ║ lower_case ║ lower_case ║
║ Symfony Framework     ║ PascalCase  ║ camelCase  ║ camelCase    ║ camelCase  ║ camelCase  ║
║ WordPress CMS         ║             ║            ║              ║ lower_case ║ lower_case ║
║ Zend Framework        ║ PascalCase  ║ camelCase  ║ camelCase    ║ camelCase  ║ camelCase  ║
╚═══════════════════════╩═════════════╩════════════╩══════════════╩════════════╩════════════╝
```

So after looking at all this, I decided to go with:

ClassName

methodName

propertyName

function_name (meant for global functions)

$variable_name

Body:
I had the same question about a year ago so I looked at some code myself. Here is what I found (constants were ALL_CAPS in every project, by the way):

╔═══════════════════════╦═════════════╦════════════╦══════════════╦════════════╦════════════╗
║      PHP Project      ║   Classes   ║  Methods   ║  Properties  ║ Functions  ║ Variables  ║
╠═══════════════════════╬═════════════╬════════════╬══════════════╬════════════╬════════════╣
║ Akelos Framework      ║ PascalCase  ║ camelCase  ║ camelCase    ║ lower_case ║ lower_case ║
║ CakePHP Framework     ║ PascalCase  ║ camelCase  ║ camelCase    ║ camelCase  ║ camelCase  ║
║ CodeIgniter Framework ║ Proper_Case ║ lower_case ║ lower_case   ║ lower_case ║ lower_case ║
║ Concrete5 CMS         ║ PascalCase  ║ camelCase  ║ camelCase    ║ lower_case ║ lower_case ║
║ Doctrine ORM          ║ PascalCase  ║ camelCase  ║ camelCase    ║ camelCase  ║ camelCase  ║
║ Drupal CMS            ║ PascalCase  ║ camelCase  ║ camelCase    ║ lower_case ║ lower_case ║
║ Joomla CMS            ║ PascalCase  ║ camelCase  ║ camelCase    ║ camelCase  ║ camelCase  ║
║ modx CMS              ║ PascalCase  ║ camelCase  ║ camelCase    ║ camelCase  ║ lower_case ║
║ Pear Framework        ║ PascalCase  ║ camelCase  ║ camelCase    ║            ║            ║
║ Prado Framework       ║ PascalCase  ║ camelCase  ║ Pascal/camel ║            ║ lower_case ║
║ SimplePie RSS         ║ PascalCase  ║ lower_case ║ lower_case   ║ lower_case ║ lower_case ║
║ Symfony Framework     ║ PascalCase  ║ camelCase  ║ camelCase    ║ camelCase  ║ camelCase  ║
║ WordPress CMS         ║             ║            ║              ║ lower_case ║ lower_case ║
║ Zend Framework        ║ PascalCase  ║ camelCase  ║ camelCase    ║ camelCase  ║ camelCase  ║
╚═══════════════════════╩═════════════╩════════════╩══════════════╩════════════╩════════════╝

So after looking at all this, I decided to go with:

ClassName

methodName

propertyName

function_name (meant for global functions)

$variable_name


答:
In my career I have discovered that coddling peoples' feelings is way more important than correct code. Some yahoo might be writing the most fucked up shit imaginable, using single character names like 'm' for map or 'c' for ...??

Suggesting that this should be changed can hurt feelings and create lots of workplace drama. If you're wiser than me you'll approach these situations carefully so your bosses don't start hating you. Writing code like that is really dumb and people don't like it being pointed out that they're doing dumb shit. You might have to learn to put up with working on shit.

So no, don't necessarily just change it.  Put out feelers first, etc...  At the place I currently work I suggested changing some code that took indexes to global arrays as parameters, grabbed the value at that index, and worked on that value to taking the value by reference and so being independent of global bullshit....I've been hated by the lead architect of the project ever since and it's cost me big time.

You obviously work in an environment where shitty code has been allowed to fester.  The people who wrote it may very well still be around and in high positions.  They can get really obnoxious at even the hint that what they're doing isn't perfection defined.


问:
Synchronously write file
I am implementing a server in C for a course project. The server should serve more than one client simultaneously. The description of the project states that fork() should be used to serve more than one client. Each children should write something to a common file. How do I handle this synchronously? Is there any mechanism like in Java where only one thread can use a function at the same time?

答: Because you're using fork(), you are spawning new processes, not new threads. That means you can't synchronize via monitors. You can, however, synchronize via named semaphores.

Title: Synchronously write file


答:
So where do asserts fit into this?

Test Your Code's Behavior

If you need to test that an assert fires than do so.  Pass in the variable that makes the assert throw and exception and in your test catch the exception to assert it was thrown.

And what about code meant to handle absurd conditions that are difficult or impossible to replicate?

You have a few choices.

Don't Test

You have the option of not testing.  Testing provides a measure of risk mitigation.  You can choose not to test, but realize you increase you risk.

Use Mocks to Facilitate Replication

You can almost always mock out some underlying call to throw the appropriate exception or error condition which can then be tested against.

Indirect Testing

Usually you want to test a condition directly.  Sometimes it's too difficult or expensive.  In some cases you can mitigate some of the risk by testing for the conditions indirectly.  This would include testing for initial states, side effects, or other indicators of the condition.

Exceptions to the Rule

Some cases will always be very difficult to test directly.  Testing for a deadlock, cases of resource starvation, threading issues can sometimes be to difficult.