答:
In a comment you wrote that this is a code generation issue - essentially a factory or builder pattern.

I would argue that is is possible to optimize the conditionals away in a lot of practical scenarios like the example below shows. In addition i would clain that if the execution time to get a boolean information about A, B or C varies optimization can not be done by optimizing if/else statements. This couvers all scenarios that i am aware of.

The fastest way to evaluate would be to present all booleans in a common variable and only evaluate that single variable. Depending on the system this is meant to run on this may or may not be possible and may or may not already be the case.

The solution should scale up with constant execution to the point where the ammount of bool information excessed the ammount of bits in an integer.

This is meant as a preactical solution with a finite set of booleans where it is known at compiletime what set of booleans should result in what set of executions.

Here is some pseudocode:

```<code>func()
{
    unsigned currentSwitches = GetBooleanSet();
    executeable currentExEc = ExecFactory(currentSwitches);
    currentExEc();
}

executeable ExecFactory(unsigned allMySwitches)
{
    switch(allMySwitches)
    {
        case 0x....: return exeLib.HeaterOn; break;
        case 0x....: return exeLib.HeaterOff; break;
        case 0x....: return exeLib.BeepLikeCrazy; break;
        default : return exeLib.NotImplementedExecution; break;
    }
}
</code>```

Edit:

Depending on how you are presented with your booleans you may or may not have to do anything at all. One scenario is that you read your booleans from some form of stream (TCP, File, etc) where they may already comacted. Another option may be that you are in a from of programmable logic environment where your bool options already share a register.

Suppose you are not in that position you may end up with custom bit fiddeling. Here is one expensive option to do that in the from of pseudocode:

```<code>enum {
bit_A, bit_B, bit C
}

GetBooleanset()
{
return (bool_A << bit_A) | (bool_B << bit_B) | (bool_C << bit_C);
}
</code>```

This expression will be optimized by your build process and you can check if the speed fits your requirements. Depending on the ammount of options and their volatility you may for example optimize by tracking the changed options and rebuild only the parts that did change.

It really depends heavily on the environment you are working in.

EDIT:

I wrote a small Ansi C implementation of the pseudocode above.

```<code>#include <stdio.h>

typedef int (*t_logf)(const char * format, ...);

#define opt_A ( 1U << 0U )
#define opt_B ( 1U << 1U )
#define opt_C ( 1U << 2U )

typedef struct {
    unsigned options;
    t_logf logf;
}System;

typedef void (*execDelegate) (System * system);
void DelegateOne (System * system);
void DelegateTwo (System * system);
void DelegateThree (System * system);
void DelegateDefault (System * system);

void buildOptions(System * system);
execDelegate ExecFactory(System * system);

void main()
{
    System system;
    execDelegate execute;
    system.logf = printf;

    buildOptions(&system);
    execute = ExecFactory(&system);
    execute(&system);

    getchar();
}

void buildOptions(System * system)
{
    //this would obviousely
    system->options = opt_A | opt_C;
}

execDelegate ExecFactory(System * system)
{
    system->logf("options: 0x%X\n", system->options);
    switch(system->options)
    {
        case opt_A | opt_B | opt_C : return DelegateOne; break;
        case opt_B | opt_C : return DelegateTwo; break;
        case opt_A | opt_C : return DelegateThree; break;
        default : return DelegateDefault; break;
    }
}

void DelegateOne (System * system)
{
    system->logf("one\n");
}

void DelegateTwo (System * system)
{
    system->logf("two\n");
}

void DelegateThree (System * system)
{
    system->logf("three\n");
}

void DelegateDefault (System * system)
{
    system->logf("default\n");
}
</code>```

Body:
In a comment you wrote that this is a code generation issue - essentially a factory or builder pattern.

I would argue that is is possible to optimize the conditionals away in a lot of practical scenarios like the example below shows. In addition i would clain that if the execution time to get a boolean information about A, B or C varies optimization can not be done by optimizing if/else statements. This couvers all scenarios that i am aware of.

The fastest way to evaluate would be to present all booleans in a common variable and only evaluate that single variable. Depending on the system this is meant to run on this may or may not be possible and may or may not already be the case.

The solution should scale up with constant execution to the point where the ammount of bool information excessed the ammount of bits in an integer.

This is meant as a preactical solution with a finite set of booleans where it is known at compiletime what set of booleans should result in what set of executions.

Here is some pseudocode:

func()
{
    unsigned currentSwitches = GetBooleanSet();
    executeable currentExEc = ExecFactory(currentSwitches);
    currentExEc();
}

executeable ExecFactory(unsigned allMySwitches)
{
    switch(allMySwitches)
    {
        case 0x....: return exeLib.HeaterOn; break;
        case 0x....: return exeLib.HeaterOff; break;
        case 0x....: return exeLib.BeepLikeCrazy; break;
        default : return exeLib.NotImplementedExecution; break;
    }
}

Edit:

Depending on how you are presented with your booleans you may or may not have to do anything at all. One scenario is that you read your booleans from some form of stream (TCP, File, etc) where they may already comacted. Another option may be that you are in a from of programmable logic environment where your bool options already share a register.

Suppose you are not in that position you may end up with custom bit fiddeling. Here is one expensive option to do that in the from of pseudocode:

enum {
bit_A, bit_B, bit C
}

GetBooleanset()
{
return (bool_A << bit_A) | (bool_B << bit_B) | (bool_C << bit_C);
}

This expression will be optimized by your build process and you can check if the speed fits your requirements. Depending on the ammount of options and their volatility you may for example optimize by tracking the changed options and rebuild only the parts that did change.

It really depends heavily on the environment you are working in.

EDIT:

I wrote a small Ansi C implementation of the pseudocode above.

#include <stdio.h>

typedef int (*t_logf)(const char * format, ...);

#define opt_A ( 1U << 0U )
#define opt_B ( 1U << 1U )
#define opt_C ( 1U << 2U )

typedef struct {
    unsigned options;
    t_logf logf;
}System;

typedef void (*execDelegate) (System * system);
void DelegateOne (System * system);
void DelegateTwo (System * system);
void DelegateThree (System * system);
void DelegateDefault (System * system);

void buildOptions(System * system);
execDelegate ExecFactory(System * system);

void main()
{
    System system;
    execDelegate execute;
    system.logf = printf;

    buildOptions(&system);
    execute = ExecFactory(&system);
    execute(&system);

    getchar();
}

void buildOptions(System * system)
{
    //this would obviousely
    system->options = opt_A | opt_C;
}

execDelegate ExecFactory(System * system)
{
    system->logf("options: 0x%X\n", system->options);
    switch(system->options)
    {
        case opt_A | opt_B | opt_C : return DelegateOne; break;
        case opt_B | opt_C : return DelegateTwo; break;
        case opt_A | opt_C : return DelegateThree; break;
        default : return DelegateDefault; break;
    }
}

void DelegateOne (System * system)
{
    system->logf("one\n");
}

void DelegateTwo (System * system)
{
    system->logf("two\n");
}

void DelegateThree (System * system)
{
    system->logf("three\n");
}

void DelegateDefault (System * system)
{
    system->logf("default\n");
}


问:
Can I use Dependency Injection without breaking Encapsulation?
Here is my Solution and projects:

BookStore  (solution)

BookStore.Coupler  (project)

Bootstrapper.cs

BookStore.Domain (project)

CreateBookCommandValidator.cs

CompositeValidator.cs

IValidate.cs

IValidator.cs

ICommandHandler.cs

BookStore.Infrastructure (project)

CreateBookCommandHandler.cs

ValidationCommandHandlerDecorator.cs

BookStore.Web (project)

Global.asax

BookStore.BatchProcesses (project)

Program.cs

Bootstrapper.cs:

```<code>public static class Bootstrapper.cs
{
    // I'm using SimpleInjector as my DI Container
    public static void Initialize(Container container)
    {
        container.RegisterManyForOpenGeneric(typeof(ICommandHandler<>), typeof(CreateBookCommandHandler).Assembly);
        container.RegisterDecorator(typeof(ICommandHandler<>), typeof(ValidationCommandHandlerDecorator<>));
        container.RegisterManyForOpenGeneric(typeof(IValidate<>),
            AccessibilityOption.PublicTypesOnly,
            (serviceType, implTypes) => container.RegisterAll(serviceType, implTypes),
            typeof(IValidate<>).Assembly);
        container.RegisterSingleOpenGeneric(typeof(IValidator<>), typeof(CompositeValidator<>));
    }
}
</code>```

CreateBookCommandValidator.cs

```<code>public class CreateBookCommandValidator : IValidate<CreateBookCommand>
{
    public IEnumerable<IValidationResult> Validate(CreateBookCommand book)
    {
        if (book.Author == "Evan")
        {
            yield return new ValidationResult<CreateBookCommand>("Evan cannot be the Author!", p => p.Author);
        }
        if (book.Price < 0)
        {
            yield return new ValidationResult<CreateBookCommand>("The price can not be less than zero", p => p.Price);
        }
    }
}
</code>```

CompositeValidator.cs

```<code>public class CompositeValidator<T> : IValidator<T>
{
    private readonly IEnumerable<IValidate<T>> validators;

    public CompositeValidator(IEnumerable<IValidate<T>> validators)
    {
        this.validators = validators;
    }

    public IEnumerable<IValidationResult> Validate(T instance)
    {
        var allResults = new List<IValidationResult>();

        foreach (var validator in this.validators)
        {
            var results = validator.Validate(instance);
            allResults.AddRange(results);
        }
        return allResults;
    }
}
</code>```

IValidate.cs

```<code>public interface IValidate<T>
{
    IEnumerable<IValidationResult> Validate(T instance);
}
</code>```

IValidator.cs

```<code>public interface IValidator<T>
{
    IEnumerable<IValidationResult> Validate(T instance);
}
</code>```

ICommandHandler.cs

```<code>public interface ICommandHandler<TCommand>
{
    void Handle(TCommand command);
}
</code>```

CreateBookCommandHandler.cs

```<code>public class CreateBookCommandHandler : ICommandHandler<CreateBookCommand>
{
    private readonly IBookStore _bookStore;

    public CreateBookCommandHandler(IBookStore bookStore)
    {
        _bookStore = bookStore;
    }

    public void Handle(CreateBookCommand command)
    {
        var book = new Book { Author = command.Author, Name = command.Name, Price = command.Price };
        _bookStore.SaveBook(book);
    }
}
</code>```

ValidationCommandHandlerDecorator.cs

```<code>public class ValidationCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
    private readonly ICommandHandler<TCommand> decorated;
    private readonly IValidator<TCommand> validator;

    public ValidationCommandHandlerDecorator(ICommandHandler<TCommand> decorated, IValidator<TCommand> validator)
    {
        this.decorated = decorated;
        this.validator = validator;
    }

    public void Handle(TCommand command)
    {
        var results = validator.Validate(command);

        if (!results.IsValid())
        {
            throw new ValidationException(results);
        }

        decorated.Handle(command);
    }
}
</code>```

Global.asax

```<code>// inside App_Start()
var container = new Container();
Bootstrapper.Initialize(container);
// more MVC specific bootstrapping to the container. Like wiring up controllers, filters, etc..
</code>```

Program.cs

```<code>// Pretty much the same as the Global.asax
</code>```

Sorry for the long setup to the problem, I have no better way of explaining this other than detailing my actual problem.

I don't want to make my CreateBookCommandValidator public. I would rather it be internal but if I make it internal then I will not be able to register it with my DI Container.  The reason I would like it to be internal is because the only project that should have notion of my IValidate<> implementations are in the BookStore.Domain project.  Any other project just needs to consume IValidator<> and the CompositeValidator should be resolved which will fulfill all validations.

How can I use Dependency Injection without breaking encapsulation?  Or am I going about this all wrong?

答:
You could make it internal and use the InternalVisibleToAttribute msdn.link so your testing framework/project can access it.

I had a related problem -> link.

Here is a link to another Stackoverflow question regarding the problem:

And finally an article on the web.

OwnerDisplayName: Evan Larsen

ContentLicense: CC BY-SA 3.0


问:
Coworker that detrimentally picks on every minutia
Hypothetically speaking imagine that there exists a coworker that has a very shallow understanding of computing. To avoid stereotyping lets give this coworker the gender neutral name Chris.

Now Chris' diagnostic ability is low and can't figure out the correct IP addresses to set his/her virtual machines to. Chris also fails to merge code properly and overwrites a commit I made fixing something, thereby re-introducing a bug. I let this slide, refix the bug and do not make a sound about it to management.

Given a task Chris either 1) complains that there isn't sufficient information resulting in 2) you provide Chris with inordinately detailed instructions to satisfy 1). The more detail you provide in a list of steps to carry out, the more chance of an error being present in your instructions. Chris gets these instructions, tries to execute them, fails and it becomes your fault because your instructions aren't good enough. How do you deal with this?

答:
Don't ever try to spoon feed anyone, in the long run it always backfires (no exceptions).

Keep communication formal at all times, and use email. Copy seniors in the team on the mail exchanges.

Provide enough information for the person to dig in, but no more. This is a job remember, not a tuition service for bickering types.

ContentLicense: CC BY-SA 2.5


问:
Inventory management system design problem
What are the conventions for item batch identifiers in inventory management systems?

For example:

A retail supermarket can order 'Item X' from either 'Supplier A' or 'Supplier B'. When it completes an order for the item from either supplier, it needs to store the record of the receipt. Inventory quantity for the item is increased upon receipt of the order.

However it is also required to store some record of the supplier. Thus some sort of batch identifier is required. This batch identifier will uniquely identify the item received and the supplier from whom it is received. A new batch is created each time items are received in stock (for example, after an order).

Hence, for purposes of accounting / auditing, information available to identify an item after it was sold comprises of ITEM_CODE, ITEM_NAME, BATCH_CODE. The BATCH_CODE is unique and is associated with DATE_RECEIVED, SUPPLIER_CODE, QTY_RECEIVED.

Is this a complete system specification for the above scenario or has anything significant been left out?

答:
Inventory management is an intrinsic factor of any company that organizes goods to meet the needs of their high-end customers. Any organization that conducts an inventory of products has a need to maintain accurate information on the movement of all these products to better serve its customers and run a profitable business.

As per my view, you should hire proper programmers for the solution.


问:
Inserting HTML code with jquery
One of our web applications is a page that takes in a serial number and various information is returned and displayed to the user. The serial is passed via AJAX, and based on the response, one of the following can happen -

An error message is shown

A new form replaces the previous form

Now, the way I am handling this is to use jQuery to destroy (using $.remove()) the table that displayed the initial serial form, then I'm appending another html table that contains another form. Right now I am including that additional form as part of the html source, and just setting it to display:none, then using jQuery to show it when appropriate. However, I don't like this approach because if someone views source on the page, they can see that table html code that is not being displayed.

My next thought would be to use AJAX to read in another HTML file, and append it that way. However, I am trying to keep down the number of files this project uses, and since most pages in our project will use AJAX, I could see a case where there are multiple files containing HTML snippets - and that feels sloppy to me.

What is the best way to handle a case where multiple html elements are being shown and removed with jQuery?

答: Don't be afraid of more HTML files with specific responsibilities. Even if you use a js template engine, I would still suggest separating these "snippets" into their own files. When changing a form, you shouldn't need to worry about the serial entry markup. Separation of concerns applies to UI components too.</p>

Title: Inserting HTML code with jquery


问:
Java web application folder structure
As a beginner to J2EE, I have recently started developing my own project from scratch using the Core of J2EE : Servlets & Jsps.

I could not evaluate whether my project folder structure is right or not.
Here is my project folder structure.

Before asking question, I admit that I could not answer or neither justify if somebody asks me, why this type of folder structure.
The question: Is it a good sign to put my jsps outside of web-inf. If not, why is it so? If yes why?

Is there any standard folder structure convention for a J2EE web application, I know maven has brought up some standards but still, we can customize as per the requirement I believe.

I have done a bit of googling and found the two references
1
2

where in the answers are not on the same page, from which I couldn't draw any conclusion.

What are the points to be considered while laying out the folder structure for a J2EE web application, importantly where should the Jsps, static content should go into & why?

答:
Well, your src/main/webapp surely reminds me of a maven project. Which is good.

For the my_app/jsps I'm not sure though.
Developers usually leave their jsp in the webapp folder, or if you want to do a little bit of url-mapping, in a webapp/jsp directory.

!Warning! : You should never put a jsp file in web-inf.
Your WEB-INF should only contain xml files to configure your website.
Remember, your jsp is a webpage or part of a webpage.

You can use folders name like template, partial... whatever feels fine for you.
It should be easy to find for a stranger.
Just separate different types of contents like fullpages, templates, partial views...

Title: Java web application folder structure


问:
Do you really have to do BDD/TDD in a test first manner?
Even though I haven't been in a TDD or BDD project, or I have been in some that say they are doing TDD but are pretty far from it, these are things that I think about and really try to read as much as I can about.

Back to the question. When you're doing BDD you should write your "test" first and make it fail, right? And then implement that feature or what you call it. But if you take this to the extreme couldn't this be some kind of top-down development? You're looking at your UI and says, "I would like to have this feature/behavior here". Then you fix your UI to implement that feature and the code that supports the UI. At this point you haven't implemented any business logic or data access logic, you have just implemented your behavior. What I'm aiming at instead of writing the test first you write your UI code first. In some cases it should result in the same code for the data access and business layer, since you use your UI code to define what your business needs to support.

Of course you should complement this with tests that is used to make sure that the feature is working as it should in the feature.

Any thoughts?

答:
Yes! Otherwise, what you get is development-driven testing.

Realistically speaking, however, there are problems that are hard to approach by using "pure" TDD.  You could be more productive writing by writing some uncovered production code up front and covering it with tests later (and learning how to approach similar problems with TDD in the future). Look at this technique, which its author called rinse-and-repeat TDD for want of a better term.


问:
Algorithm to use for shop floor layout?
I ran into a classroom problem yesterday (business oriented class, not computer science) and I found it interesting from an algorithmic perspective.

The problem goes something like this:

Assume there is a shop floor with N different rooms, and you have N different departments that need to go in those rooms.  The departments and the rooms are all the same size, so any department could go in any room.  There is a known travel distance from each room to each other room.  There is also a known amount of trips necessary from one department to another (trips are counted the same regardless which room they originate from, so a trip from A to B is equivalent to a trip from B to A).  Given those inputs, determine a layout of departments into rooms which minimizes travel time.

What is the best way to approach this problem algorithmically?  Is there already a particular algorithm or class of algorithms designed to solve this type of problem?  Does this type of problem have a name in computer science?

I am not looking for you to design an algorithm to solve this, although feel free to do so if you would like.  I'm wondering if this is a problem space that has already been well defined and studied algorithmically and if so get some links to research further.  I can see a lot of different data structures and algorithms that might apply to this and I'm curious which approach would be "best".

And don't worry, you are not doing my homework for me.  This is not a homework problem per se, as this is a business course and we were simply discussing the concepts and not trying to solve the problem algorithmically.

答:
A pragmatic solution: </p>

<p>1) distribute all departments at random (put the department names in a box and pull out combining with the numbers of rooms);
2) give to all employees new shoes
3) measure the shoes consumption (outsoles and heels)after two weeks
4) put the departments whose clerks' shoes show major consumption directly nearby
5) repeat this method n times (n= the number of departments)
6) after n trials you will measure the average of shoes consumption and know which is the best distribution of departments.
But if I were in your shoes I would make this trial as a mental experience with the help of algorithms (you have just to formalize this procedure, if you are good at math you already guess how ... if not find out)  </p>

Title: Algorithm to use for shop floor layout?

Body:
A pragmatic solution:

1) distribute all departments at random (put the department names in a box and pull out combining with the numbers of rooms);
2) give to all employees new shoes
3) measure the shoes consumption (outsoles and heels)after two weeks
4) put the departments whose clerks' shoes show major consumption directly nearby
5) repeat this method n times (n= the number of departments)
6) after n trials you will measure the average of shoes consumption and know which is the best distribution of departments.
But if I were in your shoes I would make this trial as a mental experience with the help of algorithms (you have just to formalize this procedure, if you are good at math you already guess how ... if not find out)


问:
What can go wrong with composing a method name out of a string?
I have a piece of code that composes method name to call from a string parameter. I don't feel it's a good thing to do but I'm not sure what can go wrong with this.

Here is a simplified snippet of that code:

```<code>switchToFilter = function(filter){
    var filterMethod = 'switchTo' + filter;
    myObject[filterMethod]();
}
</code>```

答:
If filter is from an external source like a user you have a potential source of unintended errors, possibly a security issue depending on the contents of myobject.

The lookup occurs at runtime so you don't get the typical benefits of type checking (existence, call signature matches function signature, etc)

That being said I do use dispatch tables much like what you have in your example. They are useful in particular instances. The key is understanding what the costs (and risks) are and making sure they don't out weigh the benefits.


问:
Global constant values throughout MVC site
My MVC (.NET) has some constant values through out the site, such as the phone number, physical address, email address etc.

I'd like to store this value once, so future updates are easier for when they change their details.

To make my question simpler, I've only focused on phone number.

My question is where and how to store this number and a problem I'm facing with my decision. At the moment, I've chosen to store it in the Global.asax file as a static method, eg

```<code>public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
       //logic
    }

    public static string GetPhoneNumber()
    {
        return "012345 678 910";
    }
}
</code>```

This works very well, in my controller I can add references to this method and assign it to a ViewBag

```<code>  public ActionResult Contact()
  {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
  }
</code>```

As per many sites, the phone number will be visible at the top of every page and as such, placing it in the _Layout.cshtml is logical.

The problem I have is there is no controller (not that I know) for the _Layout.cshtml and the only way I can pass the value is to have a ViewBag.Phone set up for every view, EG

```<code>public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
        return View();
    }

    public ActionResult About()
    {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
        return View();
    }
</code>```

This is messy and smelly but I have no idea how I can improve this.

Should I be storing my global variables in a different place or is there a better approach for this as I'm sure this is a common problem.

答:
You can access global constants directly in your _Layout.cshtml file:

```<code><div class="phone">@MvcApplication.GetPhoneNumber()</div>
</code>```

However, I would move these constants into a separate file (I generally have a Constants.cs static class) so as not to add clutter to the global.asax file.

Also, I would have them as properties:

```<code>public static string PhoneNumber
{
    get { return "012345 678 910"; }
}
</code>```

rather than methods so they could be accessed anywhere like so:

```<code>Constants.PhoneNumber
</code>```

If they are likely to change often it would be better to have these values stored in a config file or database so it does not require a recompile and deployment when they need to be changed.

Body:
You can access global constants directly in your _Layout.cshtml file:

<div class="phone">@MvcApplication.GetPhoneNumber()</div>

However, I would move these constants into a separate file (I generally have a Constants.cs static class) so as not to add clutter to the global.asax file.

Also, I would have them as properties:

public static string PhoneNumber
{
    get { return "012345 678 910"; }
}

rather than methods so they could be accessed anywhere like so:

Constants.PhoneNumber

If they are likely to change often it would be better to have these values stored in a config file or database so it does not require a recompile and deployment when they need to be changed.


答:
Store the values in web.config:

```<code><appSettings>
  <add key="CompanyTelNo" value="012345 678 910" />
</appSettings>
</code>```

Then in your code, you can reference it with:

```<code>ConfigurationSettings.AppSettings["CompanyTelNo"];
</code>```

However, since that's actually deprecated, it's better to use:

```<code>ConfigurationManager.AppSettings["CompanyTelNo"]
</code>```

Title: Global constant values throughout MVC site

Body:
My MVC (.NET) has some constant values through out the site, such as the phone number, physical address, email address etc.

I'd like to store this value once, so future updates are easier for when they change their details.

To make my question simpler, I've only focused on phone number.

My question is where and how to store this number and a problem I'm facing with my decision. At the moment, I've chosen to store it in the Global.asax file as a static method, eg

```<code>public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
       //logic
    }

    public static string GetPhoneNumber()
    {
        return "012345 678 910";
    }
}
</code>```

This works very well, in my controller I can add references to this method and assign it to a ViewBag

```<code>  public ActionResult Contact()
  {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
  }
</code>```

As per many sites, the phone number will be visible at the top of every page and as such, placing it in the _Layout.cshtml is logical.

The problem I have is there is no controller (not that I know) for the _Layout.cshtml and the only way I can pass the value is to have a ViewBag.Phone set up for every view, EG

```<code>public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
        return View();
    }

    public ActionResult About()
    {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Phone = MvcApplication.GetPhoneNumber();
        return View();
    }
</code>```

This is messy and smelly but I have no idea how I can improve this.

Should I be storing my global variables in a different place or is there a better approach for this as I'm sure this is a common problem.

Body:
Store the values in web.config:

<appSettings>
  <add key="CompanyTelNo" value="012345 678 910" />
</appSettings>

Then in your code, you can reference it with:

ConfigurationSettings.AppSettings["CompanyTelNo"];

However, since that's actually deprecated, it's better to use:

ConfigurationManager.AppSettings["CompanyTelNo"]


答:
Making the CreateBookCommandValidator public does not violate encapsulation, since

Encapsulation is used to hide the values or state of a structured data
  object inside a class, preventing unauthorized parties direct access
  to them (wikipedia)

Your CreateBookCommandValidator doesn't allow access to its data members (it currently doesn't seem to have any) so its not violating encapsulation.

Making this class public does not violate any other principle (such as the SOLID principles), because:

That class has a single well defined responsibility and therefore follows the Single Responsibility Principle.

Adding new validators to the system can be done without changing a single line of code and you therefore follow the Open/Closed Principle.

That IValidator<T> interface that this class implements is narrow (has only one member) and follows the Interface Segregation Principle.

Your consumers only depend on that IValidator<T> interface and therefore follow the Dependency Inversion Principle.

You can only make the CreateBookCommandValidator internal if the class isn't consumed directly from outside the library, but this hardly ever is the case, since your unit tests are an important consumer of this class (and almost every class in your system).

Although you can make the class internal and use [InternalsVisibleTo] to allow the unit test project to access your project's internals, why bother?

The most important reason to make classes internal is to prevent external parties (that you don't have control over) to take a dependency on such class, because that would prevent you from making future changing to that class without breaking anything. In other words, this only holds when you're creating a reusable library (such as a dependency injection library). As a matter of fact, Simple Injector contains internal stuff and its unit test project tests these internals.

However, if you're not creating a reusable project, this problem does not exist. It does not exist, because you can change the projects that depend on it, and the other developers in your team will have to follow your guidelines. And one simple guideline will do: Program to an abstraction; not an implementation (the Dependency Inversion Principle).

So long story short, don't make this class internal unless you are writing a reusable library.

But if you still want to make this class internal, you can still register it with Simple Injector without any problem like this:

```<code>container.RegisterManyForOpenGeneric(typeof(IValidate<>),
    AccessibilityOption.AllTypes,
    container.RegisterAll,
    typeof(IValidate<>).Assembly);
</code>```

The only thing to make sure of is that your all validators have a public constructor, even though they are internal. If you really want your types to have an internal constructor (don't really know why you would want that) you can override the Constructor Resolution Behavior.

UPDATE

Since Simple Injector v2.6, the default behavior of RegisterManyForOpenGeneric is to register both public and internal types. So supplying AccessibilityOption.AllTypes is now redundant and the following statement will register both public and internal types:

```<code>container.RegisterManyForOpenGeneric(typeof(IValidate<>),
    container.RegisterAll,
    typeof(IValidate<>).Assembly);
</code>```

Title: Can I use Dependency Injection without breaking Encapsulation?

Body:
Here is my Solution and projects:

BookStore  (solution)

BookStore.Coupler  (project)

Bootstrapper.cs

BookStore.Domain (project)

CreateBookCommandValidator.cs

CompositeValidator.cs

IValidate.cs

IValidator.cs

ICommandHandler.cs

BookStore.Infrastructure (project)

CreateBookCommandHandler.cs

ValidationCommandHandlerDecorator.cs

BookStore.Web (project)

Global.asax

BookStore.BatchProcesses (project)

Program.cs

Bootstrapper.cs:

```<code>public static class Bootstrapper.cs
{
    // I'm using SimpleInjector as my DI Container
    public static void Initialize(Container container)
    {
        container.RegisterManyForOpenGeneric(typeof(ICommandHandler<>), typeof(CreateBookCommandHandler).Assembly);
        container.RegisterDecorator(typeof(ICommandHandler<>), typeof(ValidationCommandHandlerDecorator<>));
        container.RegisterManyForOpenGeneric(typeof(IValidate<>),
            AccessibilityOption.PublicTypesOnly,
            (serviceType, implTypes) => container.RegisterAll(serviceType, implTypes),
            typeof(IValidate<>).Assembly);
        container.RegisterSingleOpenGeneric(typeof(IValidator<>), typeof(CompositeValidator<>));
    }
}
</code>```

CreateBookCommandValidator.cs

```<code>public class CreateBookCommandValidator : IValidate<CreateBookCommand>
{
    public IEnumerable<IValidationResult> Validate(CreateBookCommand book)
    {
        if (book.Author == "Evan")
        {
            yield return new ValidationResult<CreateBookCommand>("Evan cannot be the Author!", p => p.Author);
        }
        if (book.Price < 0)
        {
            yield return new ValidationResult<CreateBookCommand>("The price can not be less than zero", p => p.Price);
        }
    }
}
</code>```

CompositeValidator.cs

```<code>public class CompositeValidator<T> : IValidator<T>
{
    private readonly IEnumerable<IValidate<T>> validators;

    public CompositeValidator(IEnumerable<IValidate<T>> validators)
    {
        this.validators = validators;
    }

    public IEnumerable<IValidationResult> Validate(T instance)
    {
        var allResults = new List<IValidationResult>();

        foreach (var validator in this.validators)
        {
            var results = validator.Validate(instance);
            allResults.AddRange(results);
        }
        return allResults;
    }
}
</code>```

IValidate.cs

```<code>public interface IValidate<T>
{
    IEnumerable<IValidationResult> Validate(T instance);
}
</code>```

IValidator.cs

```<code>public interface IValidator<T>
{
    IEnumerable<IValidationResult> Validate(T instance);
}
</code>```

ICommandHandler.cs

```<code>public interface ICommandHandler<TCommand>
{
    void Handle(TCommand command);
}
</code>```

CreateBookCommandHandler.cs

```<code>public class CreateBookCommandHandler : ICommandHandler<CreateBookCommand>
{
    private readonly IBookStore _bookStore;

    public CreateBookCommandHandler(IBookStore bookStore)
    {
        _bookStore = bookStore;
    }

    public void Handle(CreateBookCommand command)
    {
        var book = new Book { Author = command.Author, Name = command.Name, Price = command.Price };
        _bookStore.SaveBook(book);
    }
}
</code>```

ValidationCommandHandlerDecorator.cs

```<code>public class ValidationCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
    private readonly ICommandHandler<TCommand> decorated;
    private readonly IValidator<TCommand> validator;

    public ValidationCommandHandlerDecorator(ICommandHandler<TCommand> decorated, IValidator<TCommand> validator)
    {
        this.decorated = decorated;
        this.validator = validator;
    }

    public void Handle(TCommand command)
    {
        var results = validator.Validate(command);

        if (!results.IsValid())
        {
            throw new ValidationException(results);
        }

        decorated.Handle(command);
    }
}
</code>```

Global.asax

```<code>// inside App_Start()
var container = new Container();
Bootstrapper.Initialize(container);
// more MVC specific bootstrapping to the container. Like wiring up controllers, filters, etc..
</code>```

Program.cs

```<code>// Pretty much the same as the Global.asax
</code>```

Sorry for the long setup to the problem, I have no better way of explaining this other than detailing my actual problem.

I don't want to make my CreateBookCommandValidator public. I would rather it be internal but if I make it internal then I will not be able to register it with my DI Container.  The reason I would like it to be internal is because the only project that should have notion of my IValidate<> implementations are in the BookStore.Domain project.  Any other project just needs to consume IValidator<> and the CompositeValidator should be resolved which will fulfill all validations.

How can I use Dependency Injection without breaking encapsulation?  Or am I going about this all wrong?

Body:
Making the CreateBookCommandValidator public does not violate encapsulation, since

Encapsulation is used to hide the values or state of a structured data
  object inside a class, preventing unauthorized parties direct access
  to them (wikipedia)

Your CreateBookCommandValidator doesn't allow access to its data members (it currently doesn't seem to have any) so its not violating encapsulation.

Making this class public does not violate any other principle (such as the SOLID principles), because:

That class has a single well defined responsibility and therefore follows the Single Responsibility Principle.

Adding new validators to the system can be done without changing a single line of code and you therefore follow the Open/Closed Principle.

That IValidator<T> interface that this class implements is narrow (has only one member) and follows the Interface Segregation Principle.

Your consumers only depend on that IValidator<T> interface and therefore follow the Dependency Inversion Principle.

You can only make the CreateBookCommandValidator internal if the class isn't consumed directly from outside the library, but this hardly ever is the case, since your unit tests are an important consumer of this class (and almost every class in your system).

Although you can make the class internal and use [InternalsVisibleTo] to allow the unit test project to access your project's internals, why bother?

The most important reason to make classes internal is to prevent external parties (that you don't have control over) to take a dependency on such class, because that would prevent you from making future changing to that class without breaking anything. In other words, this only holds when you're creating a reusable library (such as a dependency injection library). As a matter of fact, Simple Injector contains internal stuff and its unit test project tests these internals.

However, if you're not creating a reusable project, this problem does not exist. It does not exist, because you can change the projects that depend on it, and the other developers in your team will have to follow your guidelines. And one simple guideline will do: Program to an abstraction; not an implementation (the Dependency Inversion Principle).

So long story short, don't make this class internal unless you are writing a reusable library.

But if you still want to make this class internal, you can still register it with Simple Injector without any problem like this:

container.RegisterManyForOpenGeneric(typeof(IValidate<>),
    AccessibilityOption.AllTypes,
    container.RegisterAll,
    typeof(IValidate<>).Assembly);

The only thing to make sure of is that your all validators have a public constructor, even though they are internal. If you really want your types to have an internal constructor (don't really know why you would want that) you can override the Constructor Resolution Behavior.

UPDATE

Since Simple Injector v2.6, the default behavior of RegisterManyForOpenGeneric is to register both public and internal types. So supplying AccessibilityOption.AllTypes is now redundant and the following statement will register both public and internal types:

container.RegisterManyForOpenGeneric(typeof(IValidate<>),
    container.RegisterAll,
    typeof(IValidate<>).Assembly);


问:
Combination of asp.net server side + html/js/jQuery client side
While working with asp.net, I came to an approach that uses asp.net services for the data/business logic layer and html/javascript/jquery for the UI layer, because I could not reach the needed level of customization of the user interface with asp.net web controls.

While I've seen plenty of books describing usage of asp.net web controls and their integration with asp.net server side technology, and of html/js/jQuery client side web development without connection to any server side technology, I haven't seen any book dealing with combination of asp.net server side + html/js/jQuery client side.

My question is, is this approach acceptable, or have I overlooked some widespread technology which is better suited to accomplishing such tasks? My constraint is that it has to be based on asp.net/mvc server side technology, because my management urges that.

答:
Well I found out that the technology best suited for it is ASP.NET Web API, and they developed templates for Single Page Applications here

http://www.asp.net/single-page-application

it figures out that better to use angular.js then knockout.js though.


问:
What shoud MainWindow of a WPF contains
I am making a WPF application following MVVM model. I have seen some approaches for applying MVVM. I am concerned about my MainWindow.xaml. In some tutorials I have seen that MainWindow is only hosting a ContentControl, and in some first main page of the application.

I am making a wizard type application. There are multiple views with next and back buttons. There is one WelcomeView which is going to be the first view.

So my question is that what approach should I use. My window should contain a ContentControl pointing towards MainView or I copy paste all UI elements from WelcomeView to my MainWindow and get rid of WelcomeView.

Which is more suitable? What are Pros and Cons of each approach?

答:
We are using in our project MainWindow to display various messages like errors, warnings or questions.

Moreover if you're using composite application, MainWindow is divided into smaller parts. Every part contains separate part of information (View, ViewModel and Models).

This approach is similar to Regions in PRISM.

Title: What shoud MainWindow of a WPF contains


答:
I work in a .NET shop that has historically used Webforms. We're in the process of migrating our software to MVC, however I have some personal experience with the idea you're describing. I'm assuming you're using Webforms, not MVC, given that .NET MVC regularly utilizes javascript for the UI layer. If that's not the case, feel free to disregard.

The simple, straight-forward answer to your question is that the approach is definitely acceptable. However, it does come with a variety of headaches. The basic problem is that things like HTML (particularly HTML5) and Javascript/JQuery take an opposite tact from .NET Webforms when modeling a page. Javascript recognizes the fundamentally stateless nature of the web, whereas .NET Webforms tries to pretend that a given page has a state (like a Winform application would) and leverage means of disguising the stateless nature of the presentation.

In other words, using .NET Webforms on a new project is going to give you any number of headaches for more than the most basic, casual usage. On the other hand, I would wholeheartedly endorse using a .NET MVC backend with HTML/Javascript/JQuery for the UI. Those two technologies fit together quite nicely, and are designed with the stateless nature of the web in mind. Having .NET MVC for the business logic and HTML/Javascript for the front-end is pretty ideal, in my opinion.

Alternate approaches would be to use another framework entirely (such as Ruby on Rails, some form of PHP, etc.), however since you're familiar with ASP.NET, I'd say to give MVC a try. It still uses the .NET Framework and Feature set, just with a more logically conceived toolset to interact with when it comes to the web.

All of this goes out of the window if the application you are making is small-scale, such as for a company intranet servicing dozens of employees. In that case, the speed and simplicity of Webforms might be exactly what you're looking for - though you'll find that, as mentioned above, doing much in the way of consuming web methods and updating partial pages will be an onerous chore.

For variety, here's a couple of contrasting views:

Pro-MVC

Pro-Webforms

Title: Combination of asp.net server side + html/js/jQuery client side

Body:
While working with asp.net, I came to an approach that uses asp.net services for the data/business logic layer and html/javascript/jquery for the UI layer, because I could not reach the needed level of customization of the user interface with asp.net web controls.

While I've seen plenty of books describing usage of asp.net web controls and their integration with asp.net server side technology, and of html/js/jQuery client side web development without connection to any server side technology, I haven't seen any book dealing with combination of asp.net server side + html/js/jQuery client side.

My question is, is this approach acceptable, or have I overlooked some widespread technology which is better suited to accomplishing such tasks? My constraint is that it has to be based on asp.net/mvc server side technology, because my management urges that.


问:
How do you read this line of code?
Forgive me for my poor English, me and my friend were doing school homework, suddenly he asked me to read this line of code ptr = &array[1][1][1] (ptr is a pointer to an integer).

He said

ptr is pointing to the address of the second element of the second
  column of the second row of an array.

I think he will be right if it was an array of char. As far as it's an integer 3D array I have no idea how to read that line of code in plain English.

How would you read it?

答:
If you have a threedimensional array, then rows and colums doesn't apply, so I would say something like:

The variable ptr is assigned the address of the second item in the third dimension of the second item in the second dimension of the second item in the first dimension of the array.

Title: How do you read this line of code?


答:
If you have 3 indexes, then it must be a three dimensional array. Since C only supports jagged arrays, a multidimensional array is simulated by a three-level jagged array. In other programming languages (like C#) a multidimensional array is one object having several dimensions. In order to access one element of the array you need as many indexes as there are dimensions.

A jagged array is effectively an array of arrays of arrays. It is a construction made up of many array objects linked together in a tree like manner. Since the top level array of a dynamically allocated array can contain references to other arrays of different lengths, it is called jagged array or ragged array. A statically allocated array is always rectangular. Example: Access an element in a 3-level jagged array:

```<code>int x = a[2][0][4];
</code>```

Now, your expression is preceded by an & which means "address of" when used as unary operator. (Don't confuse with the binary & operator which is the binary AND operator.)

The expression a[2][0][4] points to (or is the address of) an element of the array of the array of the array. Therefore &a[2][0][4] is a pointer to this address. It is common to think of two dimensional arrays as of rows and columns. Now each element in this row/column is again an array. Therefore you have a pointer to the address of an element of a column of a row of an array. In my example this is the fifth element of the first column of the third row. Arrays indexes are zero-based, therefore a[0] points to the first element.

"Pointer" is a high level term used in C, where as "address" is a low level term referring to the implementation. But both denote references to memory locations.

Title: How do you read this line of code?

Body:
Forgive me for my poor English, me and my friend were doing school homework, suddenly he asked me to read this line of code ptr = &array[1][1][1] (ptr is a pointer to an integer).

He said

ptr is pointing to the address of the second element of the second
  column of the second row of an array.

I think he will be right if it was an array of char. As far as it's an integer 3D array I have no idea how to read that line of code in plain English.

How would you read it?

Body:
If you have 3 indexes, then it must be a three dimensional array. Since C only supports jagged arrays, a multidimensional array is simulated by a three-level jagged array. In other programming languages (like C#) a multidimensional array is one object having several dimensions. In order to access one element of the array you need as many indexes as there are dimensions.

A jagged array is effectively an array of arrays of arrays. It is a construction made up of many array objects linked together in a tree like manner. Since the top level array of a dynamically allocated array can contain references to other arrays of different lengths, it is called jagged array or ragged array. A statically allocated array is always rectangular. Example: Access an element in a 3-level jagged array:

int x = a[2][0][4];

Now, your expression is preceded by an & which means "address of" when used as unary operator. (Don't confuse with the binary & operator which is the binary AND operator.)

The expression a[2][0][4] points to (or is the address of) an element of the array of the array of the array. Therefore &a[2][0][4] is a pointer to this address. It is common to think of two dimensional arrays as of rows and columns. Now each element in this row/column is again an array. Therefore you have a pointer to the address of an element of a column of a row of an array. In my example this is the fifth element of the first column of the third row. Arrays indexes are zero-based, therefore a[0] points to the first element.

"Pointer" is a high level term used in C, where as "address" is a low level term referring to the implementation. But both denote references to memory locations.


问:
Inheritance with Entity Framework Code First
I'm starting work on a new personal project and I'm looking to get advice in regards to setting up my classes.

My base class is a User. The User class will have the following general properties

User ID

User Name

Password

Address (this will be a complex/value type)

I will then have a Subscriber class which is a User who has chosen to subscribe to a plan that I offer. The Subscriber class will have its own properties in addition to that of the User including:

Subscriber ID

Plan ID

Date Subscribed

etc

Is inheritance the way to go here with User being the base class or is a foreign key from the Subscriber to User class the better way? If inheritance is preferred then which method? TPH or TPT?

The plan is to have other classes with the User class acting as the base including Participants and Volunteers.

Thanks!

答:
My first thought, along the lines of 'prefer composition to inheritance', is that inheritance isn't needed (nor the best representation of the common 'subscriber' system), and that your User class should have a collection of Subscriptions.

The Subscriptions would be basically the same as you've described them, but without the inheritance piece. A particular Plan's 'Subscribers' would be the collection of Users that have a Subscription to the Plan.

Likewise with Participants and Volunteers.


答:
Let's assume we have a 2d-array like (for simplicity sake, the process for higher dimensionality is the same)

```<code>int array[3][3];
</code>```

The array viewed in memory is one dimensional, but logically we can think of it like this

```<code>array
----------------------------
| [0][0] | [0][1] | [0][2] |
----------------------------
| [1][0] | [1][1] | [1][2] |
----------------------------
| [2][0] | [2][1] | [2][2] |
----------------------------
</code>```

When you call array[1][1], you are retrieving the value at that location (which I chose below to be 12)

```<code>----------------------------
|   0    |   0    |   0    |
----------------------------
|   0    |   12   |   0    |
----------------------------
|   0    |   0    |   0    |
----------------------------
</code>```

This would allow us to construct code like the following

```<code>int value = array[1][1];
std::cout << value << std::endl;
</code>```

Output

```<code>12
</code>```

When you call &array[1][1], you are retrieving the pointer to that location

The following code would retrieve the pointer to the "center" of the array

```<code>int* ptr = &array[1][1];
(*ptr) = 10;
</code>```

Which would change the value in that location to 10.  This would result in the array to look like

```<code>----------------------------
|   0    |   0    |   0    |
----------------------------
|   0    |   10   |   0    |
----------------------------
|   0    |   0    |   0    |
----------------------------
</code>```

Basically, the process for interpreting ptr = &array[1][1][1] is the same, but you are dealing with an array of higher dimensionality.

It is the pointer to the second element of the array in each dimension.  Your teacher would've been correct if your code said ptr = &array[0][0][0]

Title: How do you read this line of code?

Body:
Let's assume we have a 2d-array like (for simplicity sake, the process for higher dimensionality is the same)

int array[3][3];

The array viewed in memory is one dimensional, but logically we can think of it like this

array
----------------------------
| [0][0] | [0][1] | [0][2] |
----------------------------
| [1][0] | [1][1] | [1][2] |
----------------------------
| [2][0] | [2][1] | [2][2] |
----------------------------

When you call array[1][1], you are retrieving the value at that location (which I chose below to be 12)

----------------------------
|   0    |   0    |   0    |
----------------------------
|   0    |   12   |   0    |
----------------------------
|   0    |   0    |   0    |
----------------------------

This would allow us to construct code like the following

int value = array[1][1];
std::cout << value << std::endl;

Output

12

When you call &array[1][1], you are retrieving the pointer to that location

The following code would retrieve the pointer to the "center" of the array

int* ptr = &array[1][1];
(*ptr) = 10;

Which would change the value in that location to 10.  This would result in the array to look like

----------------------------
|   0    |   0    |   0    |
----------------------------
|   0    |   10   |   0    |
----------------------------
|   0    |   0    |   0    |
----------------------------

Basically, the process for interpreting ptr = &array[1][1][1] is the same, but you are dealing with an array of higher dimensionality.

It is the pointer to the second element of the array in each dimension.  Your teacher would've been correct if your code said ptr = &array[0][0][0]


问:
Should I merge from the same branch or from a merge?
Kind of a best practices question: is it better to merge directly from the source to other branches or is it OK to merge from a merge?

Using Subversion for source control.

Scenario:

Branch A has changes made and committed.

Branch B and the Trunk both need updates.

Case 1

Merge from A to B and again from A to Trunk.

or

Case 2

Merge from A to B and then merge from B to Trunk.

I may also be missing a Case 3 where you merge to B and Trunk Simultaneously (not sure if that is dependent on the source control being used?).

Note that there could be any number of branches that need merging to, such that you could "cascade" the merge (A to B to C to D...).

答:
As a preface, I strongly recommend reading Advanced SCM Branching Strategies by Stephen Vance.  Much of this answer is based upon the model set up in that paper.

A key feature to branching and merging correctly in a version control system is keeping the roles of the branches consistent and separate.  Do not let your maintenance merge into your mainline, nor your feature flow into the maintenance.

The basic roles of branches are mainline, development, maintenance, accumulation, and packaging.  While sometimes these can be combined (for example, the simple 'everything in trunk one developer setup'), when working in groups and more complex environments, a clear separation of roles is often needed.

You've got two feature branches... A and B.  Each feature branch should be branched from the mainline.  Likewise, each bug fix should be branched from the mainline.

The main programming (reason for the branch) isn't done, but a bug fix needs to be copied across multiple branches and trunk

In this case, feature branch A also contains a bug fix, and part of branch A needs to get merged through the system.

The best practice would have been to branch from mainline, do the maintenance (bug fix) and merge that into the mainline, and then pick up the changes from mainline into the various branches that need it as necessary.

I'm going to assume that the mainline as a policy of "only working code."  One shouldn't break the build from the mainline.  Likewise, non-working code in mainline means that any branches from that point start out broken.

To resolve what is the case here, the best approach would be to create another branch - an accumulation branch.  This keeps any branches done from mainline while the verification of the bug fix in the accumulation branch from being broken.  To do this:

branch mainline to an accumulation branch

merge the bug fix from branch A into the accumulation branch

merge the accumulation branch back into main

propagate the fixes in mainline back to the other branches

The key for a separate branch is to in effect make a maintenance branch that only contains the bug fix, and go from there.  This lets you make sure that the branch is done correctly without breaking the mainline and make any additional tweaks for making sure that the bug fix doesn't break anything else.


问:
Ordering menu items fed from multiple modules.
I have a main application that can load modules (or plugins). Each modules can define one or more links (or items) that will be displayed in a side menu defined in the main application.

Right now, my main application execute a list of ItemProviders which are loaded from the modules. These ItemProviders return a list of items to display in the side menu.

My question now is how am I supposed to order these items since they are not aware their siblings in the menu? Keep in mind that there is not a particular logic in the order, it depends on what the client wants.

My primary solution was to give them an order number (an index). The problem with this approach is that my modules would no longer be completely independent, the "order number" would depend on other modules' number.

What would be the proper way to handle this particular case?

答:
If the user is aware that these menu items are provided by multiple plug-ins, I would either give each plug-in a sub-menu to fill, or put separators in the menu to separate the entries of the different plug-ins.

Within the set of entries from one plug-in, the plug-in would be responsible for ordering the menu items.


答:
Use Reference To Application Menu

The main application has a set of menus for the side menu already. For each menu item associate a human readable key-id for each item. You can then use this key-id later in modules to reference where new menu items should be positioned.

When loading modules their menu items can have an optional parameter called after that indicates which menu item from the main application it should appear under.

If the key-id in the application does not exist. You can append the menu item to the bottom of the sidebar.

You can still use an order numeric value to sort menu items, but respect the after parameter first.

Data might look like this grouped by title and order.

```<code> Application Menu
      "File", 0
      "Edit", 1
      "View", 2
      "Tools", 3
</code>```

A module could have a menu defined like this.

```<code> Module Menu
      after:"File"
         "Window", 0
         "Help", 1
      after:"Tools"
         "Features",0
         "Navigate",1
         "Program",2
</code>```

You could have other parameters like insert or child for submenus. The key is to use a human readable reference point back to the main application's menu. This makes extending the menu easy.

Title: Ordering menu items fed from multiple modules.

Body:
I have a main application that can load modules (or plugins). Each modules can define one or more links (or items) that will be displayed in a side menu defined in the main application.

Right now, my main application execute a list of ItemProviders which are loaded from the modules. These ItemProviders return a list of items to display in the side menu.

My question now is how am I supposed to order these items since they are not aware their siblings in the menu? Keep in mind that there is not a particular logic in the order, it depends on what the client wants.

My primary solution was to give them an order number (an index). The problem with this approach is that my modules would no longer be completely independent, the "order number" would depend on other modules' number.

What would be the proper way to handle this particular case?

Body:
Use Reference To Application Menu

The main application has a set of menus for the side menu already. For each menu item associate a human readable key-id for each item. You can then use this key-id later in modules to reference where new menu items should be positioned.

When loading modules their menu items can have an optional parameter called after that indicates which menu item from the main application it should appear under.

If the key-id in the application does not exist. You can append the menu item to the bottom of the sidebar.

You can still use an order numeric value to sort menu items, but respect the after parameter first.

Data might look like this grouped by title and order.

 Application Menu
      "File", 0
      "Edit", 1
      "View", 2
      "Tools", 3

A module could have a menu defined like this.

 Module Menu
      after:"File"
         "Window", 0
         "Help", 1
      after:"Tools"
         "Features",0
         "Navigate",1
         "Program",2

You could have other parameters like insert or child for submenus. The key is to use a human readable reference point back to the main application's menu. This makes extending the menu easy.


问:
Preferring Database Normalization vs. Schema Transparency?
A new requirement has surfaced on an old codebase, that basically enables direct (internal) communication between two formerly not-directly related classes of users (stored in different tables with completely different schema and, sadly, the code is barely OO-aware, much less designed, so there's no parent class).  Since we're out to hang a bag on this old setup that never considered this functionality, there's no guarantee that there are no PK collisions -- given the dataset in use, it's practically guaranteed that there ARE.

So, the solution seems obvious: kill it with fire and rewrite the whole mess A mapping table. I've gotten two directions for the possible ways to implement the map, but I'm not a DBA, so I'm uncertain if there are any pros and cons I've missed.

For the sake of clarifying the abstraction, consider three groups of disparate user data: Professors, Administration, Students (No, this isn't a homework assignment. Promise!)

Mapping 1

(professor_id, admin_id, and student_id are foreign keys to their respective tables)

```<code>| mailing_id (KEY) | professor_id | admin_id | student_id |
-------------------------------------------------------
| 1001             |     NULL     |    87    |  NULL      |
| 1002             |     123      |   NULL   |  NULL      |
| 1003             |     NULL     |   NULL   |  123       |
</code>```

The +/- to this approach seem pretty heavy on the cons:

Two "wasted" fields per row

Violates 2NF

Vulnerable to insert/update anomalies (a row with only 0-1 field set NULL, e.g.)

The pros are not without their own merits, though:

The mapping can be accomplished with a single lookup

Easily determine the "source" data for a given user from the mailing_id

Truth be told, in my gut, I don't like this idea at all.

Mapping 2

(assume MSG_* are defined constants, enum types, or another suitable identifier)

```<code>| mailing_id (KEY)  | user_type (UNIQUE1) | internal_id (UNIQUE2)|
------------------------------------------------------------------
| 1001              | MSG_ADMIN          | 87                    |
| 1002              | MSG_PROF           | 123                   |
| 1003              | MSG_STUDENT        | 123                   |
</code>```

With this setup, and a unique composite index of {user_type, internal_id} things become much cleaner, 3NF is maintained, and the application code doesn't have to check for I/U anomalies.

On the downside, there's a bit of a loss of transparency in determining the user source tables that has to be handled outside of the DB, basically amounting to an application-level mapping of user_type values to tables. Right now, I'm (rather strongly) leaning toward this 2nd mapping, since the downside is rather minor.

BUT I'm painfully aware of my own limitations, and am sure I've probably missed advantages or stumbling blocks in both directions, so I turn to wiser minds than mine.

答:
From experience my recommendation is to choose consistency over elegance or 'best practice'.  That is to match the existing design and go with THREE mailing tables (one for each role) with a simple mailing_id, user_id field structure.

It's inelegant but it has a few advantages...

Matching the existing structure will be easier for anyone
else who will work on this schema before it's put out to pasture.

You have no wasted fields and you're not asking the db to match up things
that won't exist.

Because each table will only to one other and it'll be relatively easy to make
a view which ties up all the data for your routines to use.

I'm sure many others will disagree with this approach, but primary aims of normalisation and best practices are to make code more consistent so it's easier to follow and debug...  and obviously bringing the whole codebase up to scratch is probably not feasible.


答:
either you are enabling dependent behavior, or you are micromanaging; it's hard to say which from the description

so let's find out!

talk to your manager about the situation, and then take a vacation; ask your manager to make sure that Chris has a new assignment while you're gone, and that no one is 'available' to help him/her.

Then see if Chris gets anything done without you.

if he/she does, then you don't need to help any more - problem solved

if not, then your company doesn't need Chris (at least at his/her current level of training/ability) - and your manager will not be able to ignore that fact

Title: Coworker that detrimentally picks on every minutia

Body:
Hypothetically speaking imagine that there exists a coworker that has a very shallow understanding of computing. To avoid stereotyping lets give this coworker the gender neutral name Chris.

Now Chris' diagnostic ability is low and can't figure out the correct IP addresses to set his/her virtual machines to. Chris also fails to merge code properly and overwrites a commit I made fixing something, thereby re-introducing a bug. I let this slide, refix the bug and do not make a sound about it to management.

Given a task Chris either 1) complains that there isn't sufficient information resulting in 2) you provide Chris with inordinately detailed instructions to satisfy 1). The more detail you provide in a list of steps to carry out, the more chance of an error being present in your instructions. Chris gets these instructions, tries to execute them, fails and it becomes your fault because your instructions aren't good enough. How do you deal with this?


问:
Loose coupling and shuffling dependencies
I have a bunch of classes that look something like this:

```<code>public class MyGame()
{
    private Graphics graphics;

    private Player player;

    public MyGame()
    {
        graphics = new Graphics();
        //...
    }

    protected void Initialize()
    {
        player = new Player();
        //...
    }

    protected void Update()
    {
        player.DoStuff();
        //...
    }
</code>```

I've been reading about design patterns, and I've come to understand that this is not a very good design because it isn't loosely coupled. Instead of coding to interfaces, I'm coding to implementations (Graphics, Player, etc.).

In order to fix this perceived problem, I start by changing those dependencies to interfaces:

```<code>public class MyGame()
{
    private IGraphics graphics;

    private IPlayer player;

    public MyGame()
    {
        graphics = new Graphics();
        //...
    }

    protected void Initialize()
    {
        player = new Player();
        //...
    }
</code>```

I'm not sure how helpful that really is, but it's nice that the graphics field (for example) isn't tied to the Graphics class - I can use the AwesomeGraphics class or SparklyGraphics class instead as long as those classes implement IGraphics.

But I still have hard dependencies on Graphics and Player, so what was the point of all that refactoring? (My actual code is much more complicated.) I've also come to understand that dependency injection is a good idea, so that's what I try to do next:

```<code>public class MyGame()
{
    private IGraphics graphics;

    private IPlayer player;

    public MyGame( IGraphics graphics, IPlayer player )
    {
        this.graphics = graphics;
        this.player = player;
        //...
    }
</code>```

This looks really nice because I no longer have any hard dependencies in MyGame. However, the dependencies are still in my code - they've just been moved to the class that instantiates MyGame:

```<code>static class Program
{
    static void Main( string[] args )
    {
        using ( var game = new Game( new Graphics(), new Player() )
        {
            game.Run();
        }
    }
}
</code>```

Now I'm back where I started! This class is not loosely coupled at all! So, again, what was the point of all that refactoring? I'm pretty sure I could use an IoC container to take care of these dependencies somehow, but that would likely just add a ton of complication to an already complicated project. Plus, wouldn't that just be moving those dependencies once again to another class?

Should I stick with what I had in the first place, or is there some tangible benefit that I'm not seeing yet?

答: You have gained the benefits of loose coupling in your refactoring.  You've moved the knowledge of the precise implementation outside of your MyGame class and into a higher-level class.  This is good: by keeping all knowledge of what the precise implementations are together, you're improving the structure of your code, making it easier for high level changes to take place, and making it easier to make changes that involve, for example, using multiple implementations of your Player class (perhaps by introducing a NetworkPlayer or AIPlayer later).  MyGame now has one fewer reason to change, so is closer to having a single responsibility, and the Single Responsibility Principle is now considered one of the most important in object-oriented design by many programmers.


答:
Eventually, all code has to depend on a concrete implementation, whether that's specified in code or some sort of DI framework configuration file.  The benefit of depending on an interface is that you can more easily depend on multiple concrete implementations, as the situation calls for.

However, those benefits aren't actually realized until you actually have multiple concrete implementations.  Most frequently, the second concrete implementation is a mock object used in unit testing.  It could also be things like multiple target platforms.  For example, I have a project that depends on interfaces for the UI so I can substitute concrete implementations for either Swing or Android.  It's common to have interfaces for multiple databases or operating system-specific functionality.

If you don't ever have that second implementation, you aren't actually receiving any tangible benefit.  You just have a future assurance that if you ever need a second implementation, it will be easier to integrate.  It's like owning non-dividend stock.  It's worth something on paper, but you don't get any real benefit until you actually sell it.

Title: Loose coupling and shuffling dependencies

Body:
I have a bunch of classes that look something like this:

```<code>public class MyGame()
{
    private Graphics graphics;

    private Player player;

    public MyGame()
    {
        graphics = new Graphics();
        //...
    }

    protected void Initialize()
    {
        player = new Player();
        //...
    }

    protected void Update()
    {
        player.DoStuff();
        //...
    }
</code>```

I've been reading about design patterns, and I've come to understand that this is not a very good design because it isn't loosely coupled. Instead of coding to interfaces, I'm coding to implementations (Graphics, Player, etc.).

In order to fix this perceived problem, I start by changing those dependencies to interfaces:

```<code>public class MyGame()
{
    private IGraphics graphics;

    private IPlayer player;

    public MyGame()
    {
        graphics = new Graphics();
        //...
    }

    protected void Initialize()
    {
        player = new Player();
        //...
    }
</code>```

I'm not sure how helpful that really is, but it's nice that the graphics field (for example) isn't tied to the Graphics class - I can use the AwesomeGraphics class or SparklyGraphics class instead as long as those classes implement IGraphics.

But I still have hard dependencies on Graphics and Player, so what was the point of all that refactoring? (My actual code is much more complicated.) I've also come to understand that dependency injection is a good idea, so that's what I try to do next:

```<code>public class MyGame()
{
    private IGraphics graphics;

    private IPlayer player;

    public MyGame( IGraphics graphics, IPlayer player )
    {
        this.graphics = graphics;
        this.player = player;
        //...
    }
</code>```

This looks really nice because I no longer have any hard dependencies in MyGame. However, the dependencies are still in my code - they've just been moved to the class that instantiates MyGame:

```<code>static class Program
{
    static void Main( string[] args )
    {
        using ( var game = new Game( new Graphics(), new Player() )
        {
            game.Run();
        }
    }
}
</code>```

Now I'm back where I started! This class is not loosely coupled at all! So, again, what was the point of all that refactoring? I'm pretty sure I could use an IoC container to take care of these dependencies somehow, but that would likely just add a ton of complication to an already complicated project. Plus, wouldn't that just be moving those dependencies once again to another class?

Should I stick with what I had in the first place, or is there some tangible benefit that I'm not seeing yet?


答:
In this example:

```<code>public MyGame( IGraphics graphics, IPlayer player )
</code>```

the statement:

However, the dependencies are still in my code

is not correct.  The are no dependencies because now the class is tied to a contract and not an implementation.

In some cases it is not necessary to be loosely coupled.  For example, the player class may not be a good candidate to be loosely coupled if it just contains properties or core logic.

Let's take a look at a better example, let's say your game uses a 3rd party ranking engine to rank players.

So your constructor may look like this:

```<code>public MyGame( IRankingProvider Provider )
</code>```

Now you can swap out different implementations of a ranking provider rather easily, your code may have 3 or 4 implementations depending on what platform the game is running on.

Also, for unit testing you can create a fake Provider to unit test the logic on MyGame without any external ranking provider dependencies.  This makes it easy to run all the unit tests on a development/build machine without installing/setting up any of the providers.

Now eventually on a development/deployment server one would want to perform integration tests using actual providers to ensure the implementation are correct, in those cases the test fixture would inject a real implementation.

So, the main benefits are:

Increased testability

Ability to switch out implementations or use multiple implementations

Removal of dependencies

One should choose carefully which parts of the system are loosely coupled.   In some cases it is not needed and when employed causes a needless layer of abstraction.

Body:
In this example:

public MyGame( IGraphics graphics, IPlayer player )

the statement:

However, the dependencies are still in my code

is not correct.  The are no dependencies because now the class is tied to a contract and not an implementation.

In some cases it is not necessary to be loosely coupled.  For example, the player class may not be a good candidate to be loosely coupled if it just contains properties or core logic.

Let's take a look at a better example, let's say your game uses a 3rd party ranking engine to rank players.

So your constructor may look like this:

public MyGame( IRankingProvider Provider )

Now you can swap out different implementations of a ranking provider rather easily, your code may have 3 or 4 implementations depending on what platform the game is running on.

Also, for unit testing you can create a fake Provider to unit test the logic on MyGame without any external ranking provider dependencies.  This makes it easy to run all the unit tests on a development/build machine without installing/setting up any of the providers.

Now eventually on a development/deployment server one would want to perform integration tests using actual providers to ensure the implementation are correct, in those cases the test fixture would inject a real implementation.

So, the main benefits are:

Increased testability

Ability to switch out implementations or use multiple implementations

Removal of dependencies

One should choose carefully which parts of the system are loosely coupled.   In some cases it is not needed and when employed causes a needless layer of abstraction.


答:
At the program level, there will always be a point at which a decision needs to be made which concrete implementations of IGraphics and IPlayer will be given to Game. This is what you're seeing here.

The point of your work is that you've moved the decision out of Game itself, so it isn't tightly coupled to any particular implementations, and left it to your higher level program code to decide.

This means that Game is much more flexible (as are IGraphics, and IPlayer), and your program is now made up of freely composable units instead of one inflexible hierarchical unit.

It may not seem like a big deal with such a simple contrived example, but once you get even a little bit more complex, the composability becomes much more beneficial.


问:
Fully Stable, In-Place Unique Algorithm in O(n)
Is there an algorithm that, given a sorted array, swaps all the first unique elements to the beginning of the array and the duplicates to the end, while remaining stable for both the unique subarray and the duplicate subarray, and that runs in O(n) swaps (and preferably one pass)? It should return the length of the unique portion of the array.

Contrived example input/result (Using python because it's easy to read):

```<code>>>> A = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]   # already sorted
>>> r = Unique(A)
>>> r
5
>>> A
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
>>> A[:r] # the sorted portion
[1, 2, 3, 4, 5]
>>> A[r:] # the duplicates portion
[1, 2, 3, 4, 5]
</code>```

Stability means that even if two or more keys compare equal, the ordering of the keys in the result persists. E.g. if A[i] == A[j] == A[k] and i < j < k in the original array, all of those properties hold in the whole array after running the Unique algorithm. (Even though A[i] might be in the unique subarray and both A[j] & A[k] are in the duplicates subarray.)

My failed attempt is a one-pass that tracks the current unique element while iterating through the array. The next unique element is swapped with the element after the end of the current unique subarray:

```<code>def Unique1(A):
    if len(A) <= 1:
        return 0
    i = 0
    for j in range(1, len(A)):
        if A[i] < A[j]:
            i += 1
            if i < j:
                A[i], A[j] = A[j], A[i]
    return i + 1
</code>```

It swaps the first unique elements of a sorted array to the beginning of the array, runs in one pass (so is O(n)), and is stable for the unique subarray, but this does not satisfy the requirements because it scrambles the duplicates subarray:

```<code>>>> A = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
>>> r = Unique1(A)
>>> A[r:]          # duplicates part
[3, 2, 4, 1, 5]    # not sorted
</code>```

While the changes the algorithm makes to the unique subarray is somewhat obvious, I can't "see" what's happening to the duplicates subarray, but I have a feeling that it could be reversed if we knew or stored more information about the duplicates.

Note, just re-sorting the duplicates subarray is a non-starter because 1: it's O(n log n) not O(n) and 2: it breaks the stability.

I can also think of another algorithm that swaps newly found unique items all the way down to the next position. While it would satisfy the other conditions, it would have O(n^2) swaps.

Is such a unique algorithm possible? And if not, why not?

答:
I'm not sure, but I think you need to drop the "preferably one-pass" from your description.  You can do it in three passes by using the following algorithm:

Take a pass over the array, counting the number of unique items as unique_count

Allocate a new temporary array with size len(A) - unique_count

Take a second pass over the array, shifting each first instance of an item to the front of the array while copying the second instance to the first free space in the temporary array

Take a pass over the temporary array, copying each item to its final position in the input array

This is still O(n), albeit with somewhat higher constant factor per item than your original implementation.


答:
You certainly have gained substantial benefit from changing the structure.

When coding new systems or fairly stable systems implementing design patterns can seem like a waste of effort and time since it didn't make your life easier right now.

Consider that the Graphics object you were using originally was developed for rendering 2D graphics and does all kinds of logic under the covers to make development easier. Later on your game grows and now needs to start doing some 3D graphics, normally you would start by inheriting from Graphics, only 2D graphics while it may have some similar methods such as Render(), Refresh(), or Invalidate() has nothing to do with 3D graphics.

By opening up several SIMPLE interfaces for Graphics you open the door to much more flexibility in your code.

As an example of the strategy pattern (dependency inversion) and coding to interfaces:

MyGame requires several things to function.

It needs our Render(), Refresh(), Invalidate(). (IGraphics)
It needs additional 3D methods such as Transform(), Rotate() . (IGraphicsManipulations3D)

And if those multiple interfaces make sense to be lumped together for something you can make a combined interface

```<code>public interface IGraphics3D : IGraphics, IGraphicsManipulations3D
</code>```

so now instead of saying you need a SPECIFIC graphics implementation you just need some object that does the basic things, you could even swap in completely different rendering engines if you wanted to.

```<code>public class UnityEngineGraphics : IGraphics3D
</code>```

or

```<code>public class HavokEngineGraphics : IGraphics3D
</code>```

But your game doesn't care one bit.

```<code>public class MyGame(IGraphics3D, IPlayer)
</code>```

The important thing to note and most likely where you find it difficult to see value is that these circumstances tend to come up later rather than sooner and when you are building the MyGame you are fully intent on using one implementation of the graphics object. Never forget that requirements change, sometimes for good, sometimes for headaches and design patterns are THE way to be preemptive.

Body:
You certainly have gained substantial benefit from changing the structure.

When coding new systems or fairly stable systems implementing design patterns can seem like a waste of effort and time since it didn't make your life easier right now.

Consider that the Graphics object you were using originally was developed for rendering 2D graphics and does all kinds of logic under the covers to make development easier. Later on your game grows and now needs to start doing some 3D graphics, normally you would start by inheriting from Graphics, only 2D graphics while it may have some similar methods such as Render(), Refresh(), or Invalidate() has nothing to do with 3D graphics.

By opening up several SIMPLE interfaces for Graphics you open the door to much more flexibility in your code.

As an example of the strategy pattern (dependency inversion) and coding to interfaces:

MyGame requires several things to function.

It needs our Render(), Refresh(), Invalidate(). (IGraphics)
It needs additional 3D methods such as Transform(), Rotate() . (IGraphicsManipulations3D)

And if those multiple interfaces make sense to be lumped together for something you can make a combined interface

public interface IGraphics3D : IGraphics, IGraphicsManipulations3D

so now instead of saying you need a SPECIFIC graphics implementation you just need some object that does the basic things, you could even swap in completely different rendering engines if you wanted to.

public class UnityEngineGraphics : IGraphics3D

or

public class HavokEngineGraphics : IGraphics3D

But your game doesn't care one bit.

public class MyGame(IGraphics3D, IPlayer)

The important thing to note and most likely where you find it difficult to see value is that these circumstances tend to come up later rather than sooner and when you are building the MyGame you are fully intent on using one implementation of the graphics object. Never forget that requirements change, sometimes for good, sometimes for headaches and design patterns are THE way to be preemptive.


问:
Is it worth using VCS (Version Control Softwares) for hobbystic/small/personal projects?
The question is fairly self-explainatory.

Is it worth using VCS (Version Control Softwares) for hobbystic/small/personal projects?

答:
Yes. You don't know when a project will become something much bigger or when you'll want to go back in time. Also, it's good practice.

On the other hand if you are just doing very small things, like tutorials or things you doubt you will be using a week from now, I say "why bother?".


答:
Yes, it is worth using a Version Control System/Software Configuration Management system such as CVS, git, mercurial, subversion, etc.  If you don't use a true version control system, you'll probably end up creating your own ad-hoc system with folders or zip files, and it won't be nearly as capable, efficient, or as easy to use as a commercial or open-source version control system.

You originally mentioned CVS, but that may not be the best fit.  It's old and it's designed to be installed on a central server (though you can just install it locally).  Although it has branching and tagging and merging, it doesn't always do a good job.  You would probably be better served by a modern distributed version control system like git or mercurial.  And although you can technically use any version control system, you can work a lot more smoothly if you choose one that is well-supported by the other tools in your toolchain.

Body:
The question is fairly self-explainatory.

Is it worth using VCS (Version Control Softwares) for hobbystic/small/personal projects?


答:
No, you probably shouldn't be using CVS, as the world has moved on and that software isn't being maintained any longer.

You might want to look into newer version control systems like Subversion (fairly similar to CVS, as both are centralized) or Git (distributed, feels more lightweight, but has a long learning curve). I personally use Git for any project that has it's own folder, no matter how small: Creating a new repo is an incredibly cheap and easy operation and has no real downsides.

Title: Is it worth using VCS (Version Control Softwares) for hobbystic/small/personal projects?


问:
How bad can it be to lack teamwork when you are a programmer?
I'm still at school, and I know I have problems dealing with other people.

I'm not an angry or shy or different, I just like to work my way and with my opinions while respecting other's, I have a big curiosity and hunger for knowledge, but I lack practice and I guess people don't want to work with me because they might fear I would talk some kind of morale. (For example I started to learn programming using linux instead of windows, even if I use windows a lot. And I have a mac).

What happens to programmers who lack teamwork? Where does the problems begin? Does being a good programmer compensate at least a little? Is it normal for a programmer to have a vision about his work instead of just doing what he is told?

答:
What happens to programmers who lack teamwork?

Then it becomes difficult to work on projects that are too large for a single programmer. Difficult for the solo programmer, and difficult for the rest of the team.

Where does the problems begin?

All sorts of places. We currently have a single programmer who is bad at working as part of a team. He tends to make short cuts that have bad effects on the rest of the application because he is too narrowly focused on fixing the bug in front of him. Or writing the new feature in such a way that it isn't compatible with the rest of the application. We have to rearrange things so that every code check-in of his is reviewed by the rest of the team. But in order not to single him out, we also review everyone else's code check ins, so along with the morning status meeting, we get no work done until after lunch. So at our office, this means that 4 people are losing a 1/2 day of work each and every day because one guy is lousy at team work. I can't say it is an improvement over the previous adventures, because we could randomly lose a day to a week (usually chasing new bugs) from his check-ins that break things (we call those "robstacles"). Some of the fixes to his code will end up clearing a half dozen bugs because of how tangled and messy the application is (my recommendation to nuke it from orbit, and start over again because that's the only way to be sure was not accepted).

When we are in a generous mood, we call him a "head down programmer" has he tends to look down at the keyboard and type real fast. He doesn't pay attention to what others are doing.

Does being a good programmer compensate at least a little?

No. Most programmers who are bad team players have a very high opinion of their own skills, and this is called the Dunning-Kruger effect. PDF of paper.

Maybe: the solo programmer would need to be far better than the rest of the team. But this just means that no one else can maintain what he does; and when that happens, it probably means that the solo programmer is not actually far better than the rest of the team - he (and it is almost always a guy) is just better at fooling everyone.

In business software development, the company will be around long after you leave. Programs were most likely written before you started, and will be maintained long after you are gone. If you write things that are so special and amazing that no one else can understand them, then you end up in the situation that Naughty Dog is in - their lead developer quit, no one else understands the proprietary programming language the guy wrote (and wrote things in), so they are now having to switch everything to C++.

Is it normal for a programmer to have a vision about his work instead of just doing what he is told?

It is common - like a traffic jam or diabetes. I would not call it normal. In the corporate world, there are lots of other things to consider; the strong ego that many developers have typically makes the developer think that nothing else matters. This "lack of fit" and lack of consideration for the rest of the business is why so many manager-types come to the conclusion that software developers are hard to work with.


答:
Yes, it's worth using, but for different reasons than are typical on large shared projects:

You might have long gaps where you don't work on a personal project.  Having the history makes it easier to see where you left off.

It makes it easier to experiment and get back to a known good point if it doesn't work.  On personal projects I do this much more often than at work, where I usually don't have the luxury of spending time on a concept that doesn't work.

It makes it easy to sync between different environments, say a laptop and a desktop.

You can easily get a bitbucket account or similar and have a backup of all your work, together with an issue tracker that helps you keep track of what you wanted to do next.

It makes it easier to answer questions like, "Have I really removed all the debug code I don't need anymore?" or "What have I changed since this part last worked?"