问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
The only thing that springs to mind is this:

```<code>#DEFINE TRUE FALSE
#DEFINE FALSE TRUE
</code>```

But once again, that's just plain old misuse hehe.

Title: Is anything in programming truly evil?

Body:
The only thing that springs to mind is this:

#DEFINE TRUE FALSE
#DEFINE FALSE TRUE

But once again, that's just plain old misuse hehe.


问:
How to show retry in sequence diagram
I am drawing sequence diagram for large integration project where one system will initiate the REST call to another system and there is a proxy in middle which will pass through the request like

A->b->C

where b is a pass through system. I have shown 200 returned from C->b->A. I am wondering how do I depict when C returns 500 or there is an IOException and A needs to retry n no of times before it gives up.

答:
One way is to use Fragments like this:

But honestly: code is much clearer for such purposes. Avoid using a graphical representation where a few lines of (pseudo) code can clarify what a 1000 pictures obfuscate. Once (in the 80s) I also though that programming graphically would be an advantage. But now I'm old an wise and know that this was wishful thinking. It's simply stupid ;-)

Regarding the IOException this heavily depends on runtime behavior. Usually this is a message sent from c which is not a return message but will produce a call stack in a. This can be placed in an alt Fragment.

OwnerDisplayName: Learner

ContentLicense: CC BY-SA 3.0

Title: How to show retry in sequence diagram


问:
ORM: runtime proxies vs bytecode instrumentation
What are the benefits of using runtime proxies with an ORM provider like Hibernate or EclipseLink compared to bytecode instrumentation/enhancement?

I know that bytecode instrumentation helps to optimize dirty checking. Because it can intercept modifications, ORM provider doesn't need to traverse all the objects in the persistence context and compare the current values with the snapshot taken when the objects were loaded (thus avoiding additional memory consumption as well, I assume).

Also, I know that it can help in situations in which additional queries have to be executed because the ORM provider doesn't know whether a proxy needs to be created or what the primary key value in the proxy is, like in lazy one-to-one associations, thus making the associations effectively eager in some situations.

Some other proxy pitfalls have been described in this blog, like direct field access (in equals and hashCode methods) and using of instanceof operator.

It seems to me that bytecode instrumentation is a better alternative. Does it have any pitfalls of its own compared to runtime proxies approach? Is there any rule of thumb which should be followed when choosing one instead of the other?

答:
Both Hibernate and EclipseLink use the Proxy design pattern to implement lazy/eager loading of entity relationships. Proxies are weaved into Java bytecode at build time (statically) or at runtime (dynamically) - basically enhancing your Entity POJOs. Other features, such as dirty checking are also weaved into bytecode.

This is an application of Aspect Oriented Programming (AOP). All the same pitfalls (e.g. unexpected classes at runtime) and advantages (e.g. cleaner source code, runtime code injection) apply.

So the question is, what are the alternatives? You could disable weaving and implement the same features (lazy loading, dirty checking, etc.) in your own code - no runtime surprises, but increased development effort.

As a rule of thumb, use annotations, avoid runtime entity class inspection and trust Hibernate or Eclipselink code weaving to deliver what you want. Note that you always have the option to implement your own proxies, etc. if complexity requires it.


问:
Is it acceptable to define a "module" and "class" within a single .VB element?

Experiment:

I have found it is possible to define both a "Module" (Namespace?) and a "Class" (Namespace?) within a single .Vb element (Module??).

You can try this at home:

Create a new Console Application Project.

*A new .Vb element named "Module1.Vb" is automatically added to the project.

Add a new Class .Vb element by right-clicking on the project in Solution Explorer>Add>Class...

Give the new class the name Test.

View the code for "Test.Vb" and paste in the following:

Imports System.Runtime.CompilerServices

Module ExtensionsTest
    <Extension()>
    Public Sub ToConsole(ByVal Ex As Exception)
        Dim ForeColor As ConsoleColor
        Console.ForegroundColor = ConsoleColor.Red
        Console.WriteLine()
        Console.WriteLine("An unhandled exception has occurred!")
        Console.WriteLine(Ex.ToString)
        Console.ForegroundColor = ForeColor
    End Sub
End Module

Class Test
    Public Sub Test()
        Try
            Dim test As New Object
            test.SomeMethodDoesntExist()
        Catch ex As Exception
            ex.ToConsole()
        End Try
    End Sub
End Class
```
<p>View the Code for Module 1 and paste in the following:</p>
<pre class="lang-vb prettyprint-override"><code>Module Module1
    Sub Main()
        Try
            Dim tester As New Test
            tester.Test()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
End Module
</code>```

Now go ahead and step through or run the application.  You'll see it all works.  So, let's move on to the...

Meat of the question

Is this acceptable practice?
It may be technically possible - but is it a bad solution for reasons I don't know?  (I'm a Mort and really don't want pick up bad coding practices unwittingly)

I originally had this as a Private method within the class definition like this:

Imports System.Runtime.CompilerServices
Class Test
    Public Sub Test()
        Try
            Dim test As New Object
            test.SomeMethodDoesntExist()
        Catch ex As Exception
            ToConsole(ex)
        End Try
    End Sub

    Private Sub ToConsole(ByVal Ex As Exception)
        Dim ForeColor As ConsoleColor
        Console.ForegroundColor = ConsoleColor.Red
        Console.WriteLine()
        Console.WriteLine("An unhandled exception has occurred!")
        Console.WriteLine(Ex.ToString)
        Console.ForegroundColor = ForeColor
    End Sub
End Class
```

I decided it would be cleaner to define the ToConsole sub as an extension method for Exception objects, but that's where I ran into trouble.  When I created the Extension attribute within the Class namespace, I got a compiler error:

Extension methods can be defined only in modules.

So, I tried the above experiment and I declared a Module within the same .VB element where my Class is defined.

As the experiment above shows, this all compiles fine and works as expected, but I'd like to know if this is a good idea or not, and why?

Thanks for taking any time to read this and even more thanks for any time taken to comment or answer!

答:
In general, the idea of one Class or Module per file is something I first noticed in Java (I believe it is/was a requirement there). C# has continued this as a suggestion, and VB.NET probably now has the same suggestion somewhere.

However, as the VB.NET designers decided you can only have extension methods in Modules, you've provided an example where it makes sense for another unit of code to be so closely related to another Class as to include it in the same file.

Of course, with the concept of Partial classes and modules you have the opposite idea of splitting single units across multiple files available too.

And BTW this concept normally means your Module would be named TestExtensions :-)

To your "Namespace?" notes in your question: VB.NET provides a Project-based namespace for your Modules and Classes, so your classes are now named ProjectNamespace.UnitName. If you provided a

Namespace SomeNamespace
...
End Namespace
```

<p>the enclosed units would be named <code>ProjectNamespace.SomeNamespace.UnitName</code>.</p>

<p>You can have multiple <code>Namespaces</code> in a file too, and you can override the <code>ProjectNamespace</code> with <code>Global.</code>:</p>

<pre class="lang-vb prettyprint-override"><code>Namespace Global.TopLevelNamespace
...
End Namespace
</code>```

Rereading your question and noting the "(Module?)" note as well, I'm guessing you're actually asking what is the "formal" VB.NET term for code units that include Class and Module and the similar term for a file of code. Because the .NET Module is so often equivalent to an Assembly, most people would know what you meant if you referred to "Namespace-level" code units as "modules", and source files are just "files". (There may be other places that give alternatve names, but I've based this on Microsoft's Introduction.)

ContentLicense: CC BY-SA 4.0

Body:
In general, the idea of one Class or Module per file is something I first noticed in Java (I believe it is/was a requirement there). C# has continued this as a suggestion, and VB.NET probably now has the same suggestion somewhere.

However, as the VB.NET designers decided you can only have extension methods in Modules, you've provided an example where it makes sense for another unit of code to be so closely related to another Class as to include it in the same file.

Of course, with the concept of Partial classes and modules you have the opposite idea of splitting single units across multiple files available too.

And BTW this concept normally means your Module would be named TestExtensions :-)

To your "Namespace?" notes in your question: VB.NET provides a Project-based namespace for your Modules and Classes, so your classes are now named ProjectNamespace.UnitName. If you provided a

Namespace SomeNamespace
...
End Namespace

the enclosed units would be named ProjectNamespace.SomeNamespace.UnitName.

You can have multiple Namespaces in a file too, and you can override the ProjectNamespace with Global.:

Namespace Global.TopLevelNamespace
...
End Namespace

Rereading your question and noting the "(Module?)" note as well, I'm guessing you're actually asking what is the "formal" VB.NET term for code units that include Class and Module and the similar term for a file of code. Because the .NET Module is so often equivalent to an Assembly, most people would know what you meant if you referred to "Namespace-level" code units as "modules", and source files are just "files". (There may be other places that give alternatve names, but I've based this on Microsoft's Introduction.)


问:
Is cyclomatic complexity density a good software quality metric?
Where I define Cyclomatic complexity density as:

```<code>Cyclomatic complexity density = Cyclomatic complexity / Lines of code
</code>```

I was reading previous discussions about cyclomatic complexity and there seems to be a sort of consensus that it has mixed usefulness, and as such there probably isn't a strong motive for using it over a simple lines of code (LOC) metric. I.e. As the size of a class or method increases beyond some threshold the probability of defects and of there having been poor design choices goes up.

It seems to me that cyclomatic complexity (CC) and LOC will tend to be correlated, hence the argument for use of the simpler LOC metric. However, there may be outlier cases where complexity is higher within some region of code, i.e. there is a higher density of execution branches in some pieces code (compared to the average) and I'm wondering if that will tend to be correlated with the presence of defects.

Is there any evidence for or against, or are there any experiences around the use of such a complexity density metric?

Or perhaps a better metric is to have both a LOC and a CC threshold, and we consider passing either threshold as bad.

答:
Consider the following:

```<code>define dispatch_message (message_id, message_contents)
    if (message_id == MESSAGE_ID_1)
        FirstMessageId(message_contents).dispatch()
    else if (message_id == MESSAGE_ID_2)
        SecondMessageId(message_contents).dispatch()
    ...
    else if (message_id == MESSAGE_ID_N)
        NthMessageId(message_contents).dispatch()
    else
        raise_or_throw_an_error
    end if
end function
</code>```

This function comprises 2N+5 lines of code and has a cyclomatic complexity of N+1 or N+3, depending on how you count raise_or_throw_an_error. Suppose N is 200. The complexity density is around 1/2. What does that mean? On the other hand, a function that has a line count of 4005 and a complexity of over 2000 means something.

Despite having a complexity of 2000+, my function isn't completely terrible. (Okay, it's terrible; there are more modern ways to do this.) This is surprisingly a fairly common construct in very high reliability systems. Done right, it's fairly obvious what the function is doing.

One problem with dividing SLOCs by complexity is that there's a strong correlation between SLOCs and complexity. My function is an anomaly. All that your metric will show is that my function is anomalous. At the other extreme, consider a very long auto-generated function with a cyclomatic complexity of one. These also are not that problematic in and of themselves. (It's the generator you need to look at, not the 40000 line long function.)

The two extremes of the SLOC to complexity ratio aren't the places to look for bugs. It's somewhere in the middle. Unfortunately, that's where you'll find most of your functions. SLOC and complexity give false alarms, but those false alarms are worth investigating. I don't see the same applying to your SLOC to complexity ratio metric. The buggiest of functions will most likely be hidden amongst a huge number of non-alarming functions that have a similar SLOC to complexity ratio.

Body:
Consider the following:

define dispatch_message (message_id, message_contents)
    if (message_id == MESSAGE_ID_1)
        FirstMessageId(message_contents).dispatch()
    else if (message_id == MESSAGE_ID_2)
        SecondMessageId(message_contents).dispatch()
    ...
    else if (message_id == MESSAGE_ID_N)
        NthMessageId(message_contents).dispatch()
    else
        raise_or_throw_an_error
    end if
end function

This function comprises 2N+5 lines of code and has a cyclomatic complexity of N+1 or N+3, depending on how you count raise_or_throw_an_error. Suppose N is 200. The complexity density is around 1/2. What does that mean? On the other hand, a function that has a line count of 4005 and a complexity of over 2000 means something.

Despite having a complexity of 2000+, my function isn't completely terrible. (Okay, it's terrible; there are more modern ways to do this.) This is surprisingly a fairly common construct in very high reliability systems. Done right, it's fairly obvious what the function is doing.

One problem with dividing SLOCs by complexity is that there's a strong correlation between SLOCs and complexity. My function is an anomaly. All that your metric will show is that my function is anomalous. At the other extreme, consider a very long auto-generated function with a cyclomatic complexity of one. These also are not that problematic in and of themselves. (It's the generator you need to look at, not the 40000 line long function.)

The two extremes of the SLOC to complexity ratio aren't the places to look for bugs. It's somewhere in the middle. Unfortunately, that's where you'll find most of your functions. SLOC and complexity give false alarms, but those false alarms are worth investigating. I don't see the same applying to your SLOC to complexity ratio metric. The buggiest of functions will most likely be hidden amongst a huge number of non-alarming functions that have a similar SLOC to complexity ratio.


答:
As you've found out, code works fine regardless of which file you put it in.  So it comes down to organization... where will you put things?

What I've found is that any departure from the "standard" conventions makes it very difficult to navigate through a code base of any significant size.  You say you have this little helper class, but where the hell is it?  You put it in a different solution, and I have a metadata reference to it, but where did you actually put it?  Unless you adhere strictly to the one file per class/interface/whatever, you've now forced me to do a search, and I'm coming after you with a carving knife.

This Stack Overflow post lists some of the exceptions where it might make sense to break this rule:

Partial classes,

Extension methods,

Enums that only pertain to a single class, although I still generally put those in their own file.

Title: Is it acceptable to define a "module" and "class" within a single .VB element?

Body:
Experiment:

I have found it is possible to define both a "Module" (Namespace?) and a "Class" (Namespace?) within a single .Vb element (Module??).

You can try this at home:

Create a new Console Application Project.

*A new .Vb element named "Module1.Vb" is automatically added to the project.

Add a new Class .Vb element by right-clicking on the project in Solution Explorer>Add>Class...

Give the new class the name Test.

View the code for "Test.Vb" and paste in the following:

Imports System.Runtime.CompilerServices

Module ExtensionsTest
    <Extension()>
    Public Sub ToConsole(ByVal Ex As Exception)
        Dim ForeColor As ConsoleColor
        Console.ForegroundColor = ConsoleColor.Red
        Console.WriteLine()
        Console.WriteLine("An unhandled exception has occurred!")
        Console.WriteLine(Ex.ToString)
        Console.ForegroundColor = ForeColor
    End Sub
End Module

Class Test
    Public Sub Test()
        Try
            Dim test As New Object
            test.SomeMethodDoesntExist()
        Catch ex As Exception
            ex.ToConsole()
        End Try
    End Sub
End Class
```
<p>View the Code for Module 1 and paste in the following:</p>
<pre class="lang-vb prettyprint-override"><code>Module Module1
    Sub Main()
        Try
            Dim tester As New Test
            tester.Test()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
End Module
</code>```

Now go ahead and step through or run the application.  You'll see it all works.  So, let's move on to the...

Meat of the question

Is this acceptable practice?
It may be technically possible - but is it a bad solution for reasons I don't know?  (I'm a Mort and really don't want pick up bad coding practices unwittingly)

I originally had this as a Private method within the class definition like this:

Imports System.Runtime.CompilerServices
Class Test
    Public Sub Test()
        Try
            Dim test As New Object
            test.SomeMethodDoesntExist()
        Catch ex As Exception
            ToConsole(ex)
        End Try
    End Sub

    Private Sub ToConsole(ByVal Ex As Exception)
        Dim ForeColor As ConsoleColor
        Console.ForegroundColor = ConsoleColor.Red
        Console.WriteLine()
        Console.WriteLine("An unhandled exception has occurred!")
        Console.WriteLine(Ex.ToString)
        Console.ForegroundColor = ForeColor
    End Sub
End Class
```

I decided it would be cleaner to define the ToConsole sub as an extension method for Exception objects, but that's where I ran into trouble.  When I created the Extension attribute within the Class namespace, I got a compiler error:

Extension methods can be defined only in modules.

So, I tried the above experiment and I declared a Module within the same .VB element where my Class is defined.

As the experiment above shows, this all compiles fine and works as expected, but I'd like to know if this is a good idea or not, and why?

Thanks for taking any time to read this and even more thanks for any time taken to comment or answer!


问:
what web system is the best to accommodate very high simultaneous web traffic?
Can PHP/mySQL handle 1,000,000 unique users onlinie at the same time? Or should we use a more powerful system like Zend? Or does it depend more on the web hosting systems like load balancing, etc?</p>

答:
In theory, PHP and MYSQL will handle an infinite connections query, it's more depending on your global Hardware infrastructure than on your software.

If you got a lot of HI-Perf servers with a high speed connection backbone, you'll be able to handle a lot of traffic, but, for my own experience, if you've got a website wich handle around 1Million of unique users connections, you should working on google or some other big company.

On my website, we've got an average of 15000 unique connexions with a peek at 25000 during holidays time.

OwnerDisplayName: bluestallion

ContentLicense: CC BY-SA 2.5


问:
Move file into apropriate directory based upon first letter of second word, followed by the first two letters of the second word with Python
EDIT: Apparently the below question is too specific. Let me rephrase:

I'm looking for a way to fit a letter into a list of specified ranges such that, if given the letter S and the ranges A-F, G-M, N-T, U-Z, it would select the third range.

ORIGINAL QUESTION:

So let's say I have a file: John_Smith.pdf

And I have a directory hierarchy like so:

```<code>A/
B/
C/
D/
...
Z/
</code>```

And inside each of those directories there are subdirectories that further breaks files down by the first two letters rather than the first (the breakdowns are not the same in every folder). In the S/ directory, the subdirectories could look like this:

```<code>SA-SF/
SG-SM/
SN-ST/
SU-SZ/
</code>```

How can I, using Python, put John_Smith.pdf into the appropriate directory (S/SG-SM/)? It would be preferable for this to be as OS agnostic as possible (e.g. using os.path.join instead of hard coding '/' or '\'. )

Thanks!

答:
I found the answer here. Python actually has this functionality built in. For example

'A' < 'F' # Returns true because A comes before F

Thus one can use the function

```<code>def is_in_range(range, letter):
    return range[:2] <= letter <=range[3:5]

is_in_range('SA-SF','SM')
False

is_in_range('SG-SM','SM')
True
</code>```

Note: Case will screw this up so .upper() will be needed

Body:
I found the answer here. Python actually has this functionality built in. For example

'A' < 'F' # Returns true because A comes before F

Thus one can use the function

def is_in_range(range, letter):
    return range[:2] <= letter <=range[3:5]

is_in_range('SA-SF','SM')
False

is_in_range('SG-SM','SM')
True

Note: Case will screw this up so .upper() will be needed


问:
"Party on my branch" workflow support in mercurial
When I'm on a git project, I have a workflow that goes something like this:

Start a new feature (open a new branch)

Write some code, commit some code, repeat

Push the code to a remote, possibly with my initials in the branch name, and 'WIP' commits, indicating that it's unfinished

Once things start taking shape, squash commits together, change their messages, delete them, rearrange them, etc.

Keep working

Decide things are ready for review, submit a pull/merge request (possibly after force-pushing to destroy my old, work-in-progress, branch)

Get some review, put more changes that came from that review on top

Get approval to merge the branch

Merge the branch. Bask in the beautiful history of the feature it is that I just merged, but never rewrite history on the master/default branch (unless I'm the only one on the project)

Is this workflow supported in mercurial? How about without plugins? I'm fairly new to mercurial, but I know enough (and lean on this cheatsheet enough) to get what I want to get done. However I'm not able to use this workflow. There is much care in crafting the perfect commit, and just piling stuff on top of it because otherwise I seem to get error messages. This seems to be by design, but I'd really rather use my workflow for my branches.. and then conform to the type of history management (e.g. merges/rebases/no rewriting) for branches that many people work on.

答:
Firstly, you will be working on the default branch most likely.

You can create a bookmark for your "branch"

You can push that bookmark to another repository. People can look at it.

When you are ready to rewrite the history you would use the MQ extension.

You can pop off all the changes you want to rewrite, change their commit notes, squash them together, then reapply them.

When you are done, delete the bookmark from the remote and create a new bookmark

Unfortunately this will leave a dangling head, you will have to run a strip command on your local and remote and on any repo that pulled in your "branch" to get rid of the old "branch"

When you are ready to merge push your bookmark and ask that it be merged with the main head of the default branch.

It's a really awkward workflow for HG because it creates lots of heads that require stripping.


问:
Use cases and multi service architecture
I've recently finished reading "writing effective use cases" by Alistair Cockburn.

I'm looking at building a web application that sits upon 2 web services. Should I have use cases for "web application requests data from service" that corresponds to "user wants data from web application".

I see 3 options.

Treat the underlying systems as actors and mention them in a whitebox fashion. E.g. user submits to webapp and webapp transmits to web service.

Treat them as blackbox and write the submission use case for the user and a transmission use case for the webapp

Treat it as too low of a use case, too much implementation details and just treat the webapp as a black box for use cases. Service behavior descriptions belong elsewhere.

Maybe other options. Does anyone have experience? Or a better understanding of how use cases should be written when dealing with multiple applications that are considered part of a single system.

答:
I like Option 2.

But then you must treat the back end service as a separate system, with its own use cases, requirements, stakeholders  etc.

This is probably a good idea if you think you may need to support other front ends such as iPhone and Andriod apps or even a Windows Desktop at some future time.


答:
I have seen colleges try to cover every single possible exception and error condition in every use case and sequence diagram. The result has always been late delivery, hours spent in review and in the end very little benefit to the project.

One way of thinking about it ala "Black Swan" by N. Taleb is that there are just too many possible disasters waiting to happen; the ant-virus software renders the machine unusable, the data centre could flood, admin forgot to pay the electricity bill, you company gets borked by a competitor etc. etc.

Another way to think about it is there are only thee exceptions.

The service is unavailable.

The service failed before your request could be processed.

The service failed after your request was processed.

While cases 2 and 3 have very different outcomes its usually impossible to tell the difference without further manual investigation.

Title: How to show retry in sequence diagram

Body:
I am drawing sequence diagram for large integration project where one system will initiate the REST call to another system and there is a proxy in middle which will pass through the request like

A->b->C

where b is a pass through system. I have shown 200 returned from C->b->A. I am wondering how do I depict when C returns 500 or there is an IOException and A needs to retry n no of times before it gives up.


问:
MVC is a kind of Design Pattern?
While I was trying to concrete the concept of design pattern, I came up with a question: As I asked in the title, Is MVC(Model-View-Controller) architecture kind of Design Pattern?</p>

答:
The Timeless Way of Building, which introduced the idea of Patterns was written in 1979, and it took another decade until programmers started to take Christopher Alexander's ideas and apply it to software (Design Patterns: Elements of Reusable Object-Oriented Software was released in 1994).

The original MVC paper(s) were written starting in 1978, before the introduction of the concept of Patterns and ~15 years before this concept reached the programming world. So, Trygve Reenskaug certainly did not think about it as a Pattern.

However, in modern terms, I would characterize it mainly as a User Interaction Design Pattern, which also influences Software Architecture and Software Design, so it also has some traits of a Software Architecture Pattern and a Software Design Pattern. But the main focus of MVC is User Empowerment and the Direct Manipulation Metaphor, both of which have nothing to do with Architecture or Design, they are all about User Interaction.

Title: MVC is a kind of Design Pattern?


答:
Yes and no and it depends. MVC is one of the terms which once had a very specific meaning, but then have grown in use to become a much broader and less specific term.

The original use of MVC was specifically as a oo design pattern used when coding desktop GUIs in Smalltalk. The pattern was specifically concerned about separating the data displayed in a form from the UI controls used to display the data, and the input gestures (mouse clicks etc.) used by the user. This was an early attempt to structure GUI code, and many more refined GUI patterns have developed since (patterns like Model-View-Presenter, Model-View-Viewmodel and so on). Martin Fowler have written a nice overview of the history of the MVC pattern as used in GUIs.

Later someone decided to reuse the term MVC for structuring web applications a certain way. It is not really the same pattern, but you can say that web MVC was inspired by the separation of concerns in the original MVC. It is more of an architecture than a classic pattern though. You will get really confused if you try to apply your understanding of the original MVC pattern to how the terms are used in MCV web apps - for example what is called the view in web-MVC corresponds more or less to the model in classic MVC.

Now MVC is often used to describe a whole web application framework, like in Microsofts Asp.net MVC framework.

Even then, some old timers continue to use the term MVC for a specific patten used when developing desktop GUI code. So in short, MVC can mean very different things depending on who you ask.

Title: MVC is a kind of Design Pattern?

Body: While I was trying to concrete the concept of design pattern, I came up with a question: As I asked in the title, Is MVC(Model-View-Controller) architecture kind of Design Pattern?</p>


问:
File sharing web application - folder PIN code entry best practice
I'm developing a web app for internal file sharing and one of the requirements is to have PIN code protected folders.

What I came up now is a folder like structure with the following:

Folder without PIN code entry - only Open button which directly forwards to the folder

Folder with PIN code entry - text field with Verify button which forwards only when the PIN is correct

What I'm not sure is what would be the best practice in the case of the folder with PIN code in terms of PIN verification and forwarding user to the folder. At the moment I have a web service to which I forward PIN, folder ID and user ID, all in cleartext format and I'm waiting for the service response which can either be true or false.

I'm assuming that this isn't the best practice as the smart but naughty user could loop through all the possible combinations of the PIN code and wait which one will give him true as a response. I have to add that only authenticated users can access folders so in worst case I'd know with whose user the breach was made.

What should I do to improve security and is there something I could do better?

答:
I'm assuming that this isn't the best practice as the smart but naughty user could loop through all the possible combinations of the PIN code and wait which one will give him true as a response.

This is called a "brute-force" attack. In principle, it is impossible to prevent brute-force attacks. There is simply no way to set up a password scheme that does not allow people to try entering random passwords and see what happens. But you can make it ridiculously hard for someone to work out what anyone else's password is.

This Security.SE answer is the ultimate introduction on how to securely store user passwords, and these PIN numbers are essentially per-folder passwords. I'll try to give you a quick summary of the key points here.

When we talk about storing user passwords in a "cryptographically secure" way, the goals we usually have in mind are:

Making a brute force attack as hard as possible without unduly inconveniencing legitimate users.

Making sure there is no "shortcut", i.e. no attack that's more effective than brute force.

I don't know how far you want to go with security for per-folder PINs, but the concrete measures you can take basically amount to:

If a user enters too many invalid PIN numbers in a row, do not allow any additional attempts for a while. This is a very easy way of preventing the simplest brute force attacks.

Require longer PIN numbers. Obviously, if you only have four digit PINs, there simply aren't that many different numbers to try, and it's unlikely the rest of the measures on this list would help much with that.

Next, do not store the actual PIN numbers anywhere. Instead, whenever the user enters a PIN, run it through a tried-and-true password hashing function (PBKDF2, bcrypt or scrypt) on the server, and store only the hash. If someone ever gets access to your database, this ensures they can't simply look up everyone's PIN numbers, or easily derive the PIN numbers from the PIN hashes.

Then, configure the hashing function to be as slow as possible without inconveniencing your users. The idea is that trying a single password should take half a second rather than a millisecond. Then, if someone manages to dump your database and tries a brute force attack directly on the data (where you have no way of locking them out after too many failures), it will take them an impossibly long time to try every password.

Finally, add "salts" into the process to combat rainbow tables. I highly doubt you want to go this far, so I won't bother explaining that one.

I suspect that for PIN numbers, the first two steps might be enough for you, but the rest would still improve security. And for real user account passwords, please do go all the way.

Of course, this only deals with the most common threats that we want to protect passwords against. It doesn't do anything about man in the middle attacks or social engineering, for instance. But it probably covers the cases you're worried about.


问:
Fine grained search over a large dataset
I have roughly 4 million records per day and have to keep 7 years worth online, so we are looking at 10.2 billion records that I need to be able to search through. The users are expecting that the search will be quick enough for a UI, results in 3-5s

Due to politics out of my control, I can't use an off the shelf database solution because it means I will have to give the database to another team to manage (don't ask) which means I loose the ability to optimize hardware and software as they have a one-size-fits-all service for databases and charge (internally) by the GB. I'm sure I am going to get comments suggesting I make the point, I already have and management understand what they are asking me to do is ridiculous.

I have been looking at using Lucene as the crux of my solution. Storing the actual data partitioned by type and by day in flat files. Then using a Lucene document to index some of the fields that are searched by, with the only "Stored" field being the id of the record (so that I can read it from the flat file)

I am not exactly clued up on Lucene or hard drives, but as per my understanding, there will be initial IO/seeking time for searching the index, then when I have all the Lucene document IDs, I read the documents which will incur further IO/seeking time, then I read the actual record from the flat flat...I can't imagine, given the size of the dataset, that this will be very quick, which I am slightly worried about?

Lucene has a max document size of 2.1billion per index, so I will require multiple indicies here.

Does this approach, on the face of it, look like it could work?

The data I am storing is event-action data. Most of the queries will be grouping by event id and getting the last event-action details for a particular event. Some of the queries will be analysing large sets events and their individual event-actions.

答:
Thinking from the front end ...

If you separate your lookup types in the UI, you might be able to have more reasonable constraints.

It sounds like one lookup type is recent event-action data on an event, which allows you to isolate by time in your data search. This perhaps gives a much smaller set of data, with the likely expectation of a user that it be retrieved somewhat soon.

Other kinds of lookup, wherein large data set or old time frame searches need to be accomplished can be given a different UI (or several UI's), with a nice spinner to indicate ... thinking now. As this can be understood by the user to be a more laborious set of requirements, patience might be reasonably expected. And of course, realistically necessary.

I don't know if you have any ability to impact the front-tend design, but if you can convey the constraints you are working with, hopefully those who handle the user interaction will respond with understanding (at least some).


问:
How do I handle setters on immutable fields?
I have a class with two readonly int fields.  They are exposed as properties:

```<code>public class Thing
{
    private readonly int _foo, _bar;

    /// <summary> I AM IMMUTABLE. </summary>
    public Thing(int foo, int bar)
    {
        _foo = foo;
        _bar = bar;
    }

    public int Foo { get { return _foo; } set { } }

    public int Bar { get { return _bar; } set { } }
}
</code>```

However, that means that the following is perfectly legal code:

```<code>Thing iThoughtThisWasMutable = new Thing(1, 42);

iThoughtThisWasMutable.Foo = 99;  // <-- Poor, mistaken developer.
                                  //     He surely has bugs now. :-(
</code>```

The bugs that come from assuming that would work are sure to be insidious.  Sure, the mistaken developer should have read the docs.  But that doesn't change the fact that no compile- or run-time error warned him about the problem.

How should the Thing class be changed so that devs are less likely to make the above mistake?

Throw an exception?  Use a getter method instead of a property?

答:
Two solutions.

Simple:

Don't include setters as noted by David for immutable readonly objects.

Alternatively:

Allow setters to return a new immutable object, verbose in comparison to the former but provides state over time for each initialised object. This design is a very useful tool for Thread safety and immutability which extends over all imperative OOP languages.

Pseudocode

```<code>public class Thing
{

{readonly vars}

    public Thing(int foo, int bar)
    {
        _foo = foo;
        _bar = bar;
    }

    public Thing withFoo(int foo) {
        return new Thing(foo, getBar());
    }

    public Thing withBar(int bar) {
        return new Thing(getFoo(), bar)
    }

    etc...
}
</code>```

public static factory

```<code>public class Thing
{

{readonly vars}

    private Thing(int foo, int bar)
    {
        _foo = foo;
        _bar = bar;
    }

    public static with(int foo, int bar) {
        return new Thing(foo, bar)
    }

    public Thing withFoo(int foo) {
        return new Thing(foo, getBar());
    }

    public Thing withBar(int bar) {
        return new Thing(getFoo(), bar)
    }

    etc...
}
</code>```

Body:
Two solutions.

Simple:

Don't include setters as noted by David for immutable readonly objects.

Alternatively:

Allow setters to return a new immutable object, verbose in comparison to the former but provides state over time for each initialised object. This design is a very useful tool for Thread safety and immutability which extends over all imperative OOP languages.

Pseudocode

public class Thing
{

{readonly vars}

    public Thing(int foo, int bar)
    {
        _foo = foo;
        _bar = bar;
    }

    public Thing withFoo(int foo) {
        return new Thing(foo, getBar());
    }

    public Thing withBar(int bar) {
        return new Thing(getFoo(), bar)
    }

    etc...
}

public static factory

public class Thing
{

{readonly vars}

    private Thing(int foo, int bar)
    {
        _foo = foo;
        _bar = bar;
    }

    public static with(int foo, int bar) {
        return new Thing(foo, bar)
    }

    public Thing withFoo(int foo) {
        return new Thing(foo, getBar());
    }

    public Thing withBar(int bar) {
        return new Thing(getFoo(), bar)
    }

    etc...
}


问:
How to write procedural code in an object oriented language?
I recently started working in domain of mesh generation . My programs usually contains large chunks of procedural code consisting of several phases. Eg.

```<code>class MeshAlgo1
{
    /* A very long function */
    void DoSomething(MeshData data)
    {
       // Phase 1
       ...
       // Phase 2
       ...
       // Phase N

    }
};
</code>```

I would like to break down these long member functions into smaller functions for better readability and maintainability.

```<code>class MeshAlgo1
{
    /* Shorter function! :-) */
    void DoSomething(MeshData data)
    {
       DoSomething1();
       //...
       DoSomething2();
       //...
       DoSomethingN();
    }
};
</code>```

But since this code is procedural, DoSomething1(), DoSomething2(),etc would not be independent of each other, and so do not fit into OOP style. That is, DoSomething2() assumes that DoSomething1() has been called before it. I would like to know what is the correct way of writing such code in Object Oriented style. Thanks a lot.

答:
When you are afraid that someone might call the methods in the wrong order, it seems to indicate that each of the private method transforms the data from one state into a different state. When that is the case you could represent each of these states with a different type. Each method would then accept an object of the previous state as input and return an object which represents the data in a different state as output. This would look like this:

```<code>private MeshDataState1 DoSomething1(MeshDataState0 data) {
    //...
}

private MeshDataState2 DoSomething2(MeshDataState1 data) {
    //...
}

private MeshDataStateFinal DoSomething3(MeshDataState2 data) {
    //...
}

public DoEverything(MeshDataState0 data) {

    MeshDataState1 dataState1 = DoSomething1(data);

    MeshDataState2 dataState2 = DoSomething2(dataState1);

    MeshDataStateFinal dataStateFinal = DoSomething3(dataState2);
}
</code>```

However, a more faithful implementation of the object-oriented paradigm would be when each state would have the method to transform itself to the next state:

```<code>public DoEverything(MeshDataState0 data) {

    MeshDataState1 dataState1 = data.toState1();

    MeshDataState2 dataState2 = dataState1.toState2();

    MeshDataStateFinal dataStateFinal = dataState2.toStateFinal();
}
</code>```

or shorter and without the intermediate variables:

```<code>public DoEverything(MeshDataState0 data) {

    MeshDataStateFinal dataStateFinal = data.toState1().toState2().toStateFinal();
}
</code>```

Body:
When you are afraid that someone might call the methods in the wrong order, it seems to indicate that each of the private method transforms the data from one state into a different state. When that is the case you could represent each of these states with a different type. Each method would then accept an object of the previous state as input and return an object which represents the data in a different state as output. This would look like this:

private MeshDataState1 DoSomething1(MeshDataState0 data) {
    //...
}

private MeshDataState2 DoSomething2(MeshDataState1 data) {
    //...
}

private MeshDataStateFinal DoSomething3(MeshDataState2 data) {
    //...
}

public DoEverything(MeshDataState0 data) {

    MeshDataState1 dataState1 = DoSomething1(data);

    MeshDataState2 dataState2 = DoSomething2(dataState1);

    MeshDataStateFinal dataStateFinal = DoSomething3(dataState2);
}

However, a more faithful implementation of the object-oriented paradigm would be when each state would have the method to transform itself to the next state:

public DoEverything(MeshDataState0 data) {

    MeshDataState1 dataState1 = data.toState1();

    MeshDataState2 dataState2 = dataState1.toState2();

    MeshDataStateFinal dataStateFinal = dataState2.toStateFinal();
}

or shorter and without the intermediate variables:

public DoEverything(MeshDataState0 data) {

    MeshDataStateFinal dataStateFinal = data.toState1().toState2().toStateFinal();
}


问:
what the best practice in REST to append or delete to a list
Suppose

GET /users/<id>

{
  user_id : "asdasdas-da-sd-asd-as-d",
  firs_name : "asdasd",
  ....
  department : [{
      id : "asdas-da-sdasd-asd",
      name : "asdasdasdasd",
      ...
      },]
}
```

<p>To add a new department for that user first create a department by:</p>

```POST /departments/
```

<p>Then we use <code>PATCH</code> with department <strong>id</strong></p>

<pre class="lang-js prettyprint-override"><code>PATCH /users/<id>

{
   department : [
    "asdas-da-sdasd-asd", // #Existing department ids
    "new-one-id"     // # New ID
 ]
}
</code>```

Is this method ok?

What is the best way to manage these in API side and considering the easiness in client side?

Or follow something like:

```<code>POST/PUT to  /user/<id>/departments/[<id>]
</code>```

to add/update the department

or

```<code>DELETE to /user/<id>/departments/<id>
</code>```

to remove that dept from list

we do not use DELETE, but only make the field active using PATCH or PUT

答:
To list the user departments

Use GET /users/<id>/departments, instead of returning this info in the users resource.

Doing so allow the below topics to work well in the most RESTful manner - the user-departments relation will always be available under /users/<id>/departments, instead of sometimes available under /users/<id>.

To assign an department to a user

The best design, IMO, is a PUT /users/<id>/departments/<id>:

The PUT method is idempotent - if you do it more than once, the result will always be the same;

By declaring in the URL the department you want to add, the request body can be empty - unless you need to parameterize this relation somehow;

Be sure to always return an 200 OK (instead of a 201 Created the first time), so the request is always the same

To remove an department from a user

Keep doing DELETE /users/<id>/departments/<id>.

It doesn't matter what your server is doing (deleting or flagging the user-departments relation).

The proposal of the DELETE method is to make something unavailable from now on.


答:
So, first let's clearly re-state the problem in terms of its requirements:

The system shall store a minimum of 4M records per day.

The system shall provide a search interface to the user

2.1 The search capability shall return results in a maximum of 3s

The system shall be capable of searching a minimum of 10.2 billion records

The system shall use a custom-designed database

4.1 The system shall have hardware and software optimized for the database to be developed

There are probably additional non-functional requirements, as well as details on how big the individual records are, which are probably relevant to your situation.

The short answer is that you have a requirements problem. If you look at these requirements, three of them (the first three) apply correctly to the system to define its function and behavior.  The last requirement is not a valid requirement from a purist perspective, but I have seen these types of requirements put into statements of work.

So, the way this problem is solved is to estimate the cost of the 4th requirement, given the other three. Once you do that, present that as your solution cost. Management will panic and immediately ask you why the problem can't be solved for a reasonable price. That is the entry point for your discussion on what needs to happen. Have an affordable alternative available and ready to present.

This is in contrast to what you are doing right now, which is assuming the other three can't be met given the last one. Management doesn't get it, because all they see are dollar signs.

Title: Fine grained search over a large dataset

Body:
I have roughly 4 million records per day and have to keep 7 years worth online, so we are looking at 10.2 billion records that I need to be able to search through. The users are expecting that the search will be quick enough for a UI, results in 3-5s

Due to politics out of my control, I can't use an off the shelf database solution because it means I will have to give the database to another team to manage (don't ask) which means I loose the ability to optimize hardware and software as they have a one-size-fits-all service for databases and charge (internally) by the GB. I'm sure I am going to get comments suggesting I make the point, I already have and management understand what they are asking me to do is ridiculous.

I have been looking at using Lucene as the crux of my solution. Storing the actual data partitioned by type and by day in flat files. Then using a Lucene document to index some of the fields that are searched by, with the only "Stored" field being the id of the record (so that I can read it from the flat file)

I am not exactly clued up on Lucene or hard drives, but as per my understanding, there will be initial IO/seeking time for searching the index, then when I have all the Lucene document IDs, I read the documents which will incur further IO/seeking time, then I read the actual record from the flat flat...I can't imagine, given the size of the dataset, that this will be very quick, which I am slightly worried about?

Lucene has a max document size of 2.1billion per index, so I will require multiple indicies here.

Does this approach, on the face of it, look like it could work?

The data I am storing is event-action data. Most of the queries will be grouping by event id and getting the last event-action details for a particular event. Some of the queries will be analysing large sets events and their individual event-actions.


答:
In my opinion, these methods themselves (as separate entities) mustn't be aware of any change of state. The concern with state should be in the form of a conditional invocation.

I may be wrong, I may be under-thinking it, but I'd simply structure it like so:

```<code>class MeshAlgo1
{
    void DoSomething(MeshData data)
    {
       DoSomething1();

       if(data.ReadyForSomething2)
           DoSomething2();

       if(data.ReadyForSomething3)
           DoSomething3();
    }
};
</code>```

Where .ReadyForSomething2 is the change in state that occurred as the result of a 'successful' call to DoSomething1().

Title: How to write procedural code in an object oriented language?

Body:
I recently started working in domain of mesh generation . My programs usually contains large chunks of procedural code consisting of several phases. Eg.

```<code>class MeshAlgo1
{
    /* A very long function */
    void DoSomething(MeshData data)
    {
       // Phase 1
       ...
       // Phase 2
       ...
       // Phase N

    }
};
</code>```

I would like to break down these long member functions into smaller functions for better readability and maintainability.

```<code>class MeshAlgo1
{
    /* Shorter function! :-) */
    void DoSomething(MeshData data)
    {
       DoSomething1();
       //...
       DoSomething2();
       //...
       DoSomethingN();
    }
};
</code>```

But since this code is procedural, DoSomething1(), DoSomething2(),etc would not be independent of each other, and so do not fit into OOP style. That is, DoSomething2() assumes that DoSomething1() has been called before it. I would like to know what is the correct way of writing such code in Object Oriented style. Thanks a lot.

Body:
In my opinion, these methods themselves (as separate entities) mustn't be aware of any change of state. The concern with state should be in the form of a conditional invocation.

I may be wrong, I may be under-thinking it, but I'd simply structure it like so:

class MeshAlgo1
{
    void DoSomething(MeshData data)
    {
       DoSomething1();

       if(data.ReadyForSomething2)
           DoSomething2();

       if(data.ReadyForSomething3)
           DoSomething3();
    }
};

Where .ReadyForSomething2 is the change in state that occurred as the result of a 'successful' call to DoSomething1().


问:
Is Open Data Protocol (odata) Being Widely Embraced by the Development Community?
EDIT: In case you aren't familiar with OData, here you go.

I am trying to determine whether it is worth learning this technology or if it is something that is not going to catch on.

The premise is interesting, and as a developer of APIs it seems like a good way to offer more flexibility to the developers that consume them.

Unfortunately, I am not seeing much "buzz" regarding Open Data Protocol in the past couple of years so just trying to gauge if it has any chance of being around once I learn it.

答:
Given that:

The two "big name" implementors, Netflix and Ebay, abandoned it a couple of years ago and excitement for OData pretty much died with their departure,

OData is a RESTful way of exposing a query mechanism through an abstraction layer. Such abstractions are now widely seen as leaky abstractions, which are a clear anti-pattern,

I'd suggest OData is slowly dying, if not dead already.


答:
Though I agree to @Philipp that a more explicit passing of parameters can solve the problem, procedural code tends to work on some "global data" (or some member variables), and changing this might have a too big impact on the exsiting code base to be done easily. For this case, I can think of a different approach to solve this:

DoSomething2() assumes that DoSomething1() has been called before it.

But why? Maybe DoSomething1 has to initialize a member variable which is expected to be initialised by DoSomething2:

```<code>class MeshAlgo1
{
    MyMesh mesh;

    private void DoSomething1()
    {
        mesh=new MyMesh();
        // initialize `mesh`
    }

    private void DoSomething2()
    {
        // ... prepare Phase 2 here ...
        // ...
        mesh.DoSomethingSpecial();
        // ...
    }
}
</code>```

So if you are afraid of someone changing unintentionally the order, you can add a run time check to your method to make it fail more fast and signale more clearly what went wrong:

```<code>    private void DoSomething2()
    {
        if(mesh==null)
           throw new Exception("mesh has to be initialized before calling DoSomething2");
        // ... prepare Phase 2 here ...
        // ...
        mesh.DoSomethingSpecial();
        // ...
    }
</code>```

Additionally, proper naming of your methods will help, and adding a comment about the necessary preconditions will also lower the risk of getting the order wrong.

What you do not get this way is a compile time check for the order, of course, but in lots of real-world scenarios a run time check is all you need.

Body:
Though I agree to @Philipp that a more explicit passing of parameters can solve the problem, procedural code tends to work on some "global data" (or some member variables), and changing this might have a too big impact on the exsiting code base to be done easily. For this case, I can think of a different approach to solve this:

DoSomething2() assumes that DoSomething1() has been called before it.

But why? Maybe DoSomething1 has to initialize a member variable which is expected to be initialised by DoSomething2:

class MeshAlgo1
{
    MyMesh mesh;

    private void DoSomething1()
    {
        mesh=new MyMesh();
        // initialize `mesh`
    }

    private void DoSomething2()
    {
        // ... prepare Phase 2 here ...
        // ...
        mesh.DoSomethingSpecial();
        // ...
    }
}

So if you are afraid of someone changing unintentionally the order, you can add a run time check to your method to make it fail more fast and signale more clearly what went wrong:

    private void DoSomething2()
    {
        if(mesh==null)
           throw new Exception("mesh has to be initialized before calling DoSomething2");
        // ... prepare Phase 2 here ...
        // ...
        mesh.DoSomethingSpecial();
        // ...
    }

Additionally, proper naming of your methods will help, and adding a comment about the necessary preconditions will also lower the risk of getting the order wrong.

What you do not get this way is a compile time check for the order, of course, but in lots of real-world scenarios a run time check is all you need.


问:
Can I remove the "above copyright notice..." section from the ISC license?
The start of the ISC license is:

Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

I'm not interested in attention or credit, so I'd like to remove the line:

provided that the above copyright notice and this permission notice appear in all copies

Simplifying the start to:

Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted.

Does this "damage" the ability of people to use the code in any way?

In the BSD license, this would be turning:

Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

Into:

Redistribution and use in source and binary forms, with or without
  modification, are permitted.

But I prefer the ISC license as it is shorter.

答:
It's not a good idea. You would be fundamentally changing the license. I would guess that the original license text was written or reviewed by lawyers so that it would be acceptable to use and perhaps even stand up if legally challenged.

Licenses work by copyright. You own the copyright to the work, but you are granting other people permission to use the work that you own under a set of conditions. It seems like being able to track the actual owner of the copyright as the software is distributed and moved around is vitally important should there be any questions that arise.

Based on places I've worked, open source licenses may need legal review, with some common licenses already reviewed and allowed (with certain restrictions). Modifying the text changes the license - what you have is not the ISC license anymore - which would mean it would need review by legal. Without ownership identified, I don't see it being allowed for use.


问:
Who should write Unit Tests?
Should unit tests be written by the developer who wrote the code or someone else ? And how effective is writing units tests as a method of learning a new system ?</p>

答:
@CarlManaster has the right idea: It's the responsibility of the developer to:

write a unit test,

verify that it fails,

implement it,

verify that it succeeds,

refactor the feature without failing the test, and finally

refactor the test code

for every feature. The reason for each of these can be summarised as follows:

Writing the test before the code ensures that the problem is sufficiently understood to actually do the right thing. You can still do exploratory programming, but TDD means you then have to throw away the result and start again by writing tests.

If your test doesn't fail before implementing the feature, you typically are either testing the wrong thing or you don't understand the problem well enough.

Implementing the actual feature is kind of the point :)

Verifying that the test now succeeds makes sure that you have a short cycle to fix it.

Refactoring is crucial to make sure the complexity of your application doesn't get out of hand. If you have tests for every feature refactoring them shouldn't break anything.

Test code should be refactored for the same reason as above. This can be tricky since you need to make sure the tests still test the same things as before. One way to avoid breaking them is, for each test that you touch (directly or indirectly), to break it by changing for example a single character in the expected output, and running it to see that it fails for the right reason. Then just undo the change, and the test should still pass and still do the right thing.

Title: Who should write Unit Tests?


答:
Directly testing your own code is good form, and a system that encourages someone other than the developer to test it is a hazard, as the code may not even be testable without heavy modifications.

That said, expanding a project's unit test suite is a great way to get yourself on board with now it works.

TDD style test first coding works very well in a situation where you have a specific feature that has been described in detail that needs to be implemented, but it isn't going to help with more in depth architectural decisions.

Title: Who should write Unit Tests?

Body: Should unit tests be written by the developer who wrote the code or someone else ? And how effective is writing units tests as a method of learning a new system ?</p>


答: Others mention methods for classes which is the Object Oriented way. Sounds like your task is to safely order the procedures. Well, a procedure is (abstractly) a behavior of an object.  Are you locked into a single class to manage these procedures as methods, or can you create two classes? Say, DoerOne withDoerOne::DoSomethingOne(), and DoerTwo withDoerTwo::DoSomethingTwo().  Now, with two objects of different class types, the problem of sequencing your procedures becomes sequencing the lifecycle of those two objects (e.g. when each is instantiated). How would you do that?


答:
Writing unit tests is part of the design process, whether you do TDD or not. So of course it's something to be done by the developer.

Integration tests, now these can be written by someone else.

Unit tests, however, are closely related to implementation and they affect the architecture.

Because even if we don't use TDD approach in strict sense, we should still design with testability in mind, so even writing unit tests post factum still has an impact on our code.

It's not only a method of learning, it gives us precious feedback on correctness and maintainability of our code. Furthermore, unit tests are a (quite valuable actually) form of documenting it.

Title: Who should write Unit Tests?


问:
Surface Area calculations
For my program, I implemented AABB collision which works fine. When AABB collision detects a collision between 2 boxes, I want to find the surface area of portion where the 2 boxes are overlapping. Is there a simple equation to use to find out that surface area?

The main issue: So it was really easy for me to point out places to calculate to find my overlapping X and Y values to find my surface are. Just like "(|6-3|)*(|6-4|)". My issue is that I'm trying to have no conditional problems. So I was wondering if there is a formula where you can plug in all the edge points of both boxes and it will always give the surface area that is overlapping no matter how they overlap. This will save me a lot of time and be more efficient when writing my code.

NOTE:

Boxes are oriented by the axis; Therefore, the sides will always be parallel to the X and Y axis.

The edge points of Box 1 and Box 2 is all that is known; So that being said, there is no co-ordinates of where the lines are intersecting.

答:
Since a long time ago I had the same problem, I came up with this simple solution:

(In case you haven't) Create java.awt.Rectangle-Objects with correct height and width

Move the Rectangles to the coordinates your objects are located (using Rectangle.setLocation(x,y)

Call Rectangle1.intersection(Rectangle2) and let the library do your computations

Even easier:
Step 1 and 2 can be done by the constructor of java.awt.Rectangle

```<code>Rectangle r1 = new Rectangle(x1, y1, width1, height1);
Rectangle r2 = new Rectangle(x2, y2, width2, height2);
Rectangle intersectingRectangle = r1.intersection(r2);
</code>```

Title: Surface Area calculations

Body:
Since a long time ago I had the same problem, I came up with this simple solution:

(In case you haven't) Create java.awt.Rectangle-Objects with correct height and width

Move the Rectangles to the coordinates your objects are located (using Rectangle.setLocation(x,y)

Call Rectangle1.intersection(Rectangle2) and let the library do your computations

Even easier:
Step 1 and 2 can be done by the constructor of java.awt.Rectangle

Rectangle r1 = new Rectangle(x1, y1, width1, height1);
Rectangle r2 = new Rectangle(x2, y2, width2, height2);
Rectangle intersectingRectangle = r1.intersection(r2);


答:
You can use this pseudo-code even without detecting collision first (or use the it to detect collision, if inter_area==0 then there is no collision or tangent at most)</p>

```<code>double intersection_area(rectangle box1,rectangle box2) {
    double inter_area=0.0
    double box1_top=box1.get_top() //10
    double box1_bottom=box1.get_bottom() //3
    double box2_top=box2.get_top() //6
    double box2_bottom=box2.get_bottom() //2
    double inter_height=min(box1_top,box2_top)-max(box1_bottom,box2_bottom) //6-3==3
    if (inter_height)>0 {
        double box1_right=box1.get_right() //6
        double box1_left=box1.get_left() //2
        double box2_right=box2.get_right() //8
        double box2_left=box2.get_left() //3
        double inter_width=min(box1_right,box2_right)-max(box1_left,box2_left)//6-3==3
        if (inter_width>0)
            inter_area = inter_height x inter_width //3x3==9
    }
    return inter_area
}
</code>```

Title: Surface Area calculations

Body:
For my program, I implemented AABB collision which works fine. When AABB collision detects a collision between 2 boxes, I want to find the surface area of portion where the 2 boxes are overlapping. Is there a simple equation to use to find out that surface area?

The main issue: So it was really easy for me to point out places to calculate to find my overlapping X and Y values to find my surface are. Just like "(|6-3|)*(|6-4|)". My issue is that I'm trying to have no conditional problems. So I was wondering if there is a formula where you can plug in all the edge points of both boxes and it will always give the surface area that is overlapping no matter how they overlap. This will save me a lot of time and be more efficient when writing my code.

NOTE:

Boxes are oriented by the axis; Therefore, the sides will always be parallel to the X and Y axis.

The edge points of Box 1 and Box 2 is all that is known; So that being said, there is no co-ordinates of where the lines are intersecting.

Body:
You can use this pseudo-code even without detecting collision first (or use the it to detect collision, if inter_area==0 then there is no collision or tangent at most)

double intersection_area(rectangle box1,rectangle box2) {
    double inter_area=0.0
    double box1_top=box1.get_top() //10
    double box1_bottom=box1.get_bottom() //3
    double box2_top=box2.get_top() //6
    double box2_bottom=box2.get_bottom() //2
    double inter_height=min(box1_top,box2_top)-max(box1_bottom,box2_bottom) //6-3==3
    if (inter_height)>0 {
        double box1_right=box1.get_right() //6
        double box1_left=box1.get_left() //2
        double box2_right=box2.get_right() //8
        double box2_left=box2.get_left() //3
        double inter_width=min(box1_right,box2_right)-max(box1_left,box2_left)//6-3==3
        if (inter_width>0)
            inter_area = inter_height x inter_width //3x3==9
    }
    return inter_area
}


问:
What are some practical uses of the "new" modifier in C# with respect to hiding?
A co-worker and I were looking at the behavior of the new keyword in C# as it applies to the concept of hiding. From the documentation:

Use the new modifier to explicitly hide a member inherited from a base
  class. To hide an inherited member, declare it in the derived class
  using the same name, and modify it with the new modifier.

We've read the documentation, and we understand what it basically does and how it does it. What we couldn't really get a handle on is why you would need to do it in the first place. The modifier has been there since 2003, and we've both been working with .Net for longer than that and it's never come up.

When would this behavior be necessary in a practical sense (e.g.: as applied to a business case)? Is this a feature that has outlived its usefulness or is what it does simply uncommon enough in what we do (specifically we do web forms and MVC applications and some small factor WinForms and WPF)? In trying this keyword out and playing with it we found some behaviors that it allows that seem a little hazardous if misused.

This sounds a little open-ended, but we're looking for a specific use case that can be applied to a business application that finds this particular tool useful.

答: I have found it quite useful when creating a test suite for legacy code. It enables me to hide external dependencies, like querying a database inside a method that is used by other methods. To be able to test the other methods I can hide the original logic that depends on external resources without needing to add the virtual keyword to those methods in test classes.</p>


问:
C++ Iterators: Best practice to represent end of range - Last or Beyond-last?
I am writing a library which deals a lot with sub-sequences of ordered containers.

So for example I have a container (1,2,3,4,5,6) and a user wants to access (3,4,5).

I am providing the subsequence by a pair of iterators, pointing to its first and last element respectively, i.e. 3 and 5.

Since the library is written in C++ and AFAIK the std convention is to have the last iterator point beyond the last element, I am wondering if what I am doing is good practice or wether I should return a pair of iterators, pointing to the first and beyond last element respectively, i.e. 3 and 6?

Also from a programming perspective, it complicates things when using std functionality, for example to count the number of elements, I have to do:

```<code>int elementCnt = std::distance(startIt, endIt) + 1;
</code>```

答:
Follow the standard - the end is the iterator past the one you want. This allows you to use all the standard algorithms and containers without problem.

It also means your users will be able to write the code they always have (eg for (x=startIt; x != endIt; x++) and this will work as expected.

If you change this behaviour and set the last iterator to the last element, all that goes out of the window and you might as well use a different nomenclature than iterators as you're effectively changing the way everyone will expect them to work.


答:
With your convention:

every function in the algorithm library should be used changing the upper bound of the range and it can be quite error prone

it isn't easy to represent empty sequences (this was Dijkstra's argument in Why Numbering Should Start At Zero).

you can easily incur in off-by-one errors (e.g. when you take a partition of a collection).

You should stay with half-closed ranges.

Title: C++ Iterators: Best practice to represent end of range - Last or Beyond-last?

Body:
I am writing a library which deals a lot with sub-sequences of ordered containers.

So for example I have a container (1,2,3,4,5,6) and a user wants to access (3,4,5).

I am providing the subsequence by a pair of iterators, pointing to its first and last element respectively, i.e. 3 and 5.

Since the library is written in C++ and AFAIK the std convention is to have the last iterator point beyond the last element, I am wondering if what I am doing is good practice or wether I should return a pair of iterators, pointing to the first and beyond last element respectively, i.e. 3 and 6?

Also from a programming perspective, it complicates things when using std functionality, for example to count the number of elements, I have to do:

```<code>int elementCnt = std::distance(startIt, endIt) + 1;
</code>```


答:
The standard library uses one-past-the end pointers for good reason - stick to this pattern. The alternative leaves no good way to describe an empty range.

Also, unless you definitely need something different/special/written here, just use Boost.Range.


答:
You should keep conventions (definitions) used in a programming language.

Example:

```<code>#include <iterator>

template< class Iterator>
class Range
{
    public:
    typedef typename std::iterator_traits<Iterator>::value_type value_type;
    typedef Iterator iterator;

    Range(const iterator& first, const iterator& last) noexcept
    :   m_first(first), m_last(last)
    {}

    Range(iterator&& first, iterator&& last) noexcept
    :   m_first(std::move(first)), m_last(std::move(last))
    {}

    Range(Range&& other) noexcept
    :   m_first(std::move(other.m_first)),
        m_last(std::move(other.m_last))
    {}

    Range& operator = (Range&& other) noexcept {
        m_first = std::move(other.m_first);
        m_last = std::move(other.m_last);
        return *this;
    }

    iterator begin() const noexcept { return m_first; }
    iterator end() const noexcept { return m_last; }

    private:
    iterator m_first;
    iterator m_last;
};

template<typename T>
inline Range<T> range(T&& first, T&& last) noexcept {
    return Range<T>(std::forward<T>(first), std::forward<T>(last));
}

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = { 1,2,3,4,5,6 };
    for(auto i : range(v.begin() + 1, v.end() - 1))
        std::cout << i << '\n';
    for(auto i : range(v.end(), v.end()))
        std::cout << i << '\n';
}
</code>```

Without sticking to the conventions, using libraries (algorithms) or language features (range based for) becomes cumbersome. Even worse, it may lead programmers expecting the common convention into to subtle errors.
Also, there is no way to express an empty range if [first, last] are inclusive.

Body:
You should keep conventions (definitions) used in a programming language.

Example:

#include <iterator>

template< class Iterator>
class Range
{
    public:
    typedef typename std::iterator_traits<Iterator>::value_type value_type;
    typedef Iterator iterator;

    Range(const iterator& first, const iterator& last) noexcept
    :   m_first(first), m_last(last)
    {}

    Range(iterator&& first, iterator&& last) noexcept
    :   m_first(std::move(first)), m_last(std::move(last))
    {}

    Range(Range&& other) noexcept
    :   m_first(std::move(other.m_first)),
        m_last(std::move(other.m_last))
    {}

    Range& operator = (Range&& other) noexcept {
        m_first = std::move(other.m_first);
        m_last = std::move(other.m_last);
        return *this;
    }

    iterator begin() const noexcept { return m_first; }
    iterator end() const noexcept { return m_last; }

    private:
    iterator m_first;
    iterator m_last;
};

template<typename T>
inline Range<T> range(T&& first, T&& last) noexcept {
    return Range<T>(std::forward<T>(first), std::forward<T>(last));
}

#include <iostream>
#include <vector>

int main() {
    std::vector<int> v = { 1,2,3,4,5,6 };
    for(auto i : range(v.begin() + 1, v.end() - 1))
        std::cout << i << '\n';
    for(auto i : range(v.end(), v.end()))
        std::cout << i << '\n';
}

Without sticking to the conventions, using libraries (algorithms) or language features (range based for) becomes cumbersome. Even worse, it may lead programmers expecting the common convention into to subtle errors.
Also, there is no way to express an empty range if [first, last] are inclusive.


问:
How should I structure my web app for browser compatibility?
We want to be able to implement cross-browser compatibility by overriding markup, scripts and styles only where necessary. We want to avoid forking everything sent to the browser, as has been done in the past!

This has led me to a directory structure with one folder per "page", with "master" markup, script and style files, and their respective overrides, one per browser. The file names, both master and overrides, would be the same from folder to folder, and the code linking them all together can be shared (all the relevant resources can be pulled in with relative urls).

```<code>MyPage(folder)
|--Index.aspx
|--Markup.xsl
|--Markup_ie11.xsl
|--Scripts.js
|--Scripts_ie11.js
|--Styles.css
|--Styles_ie11.js
AnotherPage
|--Index.aspx
|--Markup.xsl
|--Markup_ie11.xsl
|--Scripts.js
|--Scripts_ie11.js
|--Styles.css
|--Styles_ie11.js
</code>```

I have a test project with all this working nicely, but I'm very nervous about so many same-named files, and the file name on its own giving no clue to it's purpose. Nevertheless, compared to our old organisation based on filetype, some advantages jump out: the files you're likely to work on together are stored together. The folder tree is flat. The folder names are much more meaningful, and I have less need to search. There are 1/8th the number of hardcoded paths in the application (scripts, styles and markup are pulled in with relative links).

Can anyone think of a reason not to do this ???

答:
Can anyone think of a reason not to do this ?

Some very, very big ones: For one thing, browsers will not be able to effectively cache all of these files if your pages don't reference them at the same absolute URI.

That is to say, if you have:

```<code>page1/
  index.htm  -- references script.js as "/page1/script.js"
  script.js
page2/
  index.htm  -- references script.js as "script.js"
  script.js
</code>```

... both .htm files refer only to their local copies of script.js, and you now have the problem that anyone coming to the site will have to download separate copies of each script.js for each page they visit.

This will cost you more bandwidth, and it will fill the users' browser cache and push other things out.

But it gets worse.

Now, you're maintaining multiple copies of the same script in multiple locations. This has cognitive and technical overhead: If someone new is hired, they're not going to realize that each separate copy of the script needs to be updated when changes are made, and you're going to have a ballooning number of copies of the script in your source code repository, which will only grow into a mess as time goes on.

This is a dozen kinds of bad idea.

It's also a bad idea to maintain completely separate scripts for multiple major browsers. This spreads your code out and increases the cost of maintenance, not to mention the added bandwidth cost of having lots of large files to send to browsers (which will cause you grief if you use a local server cache). Instead, you should abstract all of your browser-specific code into a single file (or a number of very small files, each for a given logical unit of code) where the specific code that handles browser differences is close to the code they need to execute.

This is how literally every JavaScript and CSS framework is written, and for good reason: It minimizes code size, and it simplifies maintenance, both of which save you money in the long run.

Any other approach is wrong.

Body:
Can anyone think of a reason not to do this ?

Some very, very big ones: For one thing, browsers will not be able to effectively cache all of these files if your pages don't reference them at the same absolute URI.

That is to say, if you have:

page1/
  index.htm  -- references script.js as "/page1/script.js"
  script.js
page2/
  index.htm  -- references script.js as "script.js"
  script.js

... both .htm files refer only to their local copies of script.js, and you now have the problem that anyone coming to the site will have to download separate copies of each script.js for each page they visit.

This will cost you more bandwidth, and it will fill the users' browser cache and push other things out.

But it gets worse.

Now, you're maintaining multiple copies of the same script in multiple locations. This has cognitive and technical overhead: If someone new is hired, they're not going to realize that each separate copy of the script needs to be updated when changes are made, and you're going to have a ballooning number of copies of the script in your source code repository, which will only grow into a mess as time goes on.

This is a dozen kinds of bad idea.

It's also a bad idea to maintain completely separate scripts for multiple major browsers. This spreads your code out and increases the cost of maintenance, not to mention the added bandwidth cost of having lots of large files to send to browsers (which will cause you grief if you use a local server cache). Instead, you should abstract all of your browser-specific code into a single file (or a number of very small files, each for a given logical unit of code) where the specific code that handles browser differences is close to the code they need to execute.

This is how literally every JavaScript and CSS framework is written, and for good reason: It minimizes code size, and it simplifies maintenance, both of which save you money in the long run.

Any other approach is wrong.


问:
Handling if-statements with a known duration
I wasn't sure exactly what to call these situations, so I'll illustrate it.

If I have something like this in a method:

```<code>if (i <= 5)
    doSomething();
else
    doSomethingElse();
</code>```

but I know that i will never be less than or equal to 5 once it exceeds 5, it becomes unnecessary to continue checking the if-statement once it branches off the first time.

Is it a good idea to implement a strategy pattern in this case, to avoid redundant checks?

```<code>class strategy1 implements strategy {

    Object obj; // stores a reference to the object that uses it

    void run() {
       if (i <= 5)
            doSomething();
        else {
            obj.strategy = new strategy2(obj);
            obj.strategy.run();
        }
    }
}

class strategy2 implements strategy {

    void run() {
        doSomethingElse();
    }

}
</code>```

and the object simply calls strategy.run()

I feel like this sacrifices some readability and simplicity for performance, but it also makes it clear that i will not fall below 6 once it hits 6, which provides some more information than the if-statement alone did. Is there a better way?

答:
What you are proposing looks like a Replace Type Code [or a conditional] with State/Strategy refactoring.

Possible reasons for doing it:

Conditionals have become complex, or are anticipated to become complex in the future.

The conditionals incur delays or tax resources.

Reasons for not doing it:

The conditionals are simple at the present, and the conditionals are not expected to become complicated in the future.

Evaluating the conditionals does not incur appreciable delays, and does not tax other resources.

At the present, the conditional i < 5 fits both reasons for not doing this refactoring.

p.s.  I think what you are describing is a kind of a state pattern rather than stategy pattern.  Having said that, state and strategy patterns have similar inner workings.  Just picking at terminology.


问:
If I use locks, can my algorithm still be lock-free?
A common definition of lock-free is that at least one process makes progress. 1

If I have a simple data structure such as a queue, protected by a lock, then one process can always make progress, as one process can acquire the lock, do what it wants, and release it.

So does it meet the definition of lock-free?

1 See eg M. Herlihy, V. Luchangco, and M. Moir. Obstruction-free synchronization: Double-ended queues as an example. In Distributed Computing, 2003. "It is lock-free if it ensures only that some thread always makes progress".

答:
The example you give is not lock-free for the following reason.

Support one thread acquires the lock, and the OS scheduler suspended the thread for a infinite lone period, then all of the thread cannot make progress because no can can acquire the lock that is acquired by the suspended thread.

Generally speaking, algorithms that use locks are not lock-free.

Note that deadlock-free and lock-free are two different concepts. deadlock-free means there is no possibility for deadlock, but there could be livelock which can prevent the whole system from making progress. Lock-freedom is stronger than that because it means some threads in the system always makes progress with finite number of steps.


问:
Why dynamic memory allocation functions in C returns void*?
Consider the prototypes of C's dynamic allocation functions

```<code>malloc - void* malloc(size_t size);

calloc -  void* calloc(size_t n,size);

realloc - void* realloc(void* ptr,size_t newsize);
</code>```

Now a statement like following

```<code>int* p=(int*)malloc(sizeof(int));
</code>```

I know that casting to (int*) isn't needed in C since a void pointer can be assigned to a pointer variable of any object type, but why these functions by default not return fully typed pointer?. Wouln't it be nice if it returns int* instead of void pointer in this case? What is the reason void* is choosen as return type of these functions?

One other question: I've read here that in older C compilers the type of pointer returned by these functions was char* not void*. Is it true?

答:
Because it can't.

How would it return a fully typed pointer? C doesn't have templates/generics, and it doesn't allow function overloading; let alone overloading by return type only. So there's no mechanism to have a malloc that knew what type you wanted.

I've read here that in older C compilers the type of pointer returned by these functions was char* not void*. Is it true?

In C, there is no byte. char is guaranteed to be a byte long, so char* is canonical "a pointer to some byte buffer", which is exactly what memory allocation functions want to return.


问:
Is Pre-Order traversal same as Depth First Search?
It seems to me like pre-order traversal and DFS are same as in both the cases we traverse from root till the left branch and back to root and then to the right branch recursively. Could any please correct me if I am wrong?

Thanks in advance!

答:
Yes, but it should be the opposite way: DFS is similar to PreOrder.

Term PreOrder is more relevant to binary trees and parsers.

It is used to compare with other traversal orders of a binary tree: InOrder, PostOrder and PreOrder.

Topological Sort is similar to Post Order traversal (push the node into stack after visiting all the adjacent nodes).


问:
What is the right testing strategy in Agile Scrum/Kanban teams?
The problem is:

The team , I am working in has 10 developers to 2 testers ratio which means we are going to churn out code more quickly than it is "Test" done.

So, What should be the right approach to track activities in such scenarios according to agile experts?

My fear is that soon the day will come , when there is a lot of stuff which will be called as "Done" in previous sprints (with no testing done) but when it actually comes to testing, there might be some potential defects.

How can I track the efforts seamlessly? Should testing be part of "Done Definition"? What are the pitfalls if it is not?

As per me, it is sort of 'Waterfall' as you are calling stories "Done" before it is actually functionally tested.

答:
When we started building our product, we also implemented Kanban, and along with that, we implemented a complete test automation strategy.  As a result, today we don't have testers in our team.  Instead, developers must write test cases and automate them as part of working on any user story, enhancement or defect.  Our definition of Dev Complete includes unit testing and functional automation.

We still have a "Validation" stage after Dev complete - where all new dev work (features, bug fixes) is deployed on a staging server and someone - anyone who has functional understanding of the feature - must validate it.  We use people from our Documentation team as well as Product Management - and sometimes Sr. Engg leads/ architects - to validate.   Each release must stay a minimum of 1 week on staging before being deployed on production.

Here is a snapshot of our Kanban board -

The process and Kanban have worked for us.  We have near 100% test automation, we have a 3-4 week production release cadence and best of all, most team members have the flexibility to work on pretty much most parts of our product!

So, while this may not meet your short term objectives, you might definitely want to look at how you can restructure your team in the long run and if not already done, then look at test-automation strategies that would definitely help your team deliver greater quality at shorter intervals.


问:
What are the ways to avoid duplication of logic between domain classes and SQL queries?
The example below is totally artificial and its only purpose is to get my point across.

Suppose I have an SQL table:

```<code>CREATE TABLE rectangles (
  width int,
  height int
);
</code>```

Domain class:

```<code>public class Rectangle {
  private int width;
  private int height;

  /* My business logic */
  public int area() {
    return width * height;
  }
}
</code>```

Now suppose that I have a requirement to show to the user the total area of all rectangles in the database.
I can do that by fetching all the rows of the table, turning them to objects and iterating over them.
But this looks just stupid, because I have lots and lots of rectangles in my table.

So I do this:

```<code>SELECT sum(r.width * r.height)
FROM rectangles r
</code>```

This is easy, fast and uses the strengths of the database.
However, it introduces duplicated logic, because I have the same calculation in my domain class also.

Of course, for this example the duplication of logic is not fatal at all.
However, I face the same problem with my other domain classes, which are more complex.

答:
You say that the example is artificial, so I don't know if what I'm saying here suits your actual situation, but my answer is - use an ORM (Object-relational mapping) layer to define the structure and querying/manipulation of your database. That way you have no duplicated logic, since everything will be defined in the models.

For example, using the Django (python) framework, you would define your rectangle domain class as the following model:

```<code>class Rectangle(models.Model):
    width = models.IntegerField()
    height = models.IntegerField()

    def area(self):
        return self.width * self.height
</code>```

To calculate the total area (without any filtering) you'd define:

```<code>def total_area():
    return sum(rect.area() for rect in Rectangle.objects.all())
</code>```

As others have mentioned, you should first code for correctness, and only optimize when you really hit a bottleneck. So, if at a later date you decide, you absolutely have to optimize, you could switch to defining a raw query, such as:

```<code>def total_area_optimized():
    return Rectangle.objects.raw(
        'select sum(width * height) from myapp_rectangle')
</code>```

Body:
You say that the example is artificial, so I don't know if what I'm saying here suits your actual situation, but my answer is - use an ORM (Object-relational mapping) layer to define the structure and querying/manipulation of your database. That way you have no duplicated logic, since everything will be defined in the models.

For example, using the Django (python) framework, you would define your rectangle domain class as the following model:

class Rectangle(models.Model):
    width = models.IntegerField()
    height = models.IntegerField()

    def area(self):
        return self.width * self.height

To calculate the total area (without any filtering) you'd define:

def total_area():
    return sum(rect.area() for rect in Rectangle.objects.all())

As others have mentioned, you should first code for correctness, and only optimize when you really hit a bottleneck. So, if at a later date you decide, you absolutely have to optimize, you could switch to defining a raw query, such as:

def total_area_optimized():
    return Rectangle.objects.raw(
        'select sum(width * height) from myapp_rectangle')


问:
what web system is the best to accommodate very high simultaneous web traffic?
Can PHP/mySQL handle 1,000,000 unique users onlinie at the same time? Or should we use a more powerful system like Zend? Or does it depend more on the web hosting systems like load balancing, etc?</p>

答:
If you have 1 million simultaenous users, that means you'd need to be getting at least 300 million visitors a day (and close to a billion pages per day)*. When you're in those numbers, then you're Facebook or Google and at that point, it doesn't matter what language or framework you used to begin with, because you're pretty much running on your own platform by the time you get that big.

Remember, Facebook started off with PHP and as they scaled up, eventually they ended up writing a compiler to translate PHP into C++ code, and compile that to run on the server.

However, when you're just starting out, your first priority is to become popular: you don't become popular overnight and you'll have plenty of time to adapt your design to scale with your popularity.

* Just back-of-an-envelope calculation...


问:
How much should I be using 'let' vs 'const' in ES6?
I've been writing a lot of ES6 code for io.js recently. There isn't much code in the wild to learn from, so I feel like I'm defining my own conventions as I go.

My question is about when to use const vs let.

I've been applying this rule: If possible, use const. Only use let if you know its value needs to change. (You can always go back and change a const to a let if it later turns out you need to change its value.)

The main reason for this rule is it's easy to apply consistently. There are no grey areas.

The thing is, when I apply this rule, in practice 95% of my declarations are const. And this looks weird to me. I'm only using let for things like i in a for loop, or occasionally for things like accumulated Fibonacci totals (which doesn't come up much in real life). I was surprised by this – it turns out 95% of the 'variables' in my ES5 code to date were for values that do not vary. But seeing const all over my code feels wrong somehow.

So my question is: is it OK to be using const this much? Should I really be doing things like const foo = function () {...};?

Or should I reserve const for those kind of situations where you're hard-coding a literal at the top of a module – the kind you do in full caps, like const MARGIN_WIDTH = 410;?

答:
Be careful, because const object keys are mutable.

From here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

object keys are not protected

consider this example:

```<code>const colors = {red: "#f00"};
console.log(colors); // { "red": "#f00" }

colors.red = "#00f";
colors.green = "#0f0";
console.log(colors); // { "red": "#00f", "green": "#0f0" }
</code>```

Same thing for arrays:

```<code>const numbers = [1, 2, 3];
console.log(numbers); // [ 1, 2, 3 ]

numbers.push(4);
console.log(numbers); // [ 1, 2, 3, 4 ]
</code>```

I haven't decided totally myself, but I'm considering using const for all non-array/non-objects and use let for objects/arrays.

Body:
Be careful, because const object keys are mutable.

From here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

object keys are not protected

consider this example:

const colors = {red: "#f00"};
console.log(colors); // { "red": "#f00" }

colors.red = "#00f";
colors.green = "#0f0";
console.log(colors); // { "red": "#00f", "green": "#0f0" }

Same thing for arrays:

const numbers = [1, 2, 3];
console.log(numbers); // [ 1, 2, 3 ]

numbers.push(4);
console.log(numbers); // [ 1, 2, 3, 4 ]

I haven't decided totally myself, but I'm considering using const for all non-array/non-objects and use let for objects/arrays.


问:
Floating Point representation -128+127 = -1 = 1111 1111
While reading Computer Architecture by Patterson (page 194) I got this question. IEEE 754 uses 127 as bias for single precision floating point so that it will be easy to compare floating point numbers using hardware.

1.0 * 2^-128

biased exponent = -128+127 = -1 = 1111 1111

1.0 * 2^1

biased exponent = 1+127 = 128 = 1000 0000

For hardware compare 1) comes out to be a larger number than 2) which is wrong.
Can anybody explain how comparing is working for these two numbers?

答:
The exponent is unsigned. It cannot be -1. The smallest it can be is 0, which translates to 2^-127.

You might ask then, "If so, how is 2^-128 represented in single precision?!".

The answer lies in normalization.

Usually numbers are normalized (i.e. multiplied by a power of 2) so that the leading bit of their mantissa is 1. That bit can then be omitted, giving you extra precision (or removes redundancy, depending on who you ask).

It was decided for ~reasons~ (to enable a gradual loss of precision during underflow), that it's not worthwhile keeping to this schema when the exponent is -127. Rather the leading bit is whatever the leading bit is.

What this does, is it decreases resolution in the range 2^-127 to 2^-126 but allows to represent additional numbers below 2^-127.

Hence, 2^-128 will have an exponent of 0 (translated to -127 via the bias), and a mantissa of 010000...000. Note that, unlike all normalized numbers, the mantissa means 0.5 - which is outside the usual range of the mantissa for normalized numbers (1.0 to 2.0).

With this in mind - the exponent comparison makes easy sense - 128 is larger than 0 :)

All this is also given in the wiki article on IEEE 754-1985 (and probably others) in the very first section.