问:
Refactor class (extract methods) in a main / helper classes
Simply spoken, one of my c# classes got too big and I'm currently splitting this class in several subclasses by clustering semantically related methods (actually actions, which do side effects).

So, to give you an example:

```<code>class ViewModel
{
  // a lot of properties bound to view (MVVM pattern)
  public Property 1 //bound to view
  public Property 2 //bound to view

  // a lot of actions, containing the controller logic of the view
  //Function 1 changes Property 1 -> shall be moved to class MyViewModelHelper
  Function1() {}
</code>```

That is, when I create a helper class for the viewModel, it needs to to receive the instance reference of the main view model in its constructor, so that it has access to the public properties.

I do not want that the view has to have the knowledge about the helper classes, that is the main view model shall provide all the properties... but the functions shall delegate the work to the helper classes to keep the viewModel class maintainable.

答:
Sounds like a case for using extension methods. Simply move Function1() to MyViewModelHelper, make it static, and change the first/only paramater to be like this:

```<code>public static class MyViewModelHelper
{
    public static void Function1(this ViewModel vm)
    {
        // whatever
    }
}
</code>```

As a benefit: afterward, the semantics of the callers often don't need to change.

Body:
Sounds like a case for using extension methods. Simply move Function1() to MyViewModelHelper, make it static, and change the first/only paramater to be like this:

public static class MyViewModelHelper
{
    public static void Function1(this ViewModel vm)
    {
        // whatever
    }
}

As a benefit: afterward, the semantics of the callers often don't need to change.


问:
Using empty subclasses to add to the semantics of a class hierarchy?
I was wondering whether using (almost) empty derived classes to give additional semantics to a class hierarchy was a good idea (or practice) ?

Because a (not so short) example is always better than a long speech, let's assume we're writing a class hierarchy for SQL generation. You want to represent a data manipulation command (INSERT, UPDATE or DELETE), so you have two alternatives :

First version, with switch statement

```<code>enum CommandType {
    Insert,
    Update,
    Delete
}

class SqlCommand {
    String TableName { get; }
    String SchemaName { get; }
    CommandType CommandType { get; }
    IEnumerable<string> Columns { get; }
    // ... and so on
}

class SqlGenerator  {
    string GenerateSQLFor(SqlCommand command)
    {
        switch (command.CommandType)
        {
            case CommandType.Insert:
                return generateInsertCommand(command);
            case CommandType.Update:
                return generateUpdateCommand(command);
            case CommandType.Delete:
                return generateDeleteCommand(command);
            default:
                throw new NotSupportedException();
        }
    }
}
</code>```

Second version with VisitorPattern (Note that the question is NOT about whether the Visitor pattern should be used or adding new operations)

```<code>abstract class SqlCommand {
    String TableName { get; }
    String SchemaName { get; }
    IEnumerable<string> Columns { get; }
    // ... and so on
    abstract void Accept(SqlCommandVisitor visitor);
}

class InsertCommand : SqlCommand
{
    overrides void Accept(SqlCommandVisitor visitor)
    {
        visitor.VisitInsertCommand(this);
    }
}

class DeleteCommand : SqlCommand
{
    overrides void Accept(SqlCommandVisitor visitor)
    {
        visitor.VisitDeleteCommand(this);
    }
}

class SqlCommandVisitor  {
    void InitStringBuffer() { ... }
    string GetStringBuffer() { ... }

    string GenerateSQLFor(SqlCommand command)
    {
        InitStringBuffer();
        command.Accept(this);
        return GetStringBuffer();
    }

    void Visit(SqlCommand command) { ... }
    void VisitInsertCommand(InsertCommand command) { ... }
    void VisitDeleteCommand(DeleteCommand command) { ... }
    void VisitUpdateCommand(UpdateCommand command) { ... }
}
</code>```

With both examples we achieve the same result, but :

In the first version, my code feels more DRY, even though polymorphism is generally preferable over a switch statement.

In the second version, I feel like I'm needlessly deriving SqlCommand just so that the code carries more meaning.

Another similar case is deriving a class from a generic class, just to give additionnal meaning to the collection, eg :

```<code>class CustomerList : List<Customer> { }
</code>```

I'm left off wondering whether this is a good idea. Are there any pitfalls to doing so ?

I personally prefer the second version exactly because it adds meaning to the code, and helps me when I read my code later... But I clearly lack the experience to see any downside to this pattern.

答:
I like second approach better since when one looks into InsertCommand, this reads as "THERE IS an insert command", which means that there should be another commands. When you read next, you see these commands and you totally understand the idea.

The first approach reads as "THERE IS a command... with some details in there...".

ContentLicense: CC BY-SA 3.0


问:
Is it worth moving from Microsoft tech to Linux, NodeJS & other open source frameworks to save money for a start-up?
I am currently getting involved in a startup, I am the only developer involved at the moment, and the other guys are leaving all the tech decisions up to me at the moment.

For my day job I work at a software house that uses Microsoft tech on a day to day basis, we utilise .NET, SqlServer, Windows Server etc. However, I realise that as a startup we need to keep costs down, and after having a brief look at the cost of hosting for Windows I was shocked to see some of the prices for a dedicated server. The cheapest I found was £100 a month. Also if the business needs to scale in the future and we end up needing multiple servers, we could end up shelling out £10's of £000's a year in SQL Server / Windows Server licenses etc.

I then had a quick look at the price of Linux hosting for a dedicated server and saw the price was waaaaaay lower than windows hosting. One place was offering a machine with 2 cores for less than £20 a month.

This got me thinking maybe the way to go is open source on Linux.

As I write a lot of Javascript at work (I'm working on a single page backbone app at the moment), I thought maybe NodeJS and a web framework like Express would be cool to use. I then thought that instead of using SQL why not use an open source NoSQL database like MongoDB, which has great support on NodeJS?

My only concern is that some of the work the application is going to do is going to be dynamically building images and various other image related stuff, i.e. stuff that is quite CPU heavy - so I'm thinking of maybe writing anything CPU heavy in C++ and consuming it as a module in Node.

That's the background - but basically is Linux a good match for:

Hosting a NodeJS/Express site?

Compiling C++ node modules?

Using a NoSQL DB like MongoDB?

And is it a good idea to move to these unfamiliar technologies to save money?

3 MONTH UPDATE

I've been working on this for the past few months now so thought I would give an update in case anyone is interested.

In the end I decided against using a NodeJS & Linux stack for the simple reason of time. I am doing this startup on the side, so I am working 9 hour days, then going home and working until late on the startup. While working in this way I obviously need to be as efficient with my time as possible, or I will never end up shipping the product.

After taking some of the advice on this thread I did apply for Microsoft BizSpark, and was accepted. This means I now have access to Visual Studio license, Windows Server license etc, all for free. Which is awesome. Hopefully by the time we are required to begin paying for everything we will be turning over enough that will make it a non-issue.

Do not think I am only using Microsoft tech, however, as I have tried to use open source stuff where possible. The main place I have done this is my data layer, where I have decided to use PostgreSQL and MongoDB. I am also using BackboneJS on my front end.

Below is a summary of the tech/frameworks I am currently using:

Standard DB stuff: PostreSQL

Logging & Data Store: MongoDB

ORM: Entity Framework 5

Core libraries: .NET (C#)

Web Framework: ASP.NET MVC3

UI: Razor view engine / BackboneJS

答:
£100/month? How much do you cost? How much is going to cost your training?

If it's £100/month but you can get a .NET app up in a month, while you will need at least 3 to 6 months to get your node.js/C++ app running, go for the .NET. Seriously. Your time is way more expensive than these little £100/month.

Ideally, yes, you're right in your analysis. What you forgot is how long it's going to take you to build all this (i.e. months) especially in a technology you don't know.

Now don't get me wrong, I'm a huge fan of Node.js and the likes (just see my github profile...). I've spent more than enough time to know when to use it. Using it when you don't know about it in a startup environment (where you need to ship) is not really the best solution.

Also, I'm really not sure if this could work, but don't forget about Mono.

PS: knowing how to use jQuery is a very little help for node.js. Knowing javascript is a big help. Don't confuse both.


问:
Coding in 'core php' and separating logic from presentation
What are the various ways of acheiving this ? Can someone please guide me?

I have to code a website for a friend (designer). The friend wants me to use core php and not any framework like codeigniter (something I really like and am comfortable with !) .

I had a look at a couple of roll your own MVC frameworks guides, but am not sure if this is the ideal approach.  Since any solution I might come up with may have various bugs/security issues.
My goal is to use plain php , without the help of thirdparty frameworks, to code a site , where the logic is separate from the view .

Thanks

答:
The short answer is: always use a framework. Don't try to write your own (unless you do it for learning).

The long answer is more complex.

From my personal experience, I have seen that there are situations when you simply have no choice, especially when you have to work with people who are not familiar with OOP.

My suggestion is: especially if you are starting from scratch, try to convince your friend to use CodeIgniter. After all, he won't need to be an OOP or MVC guru to understand which view is loaded by x controller.

Only if you can't convince him, and if the project is very simple, write your own mini-framework, but don't try to implement a complete MVC pattern. It would be the same thing as using CodeIgniter, but instead of the original you would have a bad copy.

Here are my suggestions:

Create a 'main.php' file as a single entry point to your framework, with autoloading declaration, session initialization etc.

Create a 'classes' directory to keep all your logic separated.

Create a View class (the simplest thing you can do is including the view file and extracting the array of data to be used inside the view):

```<code><?php
class View {

    protected $view_name, $data;

    public function __construct($view_name, $data = array()) {
        $this->view_name = $view_name;
        $this->data = $data;
    }

    //Displays view content
    public function render(){
        //Extracts vars to current view scope
        extract($this->data);

        //Includes contents
        include $this->view_name;
    }

}
</code>```

Create an Input validation library.

Then, inside your pages, include 'main.php' and you will have access to all your classes and views.

```<code><?php include_once 'main.php';
$view = new View('view.php', array('var_name' => 'value'));
$view->render();
</code>```

I am writing a very simple framework which is built more or less on this schema. I wrote it exactly to deal with this kind of situations. Have a look if you need inspiration.

Body:
The short answer is: always use a framework. Don't try to write your own (unless you do it for learning).

The long answer is more complex.

From my personal experience, I have seen that there are situations when you simply have no choice, especially when you have to work with people who are not familiar with OOP.

My suggestion is: especially if you are starting from scratch, try to convince your friend to use CodeIgniter. After all, he won't need to be an OOP or MVC guru to understand which view is loaded by x controller.

Only if you can't convince him, and if the project is very simple, write your own mini-framework, but don't try to implement a complete MVC pattern. It would be the same thing as using CodeIgniter, but instead of the original you would have a bad copy.

Here are my suggestions:

Create a 'main.php' file as a single entry point to your framework, with autoloading declaration, session initialization etc.

Create a 'classes' directory to keep all your logic separated.

Create a View class (the simplest thing you can do is including the view file and extracting the array of data to be used inside the view):

<?php
class View {

    protected $view_name, $data;

    public function __construct($view_name, $data = array()) {
        $this->view_name = $view_name;
        $this->data = $data;
    }

    //Displays view content
    public function render(){
        //Extracts vars to current view scope
        extract($this->data);

        //Includes contents
        include $this->view_name;
    }

}

Create an Input validation library.

Then, inside your pages, include 'main.php' and you will have access to all your classes and views.

<?php include_once 'main.php';
$view = new View('view.php', array('var_name' => 'value'));
$view->render();

I am writing a very simple framework which is built more or less on this schema. I wrote it exactly to deal with this kind of situations. Have a look if you need inspiration.


问:
Best practices: Ajax and server side scripting with stored procedures
I need to rebuild an old huge website and probably to port everyting to ASP.NET and jQuery and I would like to ask for some suggestion and tips. Actually the website uses:

Ajax (client site with prototype.js)

ASP (vb script server side)

SQL Server 2005

IIS 7 as web server

This website uses hundred of stored procedures and the requests are made by an ajax call and only 1 ASP page that contain an huge select case

Shortly an example:

JAVASCRIPT + PROTOTYPE:

```<code>var data = {
    action:     'NEWS',
    callback:   'doNews',
    param1:     $('text_example').value,
    ......:     ..........};
AjaxGet(data); // perform a call using another function + prototype
</code>```

SERVER SIDE ASP:

```<code><% ......
select case request("Action")
case "NEWS"
    With cmmDB
        .ActiveConnection = Conn
        .CommandText = "sp_NEWS_TO_CALL_for_example"
        .CommandType = adCmdStoredProc

        Set par0DB = .CreateParameter("Param1", adVarchar, adParamInput,6)
        Set par1DB = .CreateParameter(".....", adInteger, adParamInput)
        ' ........ ' can be more parameters

        .Parameters.Append par0DB
        .Parameters.Append par1DB

        par0DB.Value = request("Param1")
        par1DB.Value = request(".....")

        set rs=cmmDB.execute

        RecodsetToJSON rs, jsa ' create JSON response using a sub
    End With
.... %>
</code>```

So as you can see I have an ASP page that has a lot of CASE and this page answers to all the ajax request in the site.

My question are:

Instead of having many CASES is it possible to create dynamic vb code that parses the ajax request and creates dynamically the call to the desired SP (also implementing the parameters passed by JS)?

What is the best approach to handle situations like this, by using the advantages of .Net + protoype or jQuery?

How the big sites handle situation like this? Do they do it by creating 1 page for request?

Thanks in advance for suggestion, direction and tips.

答:
Instead to have many CASES is possible to create dynamic vb code that parse the ajax request and create dynamically the call to the desired SP (also implementing the parameters passed by JS)?

Yes, the "action" parameter should just contain the name of the SP. Then you can just delete all hundreds of switch cases and if.

Or what is the best approach to handle situation like this, by using the advantages of .Net + protoype or jQuery ?

You don't even need all those libraries, I've implemented the exact same thing with just a few lines of JS and a single ashx generic handler. Best approach depends on your exact needs.

How the big sites handle situation like this ? by creating 1 page for request ?

Each "big sites" have implemented their solution around their specific needs.


问:
When to write an explicit return statement in Groovy?
At the moment I am working on a Groovy/Grails project (which I'm quite new in) and I wonder whether it is good practice to omit the return keyword in Groovy methods. As far as I know you have to explicitly insert the keyword i.e. for guard clauses, so should one use it also everywhere else? In my opinion the additional return keyword increases readability. Or is it something you just have to get used to? What is your experience with that topic?

Some examples:

```<code>def foo(boolean bar) {
    // Not consistent
    if (bar) {
        return positiveBar()
    }
    negativeBar()
}

def foo2() {
    // Special Grails example
    def entitiy = new Entity(foo: 'Foo', bar: 'Bar')
    entity.save flush: true
    // Looks strange to me this way
    entity
}
</code>```

答:
Here's an argument for omitting the return statements (Source):

An Understated Feature in Groovy

Background

I have worked with Groovy for awhile, but have been averse to one
  feature: the implicit return of the last expression evaluated. For
  example:

```<code>def getFoo() {
  def foo = null
  if (something) {
    foo = new Foo()
  }
  foo // no 'return' necessary
}
</code>```

In the above code, I would use return because it felt safer to me. I
  tended to agree with Eric's post (with respect to explicit returns).

Revelation

I get it now, and it's all thanks to the enhanced collection methods
  in Groovy.

Consider the collect method. It transforms a list by applying a
  function. In pseudocode:

```<code>[ a, b, c, d] => [ f(a), f(b), f(c), f(d) ]
</code>```

With that in mind, here's another example:

```<code>class Composer {
  def name
  // def era, etc
}

def list = [ 'Bach', 'Beethoven', 'Brahms' ]

// the closure returns the new Composer object, as it is the last
// expression evaluated.

def composers = list.collect { item -> new Composer(name : item) }

assert 'Bach' == composers[0].name
</code>```

The idea is simply to build a list of Composer objects from a list of
  strings. As noted in the comment, the closure passed to collect uses
  the implicit return to great effect. At one time, I would have taken
  3-4 lines to express that idea.

But now, this code is not merely concise: it is truly elegant. Very
  reminiscent of other languages such as Python.

The Take-Home Message

There are many lists of excellent Groovy features. However we rarely
  see 'implicit return' listed. I'm a fan: it greases the wheels for
  other features.

I realize it is available in many languages: I just haven't used it in
  Groovy. I suspect in a few weeks I won't be able to live without it.

Body:
Here's an argument for omitting the return statements (Source):

An Understated Feature in Groovy

Background

I have worked with Groovy for awhile, but have been averse to one
  feature: the implicit return of the last expression evaluated. For
  example:

def getFoo() {
  def foo = null
  if (something) {
    foo = new Foo()
  }
  foo // no 'return' necessary
}

In the above code, I would use return because it felt safer to me. I
  tended to agree with Eric's post (with respect to explicit returns).

Revelation

I get it now, and it's all thanks to the enhanced collection methods
  in Groovy.

Consider the collect method. It transforms a list by applying a
  function. In pseudocode:

[ a, b, c, d] => [ f(a), f(b), f(c), f(d) ]

With that in mind, here's another example:

class Composer {
  def name
  // def era, etc
}

def list = [ 'Bach', 'Beethoven', 'Brahms' ]

// the closure returns the new Composer object, as it is the last
// expression evaluated.

def composers = list.collect { item -> new Composer(name : item) }

assert 'Bach' == composers[0].name

The idea is simply to build a list of Composer objects from a list of
  strings. As noted in the comment, the closure passed to collect uses
  the implicit return to great effect. At one time, I would have taken
  3-4 lines to express that idea.

But now, this code is not merely concise: it is truly elegant. Very
  reminiscent of other languages such as Python.

The Take-Home Message

There are many lists of excellent Groovy features. However we rarely
  see 'implicit return' listed. I'm a fan: it greases the wheels for
  other features.

I realize it is available in many languages: I just haven't used it in
  Groovy. I suspect in a few weeks I won't be able to live without it.


问:
What is the rationale behind entering email twice for registration?
Many web sites ask users to enter their email address twice, sometimes taking the trouble to disable copy-pasting.

What is the logic behind this? Is this e.g. a security measure?

答:
Short Answer: It is done to prevent the typo (mistakenly entering email address) !

Without this check, user may enter a wrong email address and never get registration feedback email, because he has entered wrong email address. In addition, this checking measure is prevent mass spamming by CaptCHA implementation in place.


答:
I think it's simply because entering an email address is an error-prone activity.  Making you type it twice makes you think about it.

I have no hard evidence for this.

Title: What is the rationale behind entering email twice for registration?

Body:
Many web sites ask users to enter their email address twice, sometimes taking the trouble to disable copy-pasting.

What is the logic behind this? Is this e.g. a security measure?


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

    — Bill Gates

LastEditorDisplayName: Roger Pate

ContentLicense: CC BY-SA 2.5


问:
Should curly braces appear on their own line?
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.

答:
I prefer the first because it is harder for me to see the mistake in this example.

```<code>if (value > maximum);
{
    dosomething();
}
</code>```

than it is in this example

```<code>if (value > maximum); {
    dosomething();
}
</code>```

The ; { just looks more wrong to me than a line ending with ; so I'm more likely to notice it.

Body:
I prefer the first because it is harder for me to see the mistake in this example.

if (value > maximum);
{
    dosomething();
}

than it is in this example

if (value > maximum); {
    dosomething();
}

The ; { just looks more wrong to me than a line ending with ; so I'm more likely to notice it.


答:
I suspect a lot of it is "Grandma's Cooking Secret" programming where the programmer does it because they saw someone else do it. It's following tradition without thinking.

There could some logic originally behind it, such as users in 1996 not knowing that much about how to format email addresses. It could have been done then to avoid errors but then why not double every visible field? However, it probably isn't needed today and is an extra pain for mobile users.

Now, disabling copy/pasting and other tricks can be useful to prevent some automated spamming but they should be non-intrusive for the most part to normal users.


答:
It's just to try and ensure that you enter the correct address, without typos. Since email addresses are usually the primary contact information for websites, it's considered worth the extra effort to try and make sure it gets entered correctly.

It's sometimes called two-pass verification.


问:
Multi cores/CPUs with locks
I'm not sure how the locks will work with multi processors/cores, I'm going to use shared memory in my application or FIFO, what worries me is the locks, I have a server with 2-CPU, how the lock will be able to lock a variable on one CPU while the another operation went to the 2nd CPU for the same variable?
I'm in Linux environment using C, I've searched the web for some useful info, appreciate your help</p>

答:
Intel articles offers a good point of view about this.

Also there is a small article about the top 3 solutions in multithreading programming.

You didn't specify this, but if you are on Linux and you are programming in C you are probably talking about pthreads and this is a beginner tutorial that covers the main aspects of this topic.

Title: Multi cores/CPUs with locks

ContentLicense: CC BY-SA 4.0


问:
Is there something wrong with how we're doing version control?
I work with a team of programmers as the business analyst.  We just released version 2.0 of our product and are working on the next version to be released in 3 months (it's an internal software product).  Unfortunately version 2.0 has some issues that they have had to fix and we're going to deploy those fixes in a couple weeks.  The problem is that we also don't want to deploy the changes that are still being worked on and are not slated to be released for another 3 months.

The programmers decided that the way to manage this was that only the code for the defects will be checked in, and the code for the new enhancements will be kept on the developer's local machines until they are done.  I will have to get local builds from their machines to test because if they check in the code and we have to push out another patch to fix defects we don't want to include those enhancements just yet.  There is also the problem where the same code file contains both defect fixes and enhancements, so they have to copy the code file locally, then make a change to fix a bug and check that one in, then resume work on the enhancements by taking the local copy they made.

It seems quite convoluted - is there a better way to handle this type of scenario?  We're using Team Foundation Server and Visual Studio 2010.

答:
What you are describing is a terrible way to use version control. There should have been a branch made for release 2.0, or a tag or some identifier. That way, modifications to that release can be contained and more development can continue to happen.

This article can give you some ideas. It's written with git in mind, but there's no reason that it couldn't work with mercurial as well. I realize that you're using neither of these, but that's also a problem that you should consider fixing.


答:
V2.0 should have had what we used call a 'steady-state branch' (we used Perforce, not TFS) made for it once it was released. Any fixes for v2 would have been made to this branch and then propagated back into the v3 development branch while v3 features were also being worked on, i.e. a defect on v2 would result in a defect also on v3.

Having changes reside on developer's machines for a long time will likely result in an integration nightmare.

Title: Is there something wrong with how we're doing version control?

Body:
I work with a team of programmers as the business analyst.  We just released version 2.0 of our product and are working on the next version to be released in 3 months (it's an internal software product).  Unfortunately version 2.0 has some issues that they have had to fix and we're going to deploy those fixes in a couple weeks.  The problem is that we also don't want to deploy the changes that are still being worked on and are not slated to be released for another 3 months.

The programmers decided that the way to manage this was that only the code for the defects will be checked in, and the code for the new enhancements will be kept on the developer's local machines until they are done.  I will have to get local builds from their machines to test because if they check in the code and we have to push out another patch to fix defects we don't want to include those enhancements just yet.  There is also the problem where the same code file contains both defect fixes and enhancements, so they have to copy the code file locally, then make a change to fix a bug and check that one in, then resume work on the enhancements by taking the local copy they made.

It seems quite convoluted - is there a better way to handle this type of scenario?  We're using Team Foundation Server and Visual Studio 2010.


问:
Separation of concerns and security
The system I am developing is designed to have multiple organizations, with users and roles for each organization.  Some organizations can interact, some can not, and generally organizations are not allowed to see or modify each others data with some exceptions.

I have a model class A that manipulates the data storage in a permanent storage container of some kind.  I have a controller class B that validates input (including access rights verification) to objects of class A.

The controller classes are in a separate library from the model classes.

All user interaction is performed from view classes which are again in a separated library (in this case exposed as web services).

However, it seems that there is a possible security risk in keeping access control logic separate from the model, since no security checks will be performed if the model is not accessed by its associated controller and is accessed instead by some other code due to some malicious attacker or programmer error.

Should I place the security logic in the same model classes weaving these concerns together or should I keep the separation as I have now?

答:
I would prefer to see those two concepts in two separate classes. The reason is that it's a simpler and cleaner design, which usually means that it will have less bugs (including security bugs). The some design is simpler, it will usually also have less problems (including security based problems).

The attack you are protecting against can only happen through programmer error. I don't see a way that a malicious user can circumvent your controller and hit the model directly, unless you are doing something very weird in your system. The programming error in question is using the model directly and not through a control. I think this is a fairly obviously the "wrong" thing to do and most developers wouldn't do something like that. However, you should be doing code reviews for security critical code, and that's the best place to catch these sorts of issues.

Remember a developer can destroy the security controls in many different ways. They have full code access, and there's countless ways to screw something up. Your best bet is to write the code in the cleanest way possible and enforce practices like code reviews.

Title: Separation of concerns and security


答:
Well there are multiple ways to deal with issues like that, generally covered by 'branching' tag, each with own set of benefits and downsides.

But approach chosen by your developers... gee I'll quote it verbally to make sure that I didn't misread...

code... will be kept on the developer's local machines until they are done...

...the way like above is probably the only one that is totally, completely wrong!

What makes it border to criminal to me is that for TFS, there is an excellent, easy to understand, Microsoft Team Foundation Server Branching Guidance - huge and detailed document with branching strategies recommendations carefully tailored and explained for all kinds of different projects (HTML version here).


答:
It is just the old way of confirming the email address. In old days, you had to enter the same email twice in order to verify it, in the new way, you have to click on a link inside the email to verify it. The new way is far better and makes the first one obsolete.

In this particular case, there is an extra emphasis on email just because it is money related site which is obvious. Other than that this method is not prevalent these days.


答:
Quick Answer: Development team should have a separate Production branch to keep deployed code-base V2.0 separate from the Main trunk.

All the bug fixes need to be done in that branch first and then tested and deployed to other branches, in order to keep code in sync.

Your project should also have have several environments for health development like Prod, Staging, QA and Dev (sometimes UAT ). These environments should  be set up before going to Production release.

All in all, being ready for bugs and modification is the way to support a released application.

As TFS was mentioned as a version control, i have also compiled list of articles which will be helpful to set health development environment(s):

Implementing Team Foundation Server with a small development team

Welcome to the TFS Integration Platform!

Team Development with TFS Guide

Setting Up a Development Environment


答:
Your dev's have a fundamental misunderstanding of how to use version control.

Do not get into a discussion about the "right" version control software. This is not the problem.

Every code tweak is making the problem harder to fix.

WHEN y'all decide to do the right thing, you cannot continue code changes while you fix things. You MUST stop all development and get the code into version control.

The dev's must be feeling the pain enough to at least sit down and talk about it.

All version control software supports basic concepts:

ALL code goes into the version control repository.

All code files have version numbers. These numbers increment automatically as code is re-checked in.

A TAG marks all code files of a (and at a) particular version. Thus we can TAG the software version 1 release, for example.

a BRANCH is a "turn away" from the main trunk.

Any and all changes made to a branch do not affect the trunk.

You may optionally merge branch changes back into the main trunk at some point.

Thus we may experiment without fear of messing up "the good stuff."

Y'all must get the version control "leap of faith" as I call it. TRUST that following basic rules will keep things straight. Inexperience makes us think otherwise, trust me.

Here is a decent tutorial. It is general and complete enough that you don't need to scour lots of other sources

Version Control, Better Explained

edit

Put version control on your work computer.

You can do this right now w/out team coordination

Even with team version control, I highly recommend this

If your team uses Git or Mercurial you are using an independent, local repository. That's how distributed version control works.

You can use different VC software from your team. Our team uses Subversion, I use Mercurial locally. The VC software metafiles (".svn", ".mg", hidden folders) do not conflict.

You are not acting as a de-facto team repository. It's for managing your own work, refactoring efforts, etc. and CYAing yourself as the team continues to FUBAR the code base.

end edit


问:
New license similar to AGPL, but only for Javascript and CSS
I'm developing a piece of software (a WordPress plugin) in PHP and Javascript and CSS. The PHP code must be licensed under GPL, but CSS and Javascript can be under another license (as far as I've understood).

I'm thinking about writing a more permissive version of the AGPL license, and use it, for Javascript and CSS.  It would be like the AGPL, but it would only concern files accessible over the network (e.g. Javascript and CSS).

Motivation:

I want users of my software, and small companies that use and produce open source software, to be able to use my plugin for free, without having to publish  any GPL licensed server side code (PHP code).

At the same time, I might not want "big companies" to copy all code I've written, without paying me something. — Most "big companies" would probably be unable to use the AGPL-like license discussed here, and instead I would offer them to buy a commercial license.

Question 1: Is this a bad / impossible idea, for some reason?

Question 2: Are there any obvious problems with the below license text? (Is this okay to ask here? If not, please consider editing this question to remove this part of it — or add a comment to me, that I should remove it)

```<code>...The AGPL v3 license text..., see http://www.gnu.org/licenses/agpl-3.0.html

Additional permission under the GNU Affero GPL version 3 section 7:

If you modify or combine this Program, or any covered work,
by linking or combining it with other code, then any such
other code not accessible remotely through a computer
network, is not, for that reason alone (i.e. linking or combining
it) subject to any of the requirements of the GNU Affero GPL
version 3 or later.
</code>```

Related link: Lesser Affero GPLv3

答:
It’s pointless to write your own license.

99.999% of people will ignore it anyway.

0.0001% will read it and reject it because they don’t understand it, or could never get Legal to agree to it.

Any license without the firepower of somebody like $MegaCorp$ or the FSF behind it is doomed anyway. How many lawyers can you afford to defend against it in London/Tokyo while they clock up $1000/hour costs deciding what is a “large company”?


答:
Assuming you're using pthreads, you have to be aware that locks are implemented as functions and macros.

That means that a lock doesn't make a variable available or not to a CPU, nor they send operations to the other(s) CPU(s).  What you do is to spawn threads, calling pthread_create() with a function pointer as a parameter.  Typically several threads are spawned with the same function and different parameters, so each runs the same code slightly differently.

Ideally, most of the code should work on different data, allocating private blocks so that each thread can run without checking for collisions.

Of course, there's always some shared part, or some communication between threads, or some common store structure.  For this you use locks.

In short, every shared resource must have a lock, and before trying to access the resource you have to acquire the lock using pthread_mutex_lock() or a similar function, and release it with pthread_mutex_unlock() just after using the resource.

When no other thread was trying to use the same resource, these functions return quickly and your code can do as intended.  But if a thread tries to get a lock while another one already has it, the second one is blocked and can't continue until the first one releases it.

In short, surrounding some code with lock/unlock calls guarantees that only one thread will operate that part of the code with that specific lock at any given time.

What you want to do to optimize the concurrency of your code is to hold locks for as few operations as possible, during the shortest time, and with the most specificity (different locks for different data structures, even if the code is common).

Beyond this, you have to be aware of deadlocks, livelocks, priority inversion, etc.  But just making sure that each shared structure has an associated lock (and is used consistently!) is a good start.

Encapsulating the lock with the shared structure, and using only access functions that enforce the lock makes it much easier to do correctly.

Title: Multi cores/CPUs with locks

Body:
I'm not sure how the locks will work with multi processors/cores, I'm going to use shared memory in my application or FIFO, what worries me is the locks, I have a server with 2-CPU, how the lock will be able to lock a variable on one CPU while the another operation went to the 2nd CPU for the same variable?
I'm in Linux environment using C, I've searched the web for some useful info, appreciate your help</p>


问:
In a web application, is it ok to group multiple pages in one view class or one class per page?
If you are building a web application, and you have a user management component, is it recommended to do:

```<code>class UserAdminView extends View {

}
</code>```

or

```<code>class UserAdminUpdateView extends View {

}
</code>```

What about controllers? Thoughts?

答:
If you want to do it MVC style, I personally most of the time have different views for different actions. In some cases, when the content for show / edit / save / list or whatever I had there was very similar I used only one view. But rarely.

As for the Controller, there should be one controller with different methods for the different actions.

As for Model. I consider models kind of redundant. I use them only to validate forms and only because they integrate with the framework.

Business logic should be outside the MVC framework, which I consider only a delivery mechanism to the application.

PS: I know many web developers will not agree with my last statement. Don't flame, think. Thanks.


问:
How To Document an Object Oriented Design in Text
For my next project, I'm looking to document my Object Oriented design in simple text before jumping the gun to code it up. I want to do this for two reasons.

I want to give proper thought to my design and possibly revise it several times.

I haven't exactly decided which language I want to implement my project in.

I'm looking for a convention to outline my design in simple text, instead of a UML diagram. I like the convenience of text. I can version control it and easily put in a blog or wiki to share it.

I am thinking something concise e.g. how you might code in Python. However, I want the representation to be language independent. I've looked around the internet but couldn't find anything. The closest would probably be how properties and methods are defined in the box representing a class in a UML Model.

Update:
I just wanted to clarify "in Text". My goal is to be able to outline the object model in a github wiki. I imagine it being kind of an open source design in addition to code. Thus, I can create a Wiki page per entity and identify the relationships using links and formatting etc. However, what I wanted suggestions on was how to outline the specification of an entity on its page.

答:
The closest things to what you want are Use Cases. These represent a textual representation of the requirements, ideas and design of your application.
A simple explanation can be found  here at wikipedia.

However, for best documentation I recommend Alistair Cockburn's Writing Effective Use Cases book.


答: Use Python and sidestep the argument completely.</p>

Title: Should curly braces appear on their own line?

Body:
Should curly braces be on their own line or not? What do you think about it?

```<code>if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
</code>```

or should it be

```<code>if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}
</code>```

or even

```<code>if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();
</code>```

Please be constructive! Explain why, share experiences, back it up with facts and references.


问:
Rails - Does using partials slow views rendering?
I'm having performance issues on a Rails 3.1.0 application, now I've done dome changes on my queries with AR and so but views still takes too many time to render, I've divided the views, loops and so, on many partials that are rendered dynamically inside views and inside other partials.

So it's a bad practice to have a large number of partials?

Should I reduce the number of partials to improve the views rendering time?

Thanks

答:
I know about no significant rendering performance difference between many partials and one single view when you render the same content.

Obviously, if you render only some partials in some cases and others in other cases, such effectively reducing the rendering volume of a specific view, than you may gain some speed.

On the other hand, I always considered partials abstractizations which should be used at least from 2 different places to justify their existence. The other reason to use partials is when you want to render the same view but load different partials based on some business logic you have.

UPDATE:

I can't offer a measurement or some concrete numbers about the rendering speed. If you use a partial in a view, to render it you call the render method, so there is a second method call. This, as I said in my answer, is almost nothing but may help speed up things a very little.

However I never heard of a project fixing its performance problem by removing partials. Partials are a good way to offer a reuse mechanism to views and from the programmers view they should be used for that scope. They should be abstractizations for common concepts in views.

I worked on a project where partials were excessively used. Not Rails, but same MVC principles. Using little partials for everything you can imagine makes them hard to find when you start to have dozens of them. Where would you look for an input to be modified? In the view? In a partial? In which partial, there are 4 partials for this view? ...

After some hard refactorings, with each update of a view, we removed the unnecessary partials. They did not disappeared completely, but what remained are abstractizations which are well defined for the project. They represent well understood elements (like a tree for some kind of objects, or a specific list type) which repeat in a form or other on several views. I know if I see a tree that there is a partial for that. I know when I see certain type of list that there is a partial for that. I don't have hunt them down.

Code readability is the most important thing one can do for a software code base.


问:
How does a static type system affect the design of a prototype-based language?
The Wikipedia article on prototype-based languages contains the following paragraph:

Almost all prototype-based systems are based on interpreted and dynamically typed languages. Systems based on statically typed languages are technically feasible, however.

In what ways does a static type system impose restrictions or introduce complexity in prototype-based language, and why are there more dynamically-typed prototype languages?

答:
I believe a way to achieve a statically-typed, prototype-based language would be to base the language around Templates and Concepts.

Concepts were once a planned feature for C++0x.  Generic code in C++ templates is already de facto "statically duck-typed".  The idea of Concepts is to be able to say some things about required members and characteristics of types, without requiring or implying a class-inheritance model underlying that relationship (because it had to work with existing template code that was already "statically duck typed").

In a language based from the ground-up on Templates and Concepts, it would be the Concepts that are prototype-based, and Templates would free you from caring about any class model which may or may not be used to implement the types of values.

Aside from tricks of using staged-compilation to allow the language to be its own meta-language, these prototypical derivations of Concepts would necessarily be immutable once created.  However, the objection that that is not prototype-based is a red herring.  It would simply be a functional language.  A dynamic prototype-base language that is also functional has at least been attempted.


答:
We had a huge project and I documented all of the teller functions using Use Cases.
So we had Deposit, Withdrawal, etc...  with each one it had several local, mid, and backend processes to go through.  At various levels I also had access changing by security.  The use cases made all of that quite clear and allows you to document not only the system but also the players involved.  Helps in determining what areas you need to design class libraries for and what different security comes into play.

That high level view makes it very easy to a) document what is happening -- as well as -- b) identifying potential sub systems you need to design/construct.  It will, in the long run, make your next level of design much better (IMHO).

Title: How To Document an Object Oriented Design in Text

Body:
For my next project, I'm looking to document my Object Oriented design in simple text before jumping the gun to code it up. I want to do this for two reasons.

I want to give proper thought to my design and possibly revise it several times.

I haven't exactly decided which language I want to implement my project in.

I'm looking for a convention to outline my design in simple text, instead of a UML diagram. I like the convenience of text. I can version control it and easily put in a blog or wiki to share it.

I am thinking something concise e.g. how you might code in Python. However, I want the representation to be language independent. I've looked around the internet but couldn't find anything. The closest would probably be how properties and methods are defined in the box representing a class in a UML Model.

Update:
I just wanted to clarify "in Text". My goal is to be able to outline the object model in a github wiki. I imagine it being kind of an open source design in addition to code. Thus, I can create a Wiki page per entity and identify the relationships using links and formatting etc. However, what I wanted suggestions on was how to outline the specification of an entity on its page.


答:
You could write in HTML and use hyperlinks to express relationships between different classes. The problem, though, is that you can't see links. When documenting a design, the relationships are a big part of what you're trying to explain, so it won't do to make them invisible.

I'd suggest forgetting about plain text. Use HTML at a minimum, and don't be afraid to include pictures created in your favorite drawing/graphing tool. These may not be quite so universal as plain text, but you'll still be able to view them in any browser, and you should still be able to track them in a version control system just fine.


问:
Nice iterator naming
How do you name your iterators when you return a begin and an end iterator from a class?  Without it sounding clunky, that is.

Example:

```<code>typedef std::vector<Idea> Ideas_Type;

Ideas_Type::const_iterator GetIdeasBegin() const;
Ideas_Type::const_iterator GetIdeasEnd() const;
</code>```

Should it be GetIdeasBeginIter?  IdeasBegin?

答:
I would mimic the naming done in the STL. Now your classes work with many built-in functions.

begin

end

rbegin

rend

Title: Nice iterator naming


问:
Having 2 Initialize Paragraphs in 1 COBOL program
I am designing a COBOL program that does 2 things.

1 reads specific rows from a table, and inserts a new row based on the original.

2 reads different rows from the same table, and updates those rows.

Is it bad standards to have 2 initialization procedures? I need to declare 2 SQL cursors, one for each task. So I was thinking:

1 initialize cursor, 2 process, 3 initialize cursor, 4 process.

But that seems like bad logic. something is telling me it should be more like:

1 initialize cursor, 2 process But I'm having trouble thinking it out because to me, they are 2 separate tasks.

I tried to think of a way that my SQL query could do the work, and then I could just do some validation. But I'm not sure the query would be any more efficient than having a second read of the table.

Here's my structure ideas

I've added a 3rd chart that I believe follows the answer given to me on this question. Does the 3rd chart seem to me the most logical?

答:
You should separate the two tasks. You should have two cursors and initialize each separately since one is used for read and the other is for read/write.

You'd go like:

```<code> Move 0 to rc.

 Perform Task1

 If rc > 0

           logic to display message and end run.

 end

 perform Task2

 If rc > 0

           logic to display message and end run.

 end

 perform end of job messages and close open files if any.

 Stop Run.

.....................

 Task1 is:

 Open cursor 1 ...

...

Close cursor 1.

.....................

 Task2 is:

 Open cursor 2 ...

...

Close cursor 2.
</code>```

Body:
You should separate the two tasks. You should have two cursors and initialize each separately since one is used for read and the other is for read/write.

You'd go like:

 Move 0 to rc.

 Perform Task1

 If rc > 0

           logic to display message and end run.

 end

 perform Task2

 If rc > 0

           logic to display message and end run.

 end

 perform end of job messages and close open files if any.

 Stop Run.

.....................

 Task1 is:

 Open cursor 1 ...

...

Close cursor 1.

.....................

 Task2 is:

 Open cursor 2 ...

...

Close cursor 2.


问:
What is wrong with my logic for the divide and conquer algorithm for Closest pair problem?
I have been following Coursera's course on Algorithms and came up with a thought about the divide/conquer algorithm for the closest pair problem, that I want clarified.

As per Prof Roughgarden's algorithm (which you can see here if you're interested):
For a given set of points P, of which we have two copies - sorted in X and Y direction - Px and Py, the algorithm can be given as

closestPair(Px,Py):

Divide points into left half - Q, and right half - R, and form sorted copies of both halves along x and y directions - Qx,Qy,Rx,Ry

Let closestPair(Qx,Qy) be points p1 and q1

Let closestPair(Rx,Ry) be p2,q2

Let delta be minimum of dist(p1,q1) and dist(p2,q2)

This is the unfortunate case, let p3,q3 be the closestSplitPair(Px,Py,delta)

Return the best result

Now, the clarification that I want is related to step 5.
I should say this beforehand, that what I'm suggesting, is barely any improvement at all, but if you're still interested, read ahead.

Prof R says that since the points are already sorted in X and Y directions, to find the best pair in step 5, we need to iterate over points in the strip of width 2*delta, starting from bottom to up, and in the inner loop we need only 7 comparisions. Can this be bettered to just one?

How I think is possible seemed a little difficult to explain in plain text, so I drew a diagram and wrote it on paper and uploaded it here:

Since no one else came up with is, I'm pretty sure there's some error in my line of thought.
But I have literally been thinking about this for HOURS now, and I just HAD to post this. It's all that is in my head.

Can someone point out where I'm going wrong?

答:
Your simplification that lets you only do one comparison implicitly involves calculating the distance between points. I haven't watched the lecture you're referring to, but this is a well known algorithm; the assumptions and reasoning behind the step you're talking about go something like this:

For each point, a, within δ of the boundary, you can draw a box sized δ (in the x dimension) and 2 δ in the y dimension. By the assumption that no points are within d of each other in each region, that box contains at most 6 points, so you only need to compare a with at most 6 other points. The critical part that you’re missing is that this works because it’s a box. You already have the x and y coordinates of each point, so it’s easy to tell if it’s within some arbitrary rectangle. By turning the box into a circle, you actually create more work. How can you tell if a point is inside the circle? You have to calculate the distance to the center of the circle. You can limit the work by using the trick above, but then you’re back where you started.

If you don’t mind an unsolicited suggestion, I’d recommend coding up the algorithms you’re thinking of, until you can get the point where implementing algorithms is a trivial exercise. If you tried to code up your algorithm you’d quickly realize that there’s no way to find which points are within the circle you’re describing without doing more comparisons. After a while, you’ll get to the point where you aren’t tripped up by assumptions like that anymore.


问:
How do you manage your knowledge base?
As programmers we have a lot of inputs:

Ebooks

Code snippets

Interesting emails

Documents

Web articles

Blog posts

StackOverflow questions

Podcasts
...

Which tools do you use to store, organize, search and consult all of this stuff?

Is there a silver bullet solution to handle this huge amount of data?

答: TreePad Business Edition works for me.  Reasonable price, though freeware versions are also available.  Supports internal and external links, images, ... .  It doesn't need to be installed, so you can run it from a USB flash drive.</p>

Title: How do you manage your knowledge base?


问:
Is it worth moving from Microsoft tech to Linux, NodeJS & other open source frameworks to save money for a start-up?
I am currently getting involved in a startup, I am the only developer involved at the moment, and the other guys are leaving all the tech decisions up to me at the moment.

For my day job I work at a software house that uses Microsoft tech on a day to day basis, we utilise .NET, SqlServer, Windows Server etc. However, I realise that as a startup we need to keep costs down, and after having a brief look at the cost of hosting for Windows I was shocked to see some of the prices for a dedicated server. The cheapest I found was £100 a month. Also if the business needs to scale in the future and we end up needing multiple servers, we could end up shelling out £10's of £000's a year in SQL Server / Windows Server licenses etc.

I then had a quick look at the price of Linux hosting for a dedicated server and saw the price was waaaaaay lower than windows hosting. One place was offering a machine with 2 cores for less than £20 a month.

This got me thinking maybe the way to go is open source on Linux.

As I write a lot of Javascript at work (I'm working on a single page backbone app at the moment), I thought maybe NodeJS and a web framework like Express would be cool to use. I then thought that instead of using SQL why not use an open source NoSQL database like MongoDB, which has great support on NodeJS?

My only concern is that some of the work the application is going to do is going to be dynamically building images and various other image related stuff, i.e. stuff that is quite CPU heavy - so I'm thinking of maybe writing anything CPU heavy in C++ and consuming it as a module in Node.

That's the background - but basically is Linux a good match for:

Hosting a NodeJS/Express site?

Compiling C++ node modules?

Using a NoSQL DB like MongoDB?

And is it a good idea to move to these unfamiliar technologies to save money?

3 MONTH UPDATE

I've been working on this for the past few months now so thought I would give an update in case anyone is interested.

In the end I decided against using a NodeJS & Linux stack for the simple reason of time. I am doing this startup on the side, so I am working 9 hour days, then going home and working until late on the startup. While working in this way I obviously need to be as efficient with my time as possible, or I will never end up shipping the product.

After taking some of the advice on this thread I did apply for Microsoft BizSpark, and was accepted. This means I now have access to Visual Studio license, Windows Server license etc, all for free. Which is awesome. Hopefully by the time we are required to begin paying for everything we will be turning over enough that will make it a non-issue.

Do not think I am only using Microsoft tech, however, as I have tried to use open source stuff where possible. The main place I have done this is my data layer, where I have decided to use PostgreSQL and MongoDB. I am also using BackboneJS on my front end.

Below is a summary of the tech/frameworks I am currently using:

Standard DB stuff: PostreSQL

Logging & Data Store: MongoDB

ORM: Entity Framework 5

Core libraries: .NET (C#)

Web Framework: ASP.NET MVC3

UI: Razor view engine / BackboneJS

答: I don't really have an opinion on the server portion of your question, (node works just fine in my opinion, assuming you know javascript). However I will say that noSQL databases work very well with linux servers. I'm currently using an implementation of CouchDB, (easy replication whooo!), on a linux server and absolutely love it. As far as the compiling the C++ modules, I would recommend tying the cpu intensive work in javascript. After you get it working and decide its slow, then climb the C++ module hill. In my experience, having coded image manipulation, node may end up working just fine for your cpu needs. </p>


问:
Immutable structures and deep composition hierarchy
I'm developing a GUI application, heavily working with graphics - you can think about it as a vector editor, for the sake of the example. It is very tempting to make all data structures immutable - so I could get undo/redo, copy/paste, and many other things almost without effort.

Fot the sake of simplicity, I will use the following example - application is used to edit polygonal shapes, so I have "Polygon" object, which is simply list of immutable points:

```<code>Scene -> Polygon -> Point
</code>```

And so I have only one mutable variable in my program - the one which holds current Scene object. The problem which I have starts when I try to implement point dragging - in mutable version, I simply grab a Point object and start modifying its coordinates. In immutable version - I am stuck. I could have stored indices of Polygon in current Scene, index of dragged point in Polygon, and replace it every time. But this approach does not scale - when composition levels go to 5 and further, boilerplate would become unbearable.

I'm sure this problem can be solved - after all, there is Haskell with completely immutable structures and IO monad. But I just cannot find how.

Can you give me a hint?

答:
Deeply-immutable objects have the advantage that deep-cloning something simply requires copying a reference.  They have the disadvantage that making even a small change to a deeply-nested object requires constructing a new instance of every object within which it is nested.  Mutable objects have the advantage that changing an object is easy--just do it--but deep-cloning an object requires constructing a new object which contains a deep clone of every nested object.  Worse, if one wants to clone an object and make a change, clone that object, make another change, etc. then no matter how big or small the changes are one has to keep a copy of the entire hierarchy for every saved version of the object's state.  Nasty.

An approach that might be worth considering would be to define an abstract "maybeMutable" type with mutable and deeply-immutable derivative types.  All such types would feature an AsImmutable method; calling that method on a deeply-immutable instance of an object would simply return that instance.  Calling it on a mutable instance would return a deeply-immutable instance whose properties were deeply-immutable snapshots of their equivalents in the original.  Immutable types with mutable equivalents would sport an AsMutable method, which would construct a mutable instance whose properties matched those of the original.

Changing a nested object in a deeply-immutable object would require first replacing the outer immutable object with a mutable one, then replacing the property containing the thing to be changed with a mutable one, etc. but making repeated changes to the same aspect of the overall object would not require making any additional objects until such time as an attempt was made to call AsImmutable on a mutable object (which would leave the mutable objects mutable, but return immutable objects holding the same data).

As simple but significant optimizations, each mutable object could hold a cached reference to an object of its associated immutable type, and each immutable type should cache its GetHashCode value.  When calling AsImmutable on a mutable object, before returning a new immutable object, check it would match the cached reference.  If so, return the cached reference (abandoning the new immutable object).  Otherwise update the cached reference to hold the new object and return that.  If this is done, repeated calls to AsImmutable without any intervening mutations will yield the same object references.  Even if one doesn't save the cost of constructing the new instances, one will avoid the memory cost of keeping them.  Further, equality comparisons between the immutable objects may be greatly expedited if in most cases the items being compared are reference-equal or have different hash codes.


答:
It's unclear from your question, but if you are thinking of something like this:

```<code>class Brain {
  typedef std::vector<Idea> Ideas; // Not "Ideas_Type".  That's why it's capitalized.
  Ideas::const_iterator firstIdea();
  Ideas::const_iterator lastIdea();
}
</code>```

There's no need for all that.  You may as well say

```<code>class Brain {
  ...
  const Ideas &ideas();
}
</code>```

By returning a constant reference to the collection, it allows callers to process the collection as they see fit without modifying it.  If you don't want to expose the entire vector interface, then you can create a small class like this:

```<code>class my_list<T>: private std::vector<T> {
public:
  // whatever methods you like, including begin(), end(), ...
}
</code>```

And as a matter of style, save "get" methods for legacy languages.

Title: Nice iterator naming

Body:
How do you name your iterators when you return a begin and an end iterator from a class?  Without it sounding clunky, that is.

Example:

```<code>typedef std::vector<Idea> Ideas_Type;

Ideas_Type::const_iterator GetIdeasBegin() const;
Ideas_Type::const_iterator GetIdeasEnd() const;
</code>```

Should it be GetIdeasBeginIter?  IdeasBegin?

Body:
It's unclear from your question, but if you are thinking of something like this:

class Brain {
  typedef std::vector<Idea> Ideas; // Not "Ideas_Type".  That's why it's capitalized.
  Ideas::const_iterator firstIdea();
  Ideas::const_iterator lastIdea();
}

There's no need for all that.  You may as well say

class Brain {
  ...
  const Ideas &ideas();
}

By returning a constant reference to the collection, it allows callers to process the collection as they see fit without modifying it.  If you don't want to expose the entire vector interface, then you can create a small class like this:

class my_list<T>: private std::vector<T> {
public:
  // whatever methods you like, including begin(), end(), ...
}

And as a matter of style, save "get" methods for legacy languages.


答:
I think that the first approach "class UserAdminView extends View" is better. UpdateView fits better as an method of class a than an actual class.

If you want UserAdminUpdateView to be inheriting from a class than the superclass should be an UserAdmin class not a view class.

Title: In a web application, is it ok to group multiple pages in one view class or one class per page?

Body:
If you are building a web application, and you have a user management component, is it recommended to do:

```<code>class UserAdminView extends View {

}
</code>```

or

```<code>class UserAdminUpdateView extends View {

}
</code>```

What about controllers? Thoughts?


问:
Creating a line of business application with Visual Studio Isolated Shell
I ask this to the pros out there - Is it feasible to build a new LOB(Line Of Business) application with VS Shell as an stand alone application.

There are some points that I thought needs to changed, but I'm unaware how, like -

There will be no document. Instead there will be windows with controls where people enter data.
There will be no file menu(new,edit). Instead there will be a login box when the application opens(something like the SQL Server Management Studio).
There should be floating windows which hosts the control and some kind of window management where these windows can be minimized(obviously inside the shell)
These are some of the points which I thought of. Obviously there are many other points which needs to be changed and I ask you to populate the list.

Also please point me out how to start with it, best practices and possibly any other tips which you think should be mentioned.

答: Technically, yes you very much could do LOB apps with Visual Studio shell, however the shell is probably over kill for your standard LOB apps. If what you like is the docking, moving windows around etc, you could try the Avalon Dock control available for WPF, which will give you very similar functionality, and in my experience has been simple to use, and works with a basic WPF application.</p>


答:
I can't believe no one answered Github. It's great; for just code snippets, you can use Gist.

I bookmark interesting articles and use dropbox for everything else. (files, vid tutorials, podcasts)

As for SO questions, well, just SO?

Title: How do you manage your knowledge base?

Body:
As programmers we have a lot of inputs:

Ebooks

Code snippets

Interesting emails

Documents

Web articles

Blog posts

StackOverflow questions

Podcasts
...

Which tools do you use to store, organize, search and consult all of this stuff?

Is there a silver bullet solution to handle this huge amount of data?


问:
Does it still make sense to think about effective code on micro scale in C++?
Early in my programming career I was in love with pointer twiddling, lean code, doing everything with as little layers of abstraction as possible and so on. The code was very C like I would say, close to metal and clever.

Time has passed, I have a lot more experience, and I'm noticing my attitude towards the code has changed.

And with changed, I mean, I don't want to bother about everyday stuff anymore, unless it's super easy to do.

If there is a string concatenation, I will never choose raw pointers deliberately. If I need to concatenate stuff, I might add a quick guess reserve for an STL container, but I don't want to bother with preallocated buffers, C like APIs, caches, avoiding hitting the disk, or trashing. I know realloc might happen from time to time, including all the heap locks, extra copying and so on, but I don't even bother anymore.

Maybe, it is because I have spent some time early in my career where I thought of a clean and beautiful schemes with worker threads that process large amount of trivial data, only to find out later that the whole unoptimized realloc+copy+realloc+copy+realloc+copy+5 layers of wrappers doesn't even register in profiler.

Maybe it's because I've seen how compilers sometimes do magic.

However, such trivial things do add up. When all your code base uses higher order constructs, it has chances that there will be some realloc all over the place, or cold disk hits, that can cause a general perception of a slow application.

Sort of like WTL vs MFC. Or how you instantly know that the application is written in Java when you launch it.

But is it really? Is there any comparisons of software that's using only very lean and smart code vs software that uses generic containers all over the place?

Would you even feel a difference if the string allocation throughout the program would be using prereserves and smart moves vs lazily calling string.append in every place where there is a need for such functionality?

Do you try to implement mitigation solutions for such simple, well known things that are cheap to execute anyway?

Can software turn into bloatware just because extra caution is not applied to every line of code?

答:
No. Profilers can quickly and adequately tell you exactly where the problem spots are.

The reason why some frameworks are problematic is because when the problem spot is in a framework or virtual machine function, you are screwed. If you have, realistically, complete performance control over the application then go nuts. This is why you can tell when an app is launched with Java- when the slowdown is in the JVM code, there's nothing any dev can do about it. However, this tends not to be an issue with C++ development in general.

Not to mention that the power of compilers to cut the crap and make your very high-level code go much faster grows every year.

Is there any comparisons of software that's using only very lean and smart code vs software that uses generic containers all over the place?

Hate to break it to you, buddy, but generic containers are lean and smart. One of their primary advantages is that because you don't have to re-write them for every type that ever lived, you can afford to write high-performance code once and re-use it. It's a simple application of DRY that improves both performance and reliability. Writing it yourself 999999 times isn't the smart code, that's the dumb code.


答:
It will depend on which web-development design pattern your team is set to go/follow.

For example: in MVC design patter, each view it is recommended to have a dedicated view-model. While your models are the constructs that serve as a data containers, it is not recommend expose them directly as view-models. Thus, depending on view requirement, a custom view-model is build from a single or multiple models.

Important productivity tip: for a convention-based object-object mapper always try to look fr tools like AutoMapper. It will save tons of time during the development.


答:
For anyone who is a minimalist and a Mac user, try Notational Velocity.

It has an extremely streamlined interface. You type in a title, which will search your notes, or create a new note depending on what action you take. You never have to take your hands off the keyboard as there's a short-cut for everything. Also, if you are entering something while a little heft to it, there's a shortcut to start editing in your favorite text editor.

It syncs nicely with either Dropbox or Simplenote (which is great if you want a cross-platform solution).

I've tried a few other note-takers, but it's the only one I've used consistently. I guess mainly because it's quick, simple, and painless.

Title: How do you manage your knowledge base?


问:
When, Where, and How to Unit Test
I'm very familiar with xUnit frameworks and I try to implement unit tests on every project I start. Somewhere along the way, I realize that I'm writing the same tests over and over again, and then I run into a really difficult to test method or a test involving remote resources, and then I give up for a while. I end up coming back eagerly whenever I can to test simple things, but as soon as I run into harder things to test, I run for the hills with my tail between my legs.

Let's throw in some examples.

Long flow of things to do in a method. (How do I test this? Do I just make sure that the code's being called by stubbing things out? How should I rewrite the code to facilitate easier testing?)

```<code>public void doSomething() {
    Object1 value1 = doSomething1(this.getName());
    if (value1.isError()) {
        sendError(new Object1Error(value1.getError().getMessage()));
        return;
    }

    Object2 value2 = doSomething2(value1, this.getName());
    if (value2.isError()) {
        sendError(new Object2Error(value2.getError().getMessage()));
        return;
    }

    /* ad infinitum... */
}
</code>```

Overloaded methods and constructors.

```<code>public String toJSON() {
    return toJSON(true);
}

public String toJSON(boolean prettyPrint) {
    /* do work */
    return result;
}

/* test */
@Test public void testToJSON() { ... };

@Test public void testToJSONBoolean() { /* redundant similar test code... */ }
</code>```

Remote resources. How do I test that my upload API is working (ie: right request method, host, request content type, payload, etc.) without actually doing an upload? These uploads go to servers outside of my control.

```<code>public void doUpload() throws IOException {
    HttpClient client = new HttpClient();
    PutMethod putMethod = new PutMethod(...);
    putMethod.setRequestHeader(...);
    putMethod.setRequestEntity(new FileInputStreamRequestEntity(...));

    /* etc. */

    final int responseCode = client.executeMethod(putMethod);
}
</code>```

Testing server interactions with clients.

```<code>/* before we even get here, other interactions need to take place */
public void updateClientProfile(UserProfile profile) {
    // 1. validate the input
    // 2. update the user in the db
    // 3. generate an email in HTML
    // 4. send the email
    // 5. serve out a view
}
</code>```

Testing at first glance seems easy, until I get to these kind of situations. How do I keep my motivation for testing and write my code to be more testable?

It seems that the more things that a method needs to do, the exponentially more difficult and frustrating unit tests are to write. Do I test simply that the code is calling the right services and methods? Do I write unit tests simply to prove to myself that my code calls the methods I told it to call, or to determine that the logic is right? Help!

答:
First things first, When is Unit Testing Inappropriate or Unnecessary?

This is subtly different enough though.

I end up coming back eagerly whenever I can to test simple things, but as soon as I run into harder things to test, I run for the hills with my tail between my legs.

This is the biggest problem. If you get nothing else from the answer: focus on this. This is a problem that will impact your programming, your career... everything. The going will get hard, and learning to deal with it effectively is a vital personal skill.

On to the examples:

1 - a method doing a series of operations

Test the individual operations separately. If they can be mocked, mocking them will help test this method. Breaking this method into doing fewer things will help. If appropriate, having a construct that runs a sequence of delegates/function objects in order unless an error occurs will help because then you can test that construct with arbitrary functions that behave better. As an upside, that construct can be reused if you run into a similar pattern in the future.

For this particular example, I would consider refactoring to use exceptions rather than error codes. It depends on what the actual code is doing and the exception support of the language/platform.

2 - a method overload that trivially calls another

Personally I wouldn't test the trivial overload, just the core function. The trivial overload is obviously correct, and if it changes enough to break things then your other tests should fail when the implied true is not correct.

3 - methods using external resources

There are three things to consider here, since it's not clear what the example entails:

If you can, mock out the external resources. As long as your code sends the right stuff to the 'known good' API (and reacts correctly to the expected response), then that's good enough.

Make sure that you're not testing the 'known good' API.

If it's important enough, then it's worthwhile to make automated tests that aren't unit tests. Have a server that you can control and test if the upload works. These are integration tests or system tests or simply automated functional tests depending on their scope and who you're talking to. These are still useful in scenarios like these where you need to test something, but cannot effectively unit test them.

4 - server processing a request

This is similar to some of the earlier advice: Break out the components, test those individually, mock where possible, use integration tests if appropriate.

A note on mocking

This is a point that I've talked about a few times here, but might not be clear what I mean or how it can help you. Mocking.

Mocking is the use of a test-specific object (a mock object) in place of a real object to isolate the code you're looking to test. There are a number of frameworks to automate this process. Personally, I find these to be oftentimes fragile and overly complex. Sometimes they are vital to getting at things you can't get to. The simplest mock object is one you just make and supply.

When designing your test, any time you call something to get data or send data outward, consider a mock object. They allow you to supply the proper data for the test. They allow you to verify that the outward bound data is what it should be.

They are a bit of overhead though, and can make test maintenance more burdensome. If you find yourself needing them a lot, it can be a sign that your code is too widely coupled. Just be aware of these things and weigh them against the upside when doing test design. For things like database access, they are invaluable.

Title: When, Where, and How to Unit Test


答:
"Don't blame the mirror for the ugly face"

Problems you observe in tests just honestly reflect the problems with the quality of the source code.

It is very (very) unlikely that continuing blindly throwing unit tests on code that you found to be poorly designed will help you make further progress here. I tried that and I failed. I have been ready to convince self that it's my fault, that it's just me unable of making it work, but I dropped that idea after I saw that colleagues much more talented than me are having exactly the same problems (an advantage of working in strong team is that you can easily gauge when things go wrong because of your own limitations and when it happens because things are wrong).

Your best bet would be to get in touch with professional testers, setup a thorough QA to catch functional regressions and after that, refactor the code into something better - into something that makes writing unit tests productive and fun, as it should be.

Quoting self - thing is, approaches applicable with better codebase just don't cut it:

With bad code... unit tests do things opposite to how I use them in good code, like breaking at reasonable changes and failing to catch the real mistakes I make. Which is painful but not surprising - what else would one expect from testing units which have bad design to start with? Instead of helping you improve the design, unit tests often work to preserve bad code - eg in my recent maintenance project I was regularly removing large chunks of code which was only referenced from outdated senseless unit tests. BTW I use that knowledge when writing new code: when I find out that my unit tests tend to get too complicated / fragile, this indicates a need to fix some issue with my own design...

Title: When, Where, and How to Unit Test

Body:
I'm very familiar with xUnit frameworks and I try to implement unit tests on every project I start. Somewhere along the way, I realize that I'm writing the same tests over and over again, and then I run into a really difficult to test method or a test involving remote resources, and then I give up for a while. I end up coming back eagerly whenever I can to test simple things, but as soon as I run into harder things to test, I run for the hills with my tail between my legs.

Let's throw in some examples.

Long flow of things to do in a method. (How do I test this? Do I just make sure that the code's being called by stubbing things out? How should I rewrite the code to facilitate easier testing?)

```<code>public void doSomething() {
    Object1 value1 = doSomething1(this.getName());
    if (value1.isError()) {
        sendError(new Object1Error(value1.getError().getMessage()));
        return;
    }

    Object2 value2 = doSomething2(value1, this.getName());
    if (value2.isError()) {
        sendError(new Object2Error(value2.getError().getMessage()));
        return;
    }

    /* ad infinitum... */
}
</code>```

Overloaded methods and constructors.

```<code>public String toJSON() {
    return toJSON(true);
}

public String toJSON(boolean prettyPrint) {
    /* do work */
    return result;
}

/* test */
@Test public void testToJSON() { ... };

@Test public void testToJSONBoolean() { /* redundant similar test code... */ }
</code>```

Remote resources. How do I test that my upload API is working (ie: right request method, host, request content type, payload, etc.) without actually doing an upload? These uploads go to servers outside of my control.

```<code>public void doUpload() throws IOException {
    HttpClient client = new HttpClient();
    PutMethod putMethod = new PutMethod(...);
    putMethod.setRequestHeader(...);
    putMethod.setRequestEntity(new FileInputStreamRequestEntity(...));

    /* etc. */

    final int responseCode = client.executeMethod(putMethod);
}
</code>```

Testing server interactions with clients.

```<code>/* before we even get here, other interactions need to take place */
public void updateClientProfile(UserProfile profile) {
    // 1. validate the input
    // 2. update the user in the db
    // 3. generate an email in HTML
    // 4. send the email
    // 5. serve out a view
}
</code>```

Testing at first glance seems easy, until I get to these kind of situations. How do I keep my motivation for testing and write my code to be more testable?

It seems that the more things that a method needs to do, the exponentially more difficult and frustrating unit tests are to write. Do I test simply that the code is calling the right services and methods? Do I write unit tests simply to prove to myself that my code calls the methods I told it to call, or to determine that the logic is right? Help!


答:
No, because while you are using a VCS, you are not doing version control.

The central concept for version control is tracking difference over time, you are PLANNING on recording some differences, but at the moment most of your changes are unrecorded.

As others have said, you should be using branches.  Once you have that setup, you should be checking in all functional changes (ie not every keystroke, but anytime you fix a bug, add a feature, delete a feature or otherwise complete a change such that it still builds and works).


问:
How much design happens in your implementation phase?
For those of you who work in big-design-up-front/waterfall groups: how much critical thinking and design is skipped in your design phase and left to your implementation phase? How complete and detailed are your functional and technical specifications delivered at the end of the design phase?

It seems to me that there's a lot of room for interpretation in the level of detail that needs to be provided at the end of the Design phase, and it irks me when the design phase is rushed and then managers get angry that the build phase doesn't progress like we're churning out widgets on an assembly line. On the other hand, a design phase that's complete enough to make the build phase operate like an assembly line practically includes the implementation phase with it - all that would be left in "build" is to type stuff into the editor. Of course, it also means your design phase is gigantic.

I realize that this is a shortcoming of the waterfall model, but if there's anyone out there that can provide some constructive advice: Where does one draw the line? What should the expectations for the design and build phases be, and what kinds of design shortcomings or mistakes should/shouldn't be tolerated in the build phase?

答:
There is always something missed in the design phase. People are imperfect, and even with a perfect management that permits lots of design phase time without the pressure to move on to implementation, there will be things you missed.

Likewise, in design, you enter a point of diminishing returns. For example, if designing a user interface and writing that in a spec, you can rapidly reach the point where the spec contains the layout, formatting, and all of the logic of a form. In which case its pretty much identical to the implementation, with perhaps only the messy bits of code glue being different.

You do need to query the value of pushing the design too far: when design turns into writing the code because thats the clearest way to convey your intent, its time to ask if enough is enough.

Implementation, then, will start to uncover things forgotten or missed, as well as other implementation details that might have seemed easy but turn out not to be. (Perhaps the services you thought you might get from some library, or your OS, turn out to be not quite as expected... and you need to do some digging or write a whole lot of new code as a work-around, shim or patch.)

Waterfall is a lovely simple model, great for explaining to management. It is also pretty far removed from the iterative and mixed high level /low level thinking that happens in reality.

A bit more interesting commentary about this can be found in an older book: "Decline and fall of the American Programmer" by Ed Yourdon.

I know this is not a perfect answer, but then, programming & design methodologies are not perfect either. The best approach to them is to treat them as a Helpful System For Getting Things Done. The rules are there to HELP you, and to be broken when they get in the way. The breaking of the rules should be done intelligently, not simply because somebody felt like cutting code from day 1.


答:
There is a paper called A Note Concerning The Closest Pair Problem by Martin Richards (IPL 82 (2002) p193-195) which gets the number of comparisons down to 2 on the other side.

Its fairly easy to arrange 2 points from the other side and the current point so they're all d units apart and in the square half box. You just make them an equilateral triangle. Now by sliding either of these microscopically up towards the current point, you can make either one the closest point. So they're both candidates.

One of the interesting points in the paper was that empirical testing on the normal algorithm showed that there was almost always one or zero points in the candidate box. So you could get the standard algorithm to perform as well yours by pruning out points which got pushed outside the box rather than just blindly comparing against the last 7 points within the strip.

Title: What is wrong with my logic for the divide and conquer algorithm for Closest pair problem?

Body:
I have been following Coursera's course on Algorithms and came up with a thought about the divide/conquer algorithm for the closest pair problem, that I want clarified.

As per Prof Roughgarden's algorithm (which you can see here if you're interested):
For a given set of points P, of which we have two copies - sorted in X and Y direction - Px and Py, the algorithm can be given as

closestPair(Px,Py):

Divide points into left half - Q, and right half - R, and form sorted copies of both halves along x and y directions - Qx,Qy,Rx,Ry

Let closestPair(Qx,Qy) be points p1 and q1

Let closestPair(Rx,Ry) be p2,q2

Let delta be minimum of dist(p1,q1) and dist(p2,q2)

This is the unfortunate case, let p3,q3 be the closestSplitPair(Px,Py,delta)

Return the best result

Now, the clarification that I want is related to step 5.
I should say this beforehand, that what I'm suggesting, is barely any improvement at all, but if you're still interested, read ahead.

Prof R says that since the points are already sorted in X and Y directions, to find the best pair in step 5, we need to iterate over points in the strip of width 2*delta, starting from bottom to up, and in the inner loop we need only 7 comparisions. Can this be bettered to just one?

How I think is possible seemed a little difficult to explain in plain text, so I drew a diagram and wrote it on paper and uploaded it here:

Since no one else came up with is, I'm pretty sure there's some error in my line of thought.
But I have literally been thinking about this for HOURS now, and I just HAD to post this. It's all that is in my head.

Can someone point out where I'm going wrong?


问:
What do you say in a code review when the other person built an over complicated solution?
The other day I reviewed code someone on my team wrote. The solution wasn't fully functional and the design was way over complicated-- meaning stored unnecessary information, built unnecessary features, and basically the code had lots of unnecessary complexity like gold plating and it tried to solve problems that do not exist.

In this situation I ask "why was it done this way?"

The answer is the other person felt like doing it that way.

Then I ask if any of these features were part of the project spec, or if they have any use to the end user, or if any of the extra data would be presented to the end user.

The answer is no.

So then I suggest that he delete all the unnecessary complexity. The answer I usually get is "well it's already done".

My view is that it is not done, it's  buggy, it doesn't do what the users want, and maintenance cost will be higher than if it were done in the simpler way I suggested.

An equivalent scenario is:

Colleague spends 8 hours refactoring code by hand which could have been automatically done in Resharper in 10 seconds. Naturally I don't trust the refactoring by hand as it is of dubious quality and not fully tested.

Again the response I get is "well it's already done."

What is an appropriate response to this attitude?

答:
Mentality/attitude

Lead by example

Admonish in private (one-to-one, outside the code review)

Encourage a Keep-it-simple mentality among team members

Team management

Spend more time on the specification of a work item (such as architecture, algorithm outline, UI wireframe, etc)

Encourage team members to seek clarification about the scope of a work item

Encourage team members to discuss ways of implementing a work item

Make reasonable estimates for each work item before starting, and make best effort to meet them

Monitor the "improvement" of team members.

After being admonished or being shown the right way to do things, see if the team member improve.

Skill level

Allocate some time for pair-programming sessions or one-to-one training sessions for making the best use of developer tools (refactoring, code-review)

Project (risk) management

Conduct code-review more often, asynchronously (Note)

Note about "asynchronously"

The code reviewer should get notifications / invitations to review changes as soon as being committed

The code reviewer should have a chance to review the code before any meeting with the developer.

If clarification from the developer is needed, do it informally on IM/email without casting a negative opinion


问:
What is the most basic and simple platform for collaborative development (PHP project)?
I need to work with 4-5 programmers on a fairly average PHP application using codeigniter. We're in 5 different locations in one city, and all of the programmers are all not too well educated and I'm assuming that most of them have never used any version control system.

Can you recommend some very very easy-to-get-into platform for collaborating on a project like this? I'm talking about something that is only a tad more sophisticated than a shared dropbox folder.

答:
I'm assuming that most of them have never used any version control system.

You need to correct that assumption and find out if they do or do not have any knowledge or experience of any version control systems.  No point assuming when they could have knowledge.

As other answers have said, this is what version control is for.  Git is probably the best way forward, and Learn Git is a really good starting point


答:
There should be a standard policy in the project that controls deliverable quality checking procedures and tools used.

People should know what they should do and what tools are accepted for use in this project.

If you have not done this yet, organize your thoughts and do it.

Code review should have a check list of standard items. If you get "it is already done" and it is not, then personally, I would not want to be responsible for this developer's work as project manager or senior developer. This attitude must not be tolerated. I can understand arguing about how to do something or even every thing, but once a solution is accepted, lying should not be tolerated and that should be clearly stated.

Title: What do you say in a code review when the other person built an over complicated solution?

Body:
The other day I reviewed code someone on my team wrote. The solution wasn't fully functional and the design was way over complicated-- meaning stored unnecessary information, built unnecessary features, and basically the code had lots of unnecessary complexity like gold plating and it tried to solve problems that do not exist.

In this situation I ask "why was it done this way?"

The answer is the other person felt like doing it that way.

Then I ask if any of these features were part of the project spec, or if they have any use to the end user, or if any of the extra data would be presented to the end user.

The answer is no.

So then I suggest that he delete all the unnecessary complexity. The answer I usually get is "well it's already done".

My view is that it is not done, it's  buggy, it doesn't do what the users want, and maintenance cost will be higher than if it were done in the simpler way I suggested.

An equivalent scenario is:

Colleague spends 8 hours refactoring code by hand which could have been automatically done in Resharper in 10 seconds. Naturally I don't trust the refactoring by hand as it is of dubious quality and not fully tested.

Again the response I get is "well it's already done."

What is an appropriate response to this attitude?


答:
Your shop needs to enforce some design methodologies.

Requirements need to be defined clearly.

You need to develop use cases which support the requirments.

You need to specify functions needed to implement the use cases.

You need to specify any non functional requirements (response times, availability etc.)

You need an RTM (Requiements Tracabilty Matrix) to map each system function back to a use case and a real requirement.

Drop any function that is not supporting an actual requirement.

Finally in your code review flag any code that does not directly implement or support the defined functions.