答:
In almost ten years of PHP, I haven't found a single advantage in any template engine I've worked with over the "WordPress" style.

Allowing the controller to determine which templates are referenced, and allowing the view to directly reference sub-templates, is direct, concise, and maintainable.

The only secondary suggestion I have is that the developer should be able to specify the theme that the template originates from in some sort of general config. This prevents the developer from having to globally find/replace the theme name in the controllers and subtemplate references.

Title: Effective template system

Body:
I'm building a content management system, and need advice on which theming structure should I adopt. A few options (This is not a complete list):

Wordpress style:

the controller decides what template to load based on the user request, like: home page / article archive / single article page etc.

each of these templates are unrelated to other templates, and must exist within the theme

the theme developer decides if (s)he want to use inner-templates (like "sidebar", "sidebar item"), and includes them manually where (s)he thinks are needed.

Drupal style:

the controller gives control to the theme developer only to inner-templates; if they don't exist it falls back internally to some default templates (I find this very restrictive)

Funky style:

the controller only loads a "index.php" template and provides the theme developer conditional tags, which he can use to include inner-templates if (s)he wants.

Among these styles, or others what style of template system allows for fast development and a more concise design and implementation.


问:
Is there a device still being sold that requires efficient programming? What is it?
Edit: As a lot of you have pointed out, efficient can mean a lot of things. I guess when I say that the device 'requires efficient programming', I mean that the device does not have lots of memory or a very high CPU clock rate, and therefore needs to be programmed with these limitations in mind.

Original Question: Sometimes, to train themselves, athletes will work in higher altitude places to workout. This is because there is less air, meaning working out is much more difficult. Once athletes have gotten used to exercising in these conditions, they find doing physical work in normal altitude places much easier.

I want to do this same thing, except with software development, and more specifically, game development. I want to find some system with a low amount of RAM (in the kilobytes), low CPU clock speed, and few registers. I figure learning to program games on this kind of system would be very useful in teaching me to write efficient code. Also, it would be very fun :)

The systems that I have thought about programming are the old Nintendo ones; GBA, NES, SNES. But I have learned the hard way that obtaining these, then obtaining the flash cards for them are very difficult, and on the border of being illegal.

So, my question is is there a crummy device that will teach me to write efficient code that is still out there and being sold? I would like it to be a physical device, looking at my programs run on physical machines would be a lot more satisfying then watching it on an emulator, and also, emulators can be buggy.

答:
Note that the work of a developer is much more complicate than "writing efficient code" and, by the way, writing code in general, so the comparison with athletes is strange.

Now, if for some reason you should improve specifically the efficiency of your code, without carrying about anything else, then there is no reason to search for low-grade hardware devices. Take the device you used for the last years and run the code you write in a profiler, or run it hundreds of thousands of times. Chances are that a few barely noticeable milliseconds lost due to inefficient code will have a visible impact on your benchmarks when multiplied by, say, 500 000.

In the same way, you can limit yourself to low memory (RAM) footprint, even if you have access to much more memory on your device. If you write code in C, you can probably try to fix as well some size limit for the final executable.

Advantages?

You still use high-quality hardware and contemporary software to write, compile and debug code.

You can train yourself in any programming language, learning different optimization techniques. I'm pretty sure Haskell optimization would not be the same as Java optimization.

You can use professional profilers which will gather precise data for you, with the ability to analyze it statistically later, see how performance of your code decreases or increases over time, etc. Moreover, you know exactly where the bottleneck is, instead of wrongly guessing it or doing premature optimization.

You can build in one step. Less time you waste transmitting the application from your developer device to the device you test the code on means more time spent doing something useful or fun, like writing and testing code.

You can adjust the parameters on the fly. 500 000 iterations of your code are too slow? You can change it to be 250 000 iterations instead.

Play with one limitation affecting another. For example you may want to have the fastest sort algorithm but which requires more memory, or the slower algorithm with a smaller memory footprint.

ContentLicense: CC BY-SA 3.0


问:
How to make creating viewmodels at runtime less painful
I apologize for the long question, it reads a bit as a rant, but I promise it's not! I've summarized my question(s) below

In the MVC world, things are straightforward. The Model has state, the View shows the Model, and the Controller does stuff to/with the Model (basically), a controller has no state. To do stuff the Controller has some dependencies on web services, repository, the lot. When you instantiate a controller you care about supplying those dependencies, nothing else. When you execute an action (method on Controller), you use those dependencies to retrieve or update the Model or calling some other domain service. If there's any context, say like some user wants to see the details of a particular item, you pass the Id of that item as parameter to the Action. Nowhere in the Controller is there any reference to any state. So far so good.

Enter MVVM. I love WPF, I love data binding. I love frameworks that make data binding to ViewModels even easier (using Caliburn Micro a.t.m.). I feel things are less straightforward in this world though. Let's do the exercise again: the Model has state, the View shows the ViewModel, and the ViewModel does stuff to/with the Model (basically), a ViewModel does have state! (to clarify; maybe it delegates all the properties to one or more Models, but that means it must have a reference to the model one way or another, which is state in itself) To do stuff the ViewModel has some dependencies on web services, repository, the lot. When you instantiate a ViewModel you care about supplying those dependencies, but also the state. And this, ladies and gentlemen, annoys me to no end.

Whenever you need to instantiate a ProductDetailsViewModel from the ProductSearchViewModel (from which you called the ProductSearchWebService which in turn returned IEnumerable<ProductDTO>, everybody still with me?), you can do one of these things:

call new ProductDetailsViewModel(productDTO, _shoppingCartWebService /* dependcy */);, this is bad, imagine 3 more dependencies, this means the ProductSearchViewModel needs to take on those dependencies as well. Also changing the constructor is painful.

call _myInjectedProductDetailsViewModelFactory.Create().Initialize(productDTO);, the factory is just a Func, they are easily generated by most IoC frameworks. I think this is bad because Init methods are a leaky abstraction. You also can't use the readonly keyword for fields that are set in the Init method. I'm sure there are a few more reasons.

call _myInjectedProductDetailsViewModelAbstractFactory.Create(productDTO); So... this is the pattern (abstract factory) that is usually recommended for this type of problem. I though it was genius since it satisfies my craving for static typing, until I actually started using it. The amount of boilerplate code is I think too much (you know, apart from the ridiculous variable names I get use). For each ViewModel that needs runtime parameters you'll get two extra files (factory interface and implementation), and you need to type the non-runtime dependencies like 4 extra times. And each time the dependencies change, you get to change it in the factory as well. It feels like I don't even use a DI container anymore. (I think Castle Windsor has some kind of solution for this [with it's own drawbacks, correct me if I'm wrong]).

do something with anonymous types or dictionary. I like my static typing.

So, yeah. Mixing state and behavior in this way creates a problem which don't exist at all in MVC. And I feel like there currently isn't a really adequate solution for this problem. Now I'd like to observe some things:

People actually use MVVM. So they either don't care about all of the above, or they have some brilliant other solution.

I haven't found an in-depth example of MVVM with WPF. For example, the NDDD-sample project immensely helped me understand some DDD concepts. I'd really like it if someone could point me in the direction of something similar for MVVM/WPF.

Maybe I'm doing MVVM all wrong and I should turn my design upside down. Maybe I shouldn't have this problem at all. Well I know other people have asked the same question so I think I'm not the only one.

To summarize

Am I correct to conclude that having the ViewModel being an integration point for both state and behavior is the reason for some difficulties with the MVVM pattern as a whole?

Is using the abstract factory pattern the only/best way to instantiate a ViewModel in a statically typed way?

Is there something like an in depth reference implementation available?

Is having a lot of ViewModels with both state/behavior a design smell?

答:
The issue of dependencies when initiating a new view model can be handled with IOC.

```<code>public class MyCustomViewModel{
  private readonly IShoppingCartWebService _cartService;

  private readonly ITimeService _timeService;

  public ProductDTO ProductDTO { get; set; }

  public ProductDetailsViewModel(IShoppingCartWebService cartService, ITimeService timeService){
    _cartService = cartService;
    _timeService = timeService;
  }
}
</code>```

When setting up the container...

```<code>Container.Register<IShoppingCartWebService,ShoppingCartWebSerivce>().As.Singleton();
Container.Register<ITimeService,TimeService>().As.Singleton();
Container.Register<ProductDetailsViewModel>();
</code>```

When you need your view model:

```<code>var viewmodel = Container.Resolve<ProductDetailsViewModel>();
viewmodel.ProductDTO = myProductDTO;
</code>```

When utilizing a framework such as caliburn micro there is often some form of IOC container already present.

```<code>SomeCompositionView view = new SomeCompositionView();
ISomeCompositionViewModel viewModel = IoC.Get<ISomeCompositionViewModel>();
ViewModelBinder.Bind(viewModel, view, null);
</code>```

Body:
The issue of dependencies when initiating a new view model can be handled with IOC.

public class MyCustomViewModel{
  private readonly IShoppingCartWebService _cartService;

  private readonly ITimeService _timeService;

  public ProductDTO ProductDTO { get; set; }

  public ProductDetailsViewModel(IShoppingCartWebService cartService, ITimeService timeService){
    _cartService = cartService;
    _timeService = timeService;
  }
}

When setting up the container...

Container.Register<IShoppingCartWebService,ShoppingCartWebSerivce>().As.Singleton();
Container.Register<ITimeService,TimeService>().As.Singleton();
Container.Register<ProductDetailsViewModel>();

When you need your view model:

var viewmodel = Container.Resolve<ProductDetailsViewModel>();
viewmodel.ProductDTO = myProductDTO;

When utilizing a framework such as caliburn micro there is often some form of IOC container already present.

SomeCompositionView view = new SomeCompositionView();
ISomeCompositionViewModel viewModel = IoC.Get<ISomeCompositionViewModel>();
ViewModelBinder.Bind(viewModel, view, null);


问:
Allow threads (in c) to print messages without interfering with user input
I'm a writing a small webserver for personal use in c (not c++). I want to allow user input in the console like "shutdown server" or "restart server".

In order to allow this kind of input the server is running in a seperate thread (pthreads), so the console isn't blocked.

I also want this thread to print output in the console like "a new client connected" or "client requestet 'home.html'".

The problem is: If I'm typing something like "shutdown server" and at the same time the thread prints something like "a new client connected" everthing mixes up and I get something like "shuta new client connectedown server"

Is there an elegant way to print the output of the thread and at the same time allow the user to enter commands without both interfering?

Or is this a stupid idea to begin with? If yes: Is there a standard way to handle things like that (i.e. to control server).

答:
When you start your server from a command line, that console should be used as the running log (you should also have your logs written to a file for some permanence. There are two options for handling your scenario.

Have your server temporarily stop outputting to the console when a user starts typing i.e. turn on an "interactive mode.

When your server starts, have it open an "administrative port" that listens to commands sent to it from a different console. When you want to sent the shutdown command you'd use a separate program the server admin client to allow you to interface with the server via the command line (or a UI).


问:
Why is test driven development missing from Joel's Test?
I was reading this blog by Joel Spolsky about 12 steps to better code. The absence of Test Driven Development really surprised me. So I want to throw the question to the Gurus. Is TDD not really worth the effort?

答:
Test driven development was virtually unknown before Kent Beck's book came out in 2002, two years after Joel wrote that post.  The question then becomes why hasn't Joel updated his test, or if TDD had been better known in 2000 would he have included it among his criteria?

I believe he wouldn't have, for the simple reason that the important thing is you have a well-defined process, not the specific details of that process.  It's the same reason he recommends version control without specifying a specific version control system, or recommends having a bug database without recommending a specific brand.  Good teams continually improve and adapt, and use tools and processes that are a good fit for their particular situation at that particular time.  For some teams, that definitely means TDD.  For other teams, not so much.  If you do adopt TDD, make sure it's not out of a cargo cult mentality.


答:
No one but Joel could answer that for sure. But we can try some reasons/observations.

First of all, testing is not absent from the Joel's Test

Tests are mentioned two times in 12 steps directly (10 and 12)

The existence of a build is one of the first points. The idea of having build is to get the capacity to see if they break, so we are (also) talking about testing here.

Secondly, the whole idea of the Joel Test (as I understand it) is to have quick, yes-no questions. "Do you do TDD ?" will not exactly fit in (answer could be : "some of us", "for that part of the code" or "we do unit test".

Thirdly, I think no one said that (even Joel) that those points where "the only ones worth time" (by the way, "do you program" is not on it), just that those are good quick questions to ask when coming into contact with a software team, whether as a future team member or even as a customer - this is a list I gave to some non technical people around me that were looking for clues about how good/bad their own IT department was. It is not everything, but it is really bad to beat in three minutes.

Title: Why is test driven development missing from Joel's Test?

Body: I was reading this blog by Joel Spolsky about 12 steps to better code. The absence of Test Driven Development really surprised me. So I want to throw the question to the Gurus. Is TDD not really worth the effort?


答:
The way I usually do this (using PRISM), is each assembly contains an container initialisation module, where all the interfaces, instances are registered on startup.

```<code>private void RegisterResources()
{
    Container.RegisterType<IDataService, DataService>();
    Container.RegisterType<IProductSearchViewModel, ProductSearchViewModel>();
    Container.RegisterType<IProductDetailsViewModel, ProductDetailsViewModel>();
}
</code>```

And given your example classes, would be implemented like this, with the container being passed all the way through. This way any new dependencies can be added easily as you already have access to the container.

```<code>/// <summary>
/// IDataService Interface
/// </summary>
public interface IDataService
{
    DataTable GetSomeData();
}

public class DataService : IDataService
{
    public DataTable GetSomeData()
    {
        MessageBox.Show("This is a call to the GetSomeData() method.");

        var someData = new DataTable("SomeData");
        return someData;
    }
}

public interface IProductSearchViewModel
{
}

public class ProductSearchViewModel : IProductSearchViewModel
{
    private readonly IUnityContainer _container;

    /// <summary>
    /// This will get resolved if it's been added to the container.
    /// Or alternately you could use constructor resolution.
    /// </summary>
    [Dependency]
    public IDataService DataService { get; set; }

    public ProductSearchViewModel(IUnityContainer container)
    {
        _container = container;
    }

    public void SearchAndDisplay()
    {
        DataTable results = DataService.GetSomeData();

        var detailsViewModel = _container.Resolve<IProductDetailsViewModel>();
        detailsViewModel.DisplaySomeDataInView(results);

        // Create the view, usually resolve using region manager etc.
        var detailsView = new DetailsView() { DataContext = detailsViewModel };
    }
}

public interface IProductDetailsViewModel
{
    void DisplaySomeDataInView(DataTable dataTable);
}

public class ProductDetailsViewModel : IProductDetailsViewModel
{
    private readonly IUnityContainer _container;

    public ProductDetailsViewModel(IUnityContainer container)
    {
        _container = container;
    }

    public void DisplaySomeDataInView(DataTable dataTable)
    {
    }
}
</code>```

It's quite common to have a ViewModelBase class, which all your view models are derived from, which contains a reference to the container. As long as you get into the habit of resolving all view models instead of new()'ing them, it should make all dependency resolution a lot simpler.

Title: How to make creating viewmodels at runtime less painful

Body:
I apologize for the long question, it reads a bit as a rant, but I promise it's not! I've summarized my question(s) below

In the MVC world, things are straightforward. The Model has state, the View shows the Model, and the Controller does stuff to/with the Model (basically), a controller has no state. To do stuff the Controller has some dependencies on web services, repository, the lot. When you instantiate a controller you care about supplying those dependencies, nothing else. When you execute an action (method on Controller), you use those dependencies to retrieve or update the Model or calling some other domain service. If there's any context, say like some user wants to see the details of a particular item, you pass the Id of that item as parameter to the Action. Nowhere in the Controller is there any reference to any state. So far so good.

Enter MVVM. I love WPF, I love data binding. I love frameworks that make data binding to ViewModels even easier (using Caliburn Micro a.t.m.). I feel things are less straightforward in this world though. Let's do the exercise again: the Model has state, the View shows the ViewModel, and the ViewModel does stuff to/with the Model (basically), a ViewModel does have state! (to clarify; maybe it delegates all the properties to one or more Models, but that means it must have a reference to the model one way or another, which is state in itself) To do stuff the ViewModel has some dependencies on web services, repository, the lot. When you instantiate a ViewModel you care about supplying those dependencies, but also the state. And this, ladies and gentlemen, annoys me to no end.

Whenever you need to instantiate a ProductDetailsViewModel from the ProductSearchViewModel (from which you called the ProductSearchWebService which in turn returned IEnumerable<ProductDTO>, everybody still with me?), you can do one of these things:

call new ProductDetailsViewModel(productDTO, _shoppingCartWebService /* dependcy */);, this is bad, imagine 3 more dependencies, this means the ProductSearchViewModel needs to take on those dependencies as well. Also changing the constructor is painful.

call _myInjectedProductDetailsViewModelFactory.Create().Initialize(productDTO);, the factory is just a Func, they are easily generated by most IoC frameworks. I think this is bad because Init methods are a leaky abstraction. You also can't use the readonly keyword for fields that are set in the Init method. I'm sure there are a few more reasons.

call _myInjectedProductDetailsViewModelAbstractFactory.Create(productDTO); So... this is the pattern (abstract factory) that is usually recommended for this type of problem. I though it was genius since it satisfies my craving for static typing, until I actually started using it. The amount of boilerplate code is I think too much (you know, apart from the ridiculous variable names I get use). For each ViewModel that needs runtime parameters you'll get two extra files (factory interface and implementation), and you need to type the non-runtime dependencies like 4 extra times. And each time the dependencies change, you get to change it in the factory as well. It feels like I don't even use a DI container anymore. (I think Castle Windsor has some kind of solution for this [with it's own drawbacks, correct me if I'm wrong]).

do something with anonymous types or dictionary. I like my static typing.

So, yeah. Mixing state and behavior in this way creates a problem which don't exist at all in MVC. And I feel like there currently isn't a really adequate solution for this problem. Now I'd like to observe some things:

People actually use MVVM. So they either don't care about all of the above, or they have some brilliant other solution.

I haven't found an in-depth example of MVVM with WPF. For example, the NDDD-sample project immensely helped me understand some DDD concepts. I'd really like it if someone could point me in the direction of something similar for MVVM/WPF.

Maybe I'm doing MVVM all wrong and I should turn my design upside down. Maybe I shouldn't have this problem at all. Well I know other people have asked the same question so I think I'm not the only one.

To summarize

Am I correct to conclude that having the ViewModel being an integration point for both state and behavior is the reason for some difficulties with the MVVM pattern as a whole?

Is using the abstract factory pattern the only/best way to instantiate a ViewModel in a statically typed way?

Is there something like an in depth reference implementation available?

Is having a lot of ViewModels with both state/behavior a design smell?

Body:
The way I usually do this (using PRISM), is each assembly contains an container initialisation module, where all the interfaces, instances are registered on startup.

private void RegisterResources()
{
    Container.RegisterType<IDataService, DataService>();
    Container.RegisterType<IProductSearchViewModel, ProductSearchViewModel>();
    Container.RegisterType<IProductDetailsViewModel, ProductDetailsViewModel>();
}

And given your example classes, would be implemented like this, with the container being passed all the way through. This way any new dependencies can be added easily as you already have access to the container.

/// <summary>
/// IDataService Interface
/// </summary>
public interface IDataService
{
    DataTable GetSomeData();
}

public class DataService : IDataService
{
    public DataTable GetSomeData()
    {
        MessageBox.Show("This is a call to the GetSomeData() method.");

        var someData = new DataTable("SomeData");
        return someData;
    }
}

public interface IProductSearchViewModel
{
}

public class ProductSearchViewModel : IProductSearchViewModel
{
    private readonly IUnityContainer _container;

    /// <summary>
    /// This will get resolved if it's been added to the container.
    /// Or alternately you could use constructor resolution.
    /// </summary>
    [Dependency]
    public IDataService DataService { get; set; }

    public ProductSearchViewModel(IUnityContainer container)
    {
        _container = container;
    }

    public void SearchAndDisplay()
    {
        DataTable results = DataService.GetSomeData();

        var detailsViewModel = _container.Resolve<IProductDetailsViewModel>();
        detailsViewModel.DisplaySomeDataInView(results);

        // Create the view, usually resolve using region manager etc.
        var detailsView = new DetailsView() { DataContext = detailsViewModel };
    }
}

public interface IProductDetailsViewModel
{
    void DisplaySomeDataInView(DataTable dataTable);
}

public class ProductDetailsViewModel : IProductDetailsViewModel
{
    private readonly IUnityContainer _container;

    public ProductDetailsViewModel(IUnityContainer container)
    {
        _container = container;
    }

    public void DisplaySomeDataInView(DataTable dataTable)
    {
    }
}

It's quite common to have a ViewModelBase class, which all your view models are derived from, which contains a reference to the container. As long as you get into the habit of resolving all view models instead of new()'ing them, it should make all dependency resolution a lot simpler.


问:
Command pattern design
I have this old implementation of the Command pattern. It is kind of passing a Context through all the DIOperation implementation, but I realized later on, in the process of learning and learning (that never stops), that is not optimal. I also think that the "visiting" here doesn't really fit and just confuses.

I am actually thinking of refactoring my code, also because a Command should know nothing about the others and at the moment they all share the same key-value pairs. It is really hard to maintain which class owns which key-value, sometimes leading to duplicate variables.

An Example of use case: let's say CommandB requires UserName which is set by CommandA. Should CommandA set the key UserNameForCommandB=John? Or should they share a common UserName=John key-value? What if the UserName is used by a third Command?

How can I improve this design? Thanks!

```<code>class DIParameters {
public:
   /**
    * Parameter setter.
    */
    virtual void setParameter(std::string key, std::string value) = 0;
    /**
    * Parameter getter.
    */
    virtual std::string getParameter(std::string key) const = 0;

    virtual ~DIParameters() = 0;
};

class DIOperation {
public:
    /**
     * Visit before performing execution.
     */
    virtual void visitBefore(DIParameters& visitee) = 0;
    /**
     * Perform.
     */
    virtual int perform() = 0;
    /**
     * Visit after performing execution.
     */
    virtual void visitAfter(DIParameters& visitee) = 0;

    virtual ~DIOperation() = 0;
};
</code>```

答:
What is nice about design principles is that sooner or later, they conflict with each other.

In the situation described, I think I would prefer to go with some kind of context that each command can take information from and put information to (especially if those are key-value pairs). This is based on a trade off : I do not want separate commands to be coupled just because they are some kind of input to each other. Inside CommandB, I do not care how UserName was set - just that it is there for me to use. Same thing in CommandA : I set the information in, I do not want to know what other are doing with it - neither who they are.

This means a sort of passing context, which you can find bad. For me, the alternative is worse, especially if this simple key-value context (can be a simple bean with getters and setters, to limit a bit the "free form" factor) can allow the solution to be simple and testable, with well separated commands, each with its own business logic.

OwnerDisplayName: Kap

Title: Command pattern design


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答: Every programmer should know the "science" in Computer Science (design patterns, algorithms, objects, etc...) if you can master that, you can program using any language, it is just a matter of getting used to the syntax.</p>

ContentLicense: CC BY-SA 2.5


问:
Contributor's actions after rejected pull request
Imagine, there is an open-source project with a Maintainer and a Contributor. Both of them have theirs repos exported to some repository hosting (github, bitbucket, sourceforge --- whatever, but they are public).

Imagine further, Contributor did several commits, pushed them into his repo and sent pull-request to the Maintainer. Maintainer did review, made several comments about commits (fix this, fix that, simplify there, blah-blah-blah) and rejected the pull-request. Note:

For Contributor it's obvious that it's better to just fix patches/commits than rewriting from scratch.

Please consider situation, when there are many commits and fixes have to be scattered between them.

What should Contributor do in this situation before making next pull-request? Remove invalid repo, rewrite history and push new one? Make a fix commit into current one?

May Maintainer demand, that incoming history should be clean? I.e. is it technically simple enough to do?

答:
Most of the time, you simply incorporate the changes into a new commit which gets appended to the same pull request.  Primarily this is so you don't lose the review history when the fixes are reviewed.  Reviewers will want to be able to easily compare your original submission to the fixed version.  If the maintainer wants a "clean history" (by definition an inaccurate history, but that's a rant for another time), then they will usually squash your pull request when they accept it.

However, some maintainers may specifically ask you to clean up the history.  In that case, a contributor should do what they ask, which may necessitate a new pull request, depending on the tool you're using.  If you are submitting several dependent features at once, you may want to keep them in separate branches locally to make clean up like this easier.


问:
You're hired to fix a small bug for a security-intensive site. Looking at the code, it's filled with security holes. What do you do?
I've been hired by someone to do some small work on a site. It's a site for a large company. It contains very sensitive data, so security is very important. Upon analyzing the code, I've noticed it's filled with security holes - read, lots of PHP files throwing user get/post input directly into mysql requests and system commands.

The problem is, the person who made the site for him is a programmer with family and children who depend on that job. I can't just say: "your site is a script kiddie amusement park. Let me redo it for you and you'll be fine."

What would you do in this situation?

Update:

I followed some good advice here and politely reported to the developer that I've found some possible security flaws on the site. I pointed out the line and said there could be a possible vulnerability for SQL injection attacks there, and asked if he knew about it. He replied: "sure, but I think that to exploit it the attacker should have information on the structure of the database; I have to understand better".

Update 2:

I said that's not always the case and suggested he follows this Stack Overflow question link in order to deal with it properly: How to prevent SQL injection in PHP? He said he would study it and thanked me for telling him before. I guess my part is done, thanks guys.

答:
It won't do anyone any good to not report the issues. If you had a specific task you were hired for complete it but document other security issues as you see them and report them to the appropriate individual, probably the individual that you are reporting to for the task you were hired for.

This is a situation where strong soft skills are going to come in handy as to handle this with tact will require not putting down the work done by others on the site and not making the developer feel as if you are questioning his talent.

Obviously avoid words like "crap, bad, poor, riddled" when referring to the code/flaws and similar words for the developer that wrote the site.


答:
First and foremost here, the priority is to close the security holes.

If you're working directly with the engineer who wrote this, document everything and give it to that engineer.

If not, tell your employer the security issues are bigger than initially thought and that the site needs a lot of work. Ask to work with the main developer who's on the site, and offer to teach them about PHP security (don't promise to make the person an expert, but do offer to train them in everything you know) so that person can take it over after you're done.

Don't make this a "this guy is bad, fire him" issue. Approach it from the perspective of "Hey, I found some potential bugs that need fixing stat, which seem to be coming from some ignorance/common misconceptions about site security. I'd also like to talk to your development so we can improve your site and hopefully avoid more of these issues in the future."

Title: You're hired to fix a small bug for a security-intensive site. Looking at the code, it's filled with security holes. What do you do?

Body:
I've been hired by someone to do some small work on a site. It's a site for a large company. It contains very sensitive data, so security is very important. Upon analyzing the code, I've noticed it's filled with security holes - read, lots of PHP files throwing user get/post input directly into mysql requests and system commands.

The problem is, the person who made the site for him is a programmer with family and children who depend on that job. I can't just say: "your site is a script kiddie amusement park. Let me redo it for you and you'll be fine."

What would you do in this situation?

Update:

I followed some good advice here and politely reported to the developer that I've found some possible security flaws on the site. I pointed out the line and said there could be a possible vulnerability for SQL injection attacks there, and asked if he knew about it. He replied: "sure, but I think that to exploit it the attacker should have information on the structure of the database; I have to understand better".

Update 2:

I said that's not always the case and suggested he follows this Stack Overflow question link in order to deal with it properly: How to prevent SQL injection in PHP? He said he would study it and thanked me for telling him before. I guess my part is done, thanks guys.


答:
First and foremost - fix the thing they hired you for. If you don't do that, then you'll be perceived as the type of consultant who's interested in making more work for themself, rather than getting the job done.

Along with the fixes, you need to give them a list of the stuff you've noticed that's wrong from a security perspective, and why these things are wrong.


答:
Your job isn't to redo the site for him. It's to fix the small bug. However, if you've noticed security issues that should be fixed you can bring it up with the site owner and offer insight on what the problem might be.

Don't berate or talk negatively about the original developer or comment on how horrible the code is. Be respectful and professional. You can offer to work with the developer to resolve the issues. Don't try to fix it yourself or offer a solution unless you've been contracted to address the problem. If they follow your advice and you're wrong they could come back on you.


答:
There's a difference between ignorance and incompetence.  There was a time when you didn't know what SQL injection was either, and there's no reason to believe the original programmer isn't capable of fixing the problems once he is made aware of them.

So tell them.  Be specific and objective, and make yourself available to answer questions, provide examples of exploits, and recommendations for fixes.  If they still don't get it after that point, the most you can really do is not put any of your own personal information on the site.


问:
How to avoid giant glue methods?
In my current job, I've been tasked with cleaning up old code a few times.  Often the code is a labyrinth and the data behind it is even more tangled.  I find myself combing out things into nice, neat, modular methods.  Each method does one thing and does it well.  That's when things start to go south...

Invariably, I end up with a clean API and no real way to tie it all together.  The solution has been to write a big ugly "glue" method (generally full of conditional statements) that eventually calls all of my "clean" methods.

The glue method usually ends up being a terse version of the tangle of code/data that I was attempting to clean up.  It's generally more readable, but it's still annoying.

How can I avoid such methods?  Is this a symptom of the tangled data or a reflection of something that I'm doing wrong?

答:
It sounds like you are refactoring the API by just thinking about the implementation of the API, but without thinking enough about the code that uses the API - that is, the "glue code" you are talking about.

If that's true you might try to start at the other end. Rewrite the stuff that threatens to become your ugly glue code first, and create a couple of not yet implemented interfaces that will become your API in that process. Do not think too much about the actual implementation of this API yet - it's OK if you have the gut feeling that you can do it. And only then rewrite the code labyrinth to conform to that API. Of course there will be some changes in the API and the glue code in this process, but it should fit together better.

Title: How to avoid giant glue methods?


答:
Joel has actually addressed this specifically in a few places.

He's explained that the things tests are not capable of catching a lot of important issues, particularly subjective ones such as "does this software's user interface suck?"  According to him, over-reliance on automated tests at Microsoft is how we ended up with Windows Vista.

He's written how, in his experience, the kinds of bugs that users actually find tend to fall into two categories: 1) the ones that show up in common usage, which the programmers would have found themselves had they run their own code before using it, or 2) edge cases so obscure that no one would have thought to write tests to cover them in the first place.  He's stated that only a very small percentage of the bugs he and his team fixes in FogBugz are the sort of thing that unit testing would have caught.  (I can't find that article now, but if anyone knows which one I mean, feel free to edit the link into here.)

And he's written how it can be more trouble than it's worth, especially when your project grows into a very large project with many unit tests, and then you change something (intentionally) and end up with a very large number of broken unit tests.  He specifically uses the problems that unit testing can cause as the reason why he has not added it as a 13th point to the Joel Test, even when people suggest that he ought to.


答:
There is no good way to do what you want to do.

As you have observed, if you allow the logger to continue its output while the command interpreter is echoing the user's typing, you get a mishmashed mess.

The flip side is this: if you block the logger when the user starts typing, you risk blocking an IMPORTANT message, one that requires IMMEDIATE action.

The best answer is to have two (2) "consoles", displayed simultaneously, so you don't have to block your logger.

If you can't do that, because (for example), you're on a raw serial port, then option two is to add priorities to your output messages.  When the user starts typing, unimportant messages get held until he finishes typing.  Important messages blast through, and then the command interpreter retypes his line so far.  This will require some amount of buffer space to stack his messages while he's scratching his head.

PERSONALLY, if I was going to do something like this, I'd put a timeout on the held messages: if he doesn't finish typing his command in some amount of time, the previously-held unimportant messages get dumped through, and then the command line so far gets retyped.

Usually, it isn't worth the trouble to avoid the message mixing.  If you have a verbose operator and a verbose message logger, you've got bigger problems than just mixed output streams.

Title: Allow threads (in c) to print messages without interfering with user input

Body:
I'm a writing a small webserver for personal use in c (not c++). I want to allow user input in the console like "shutdown server" or "restart server".

In order to allow this kind of input the server is running in a seperate thread (pthreads), so the console isn't blocked.

I also want this thread to print output in the console like "a new client connected" or "client requestet 'home.html'".

The problem is: If I'm typing something like "shutdown server" and at the same time the thread prints something like "a new client connected" everthing mixes up and I get something like "shuta new client connectedown server"

Is there an elegant way to print the output of the thread and at the same time allow the user to enter commands without both interfering?

Or is this a stupid idea to begin with? If yes: Is there a standard way to handle things like that (i.e. to control server).


答:
Lets assume you have a command interface:

```<code>class Command {
public:
    void execute() = 0;
};
</code>```

And a subject:

```<code>class Subject {
    std::string name;
public:
    void setName(const std::string& name) {this->name = name;}
}
</code>```

What you need is:

```<code>class NameObserver {
public:
    void update(const std::string& name) = 0;
};

class Subject {
    NameObserver& o;
    std::string name;
private:
    void setName(const std::string& name) {
        this->name = name;
        o.update(name);
    }
};

class CommandB: public Command, public NameObserver {
    std::string name;
public:
    void execute();
    void update(const std::string& name) {
        this->name = name;
        execute();
    }
};
</code>```

Set NameObserver& o as a reference to CommandB. Now whenever CommandA changes the Subjects name CommandB can execute with the correct information. If name is used by more command use a std::list<NameObserver>

Title: Command pattern design

Body:
I have this old implementation of the Command pattern. It is kind of passing a Context through all the DIOperation implementation, but I realized later on, in the process of learning and learning (that never stops), that is not optimal. I also think that the "visiting" here doesn't really fit and just confuses.

I am actually thinking of refactoring my code, also because a Command should know nothing about the others and at the moment they all share the same key-value pairs. It is really hard to maintain which class owns which key-value, sometimes leading to duplicate variables.

An Example of use case: let's say CommandB requires UserName which is set by CommandA. Should CommandA set the key UserNameForCommandB=John? Or should they share a common UserName=John key-value? What if the UserName is used by a third Command?

How can I improve this design? Thanks!

```<code>class DIParameters {
public:
   /**
    * Parameter setter.
    */
    virtual void setParameter(std::string key, std::string value) = 0;
    /**
    * Parameter getter.
    */
    virtual std::string getParameter(std::string key) const = 0;

    virtual ~DIParameters() = 0;
};

class DIOperation {
public:
    /**
     * Visit before performing execution.
     */
    virtual void visitBefore(DIParameters& visitee) = 0;
    /**
     * Perform.
     */
    virtual int perform() = 0;
    /**
     * Visit after performing execution.
     */
    virtual void visitAfter(DIParameters& visitee) = 0;

    virtual ~DIOperation() = 0;
};
</code>```

Body:
Lets assume you have a command interface:

class Command {
public:
    void execute() = 0;
};

And a subject:

class Subject {
    std::string name;
public:
    void setName(const std::string& name) {this->name = name;}
}

What you need is:

class NameObserver {
public:
    void update(const std::string& name) = 0;
};

class Subject {
    NameObserver& o;
    std::string name;
private:
    void setName(const std::string& name) {
        this->name = name;
        o.update(name);
    }
};

class CommandB: public Command, public NameObserver {
    std::string name;
public:
    void execute();
    void update(const std::string& name) {
        this->name = name;
        execute();
    }
};

Set NameObserver& o as a reference to CommandB. Now whenever CommandA changes the Subjects name CommandB can execute with the correct information. If name is used by more command use a std::list<NameObserver>


问:
Leaving "Else" comments
Let's say I have a not-so-intuitive if statement in my code, but only if you're new to the codebase:

```<code>def set_markets(markets=None):
    """
    Will accept 'all' as markets to set all markets on.
    For individual markets, pass in a list of ints.
    """
    if markets:
        if type(markets) == list:
            markets = ','.join(map(str, markets))
        self._set_markets(markets)
</code>```

For those of you wondering:

The existing system I'm interacting with (a database) expects a list of integers from the front end interface. This code does it from the backend, so a list of ints was chosen since it best represents what a user might feed in otherwise.

The markets stuff is handed down from another class, so even though it appears like it's taking place over 5 lines, it's more like ~50 lines.

My question is, would you consider this more readable? Why or why not?

```<code>def set_markets(markets=None):
    """
    Will accept 'all' as markets to set all markets on.
    For individual markets, pass in a list of ints.
    """
    if markets:
        if type(markets) == list:
            markets = ','.join(map(str, markets))
      # else:
          # markets are set to "all"
        self._set_markets(markets)
</code>```

EDIT:

This code looks worse than it is because I left off a detail: if None is fed in for markets (the default parameter), then it will not modify the markets settings the database.

Here's what I have now:

```<code>    if markets is not None:
        if isinstance(markets, list):
            markets = ','.join(map(str, markets))
        else:
            markets = 'all'
        self._set_new_header_markets(markets)
</code>```

答:
Firstly, putting code in comments makes me assume it's dead code. It'll just be really confusing if you do that.

Secondly, the fact that you need a comment is because your code is unreadable. Try for making the code readable before adding a comment.

If you accept 'all' or a list, you should really do it like this:

```<code>if markets == 'all':
   self._set_markets('all')
else:
   self._set_markets(','.join(map(str, markers))
</code>```

Then its abundantly clear what is going on and you avoid type checking, and you don't accept invalid data so long as it isn't a list.

Title: Leaving "Else" comments

Body:
Firstly, putting code in comments makes me assume it's dead code. It'll just be really confusing if you do that.

Secondly, the fact that you need a comment is because your code is unreadable. Try for making the code readable before adding a comment.

If you accept 'all' or a list, you should really do it like this:

if markets == 'all':
   self._set_markets('all')
else:
   self._set_markets(','.join(map(str, markers))

Then its abundantly clear what is going on and you avoid type checking, and you don't accept invalid data so long as it isn't a list.


答:
To me, the fact that you've formatted the else: to look like regular code is misleading; something more commenty seems like it'd be appropriate.

Right now it looks like the else is commented out because there is no code for that block yet, and the inner comment is a placeholder for code to come, which is not the case (?). I'd inline both comments, bump up the indentation on the hash and maybe remove the else's formatting:

```<code>if markets:
    if type(markets) == list:
        markets = ','.join(map(str, markets))
    # else: markets are set to "all"
    self._set_markets(markets)
</code>```

Title: Leaving "Else" comments

Body:
Let's say I have a not-so-intuitive if statement in my code, but only if you're new to the codebase:

```<code>def set_markets(markets=None):
    """
    Will accept 'all' as markets to set all markets on.
    For individual markets, pass in a list of ints.
    """
    if markets:
        if type(markets) == list:
            markets = ','.join(map(str, markets))
        self._set_markets(markets)
</code>```

For those of you wondering:

The existing system I'm interacting with (a database) expects a list of integers from the front end interface. This code does it from the backend, so a list of ints was chosen since it best represents what a user might feed in otherwise.

The markets stuff is handed down from another class, so even though it appears like it's taking place over 5 lines, it's more like ~50 lines.

My question is, would you consider this more readable? Why or why not?

```<code>def set_markets(markets=None):
    """
    Will accept 'all' as markets to set all markets on.
    For individual markets, pass in a list of ints.
    """
    if markets:
        if type(markets) == list:
            markets = ','.join(map(str, markets))
      # else:
          # markets are set to "all"
        self._set_markets(markets)
</code>```

EDIT:

This code looks worse than it is because I left off a detail: if None is fed in for markets (the default parameter), then it will not modify the markets settings the database.

Here's what I have now:

```<code>    if markets is not None:
        if isinstance(markets, list):
            markets = ','.join(map(str, markets))
        else:
            markets = 'all'
        self._set_new_header_markets(markets)
</code>```

Body:
To me, the fact that you've formatted the else: to look like regular code is misleading; something more commenty seems like it'd be appropriate.

Right now it looks like the else is commented out because there is no code for that block yet, and the inner comment is a placeholder for code to come, which is not the case (?). I'd inline both comments, bump up the indentation on the hash and maybe remove the else's formatting:

if markets:
    if type(markets) == list:
        markets = ','.join(map(str, markets))
    # else: markets are set to "all"
    self._set_markets(markets)


问:
Unit testing in Django
I'm really struggling to write effective unit tests for a large Django project.  I have reasonably good test coverage, but I've come to realize that the tests I've been writing are definitely integration/acceptance tests, not unit tests at all, and I have critical portions of my application that are not being tested effectively.  I want to fix this ASAP.

Here's my problem. My schema is deeply relational, and heavily time-oriented, giving my model object high internal coupling and lots of state.  Many of my model methods query based on time intervals, and I've got a lot of auto_now_add going on in timestamped fields.  So take a method that looks like this for example:

```<code>def summary(self, startTime=None, endTime=None):
    # ... logic to assign a proper start and end time
    # if none was provided, probably using datetime.now()

    objects = self.related_model_set.manager_method.filter(...)

    return sum(object.key_method(startTime, endTime) for object in objects)
</code>```

How does one approach testing something like this?

Here's where I am so far.  It occurs to me that the unit testing objective should be given some mocked behavior by key_method on its arguments, is summary correctly filtering/aggregating to produce a correct result?

Mocking datetime.now() is straightforward enough, but how can I mock out the rest of the behavior?

I could use fixtures, but I've heard pros and cons of using fixtures for building my data (poor maintainability being a con that hits home for me).

I could also setup my data through the ORM, but that can be limiting, because then I have to create related objects as well.  And the ORM doesn't let you mess with auto_now_add fields manually.

Mocking the ORM is another option, but not only is it tricky to mock deeply nested ORM methods, but the logic in the ORM code gets mocked out of the test, and mocking seems to make the test really dependent on the internals and dependencies of the function-under-test.

The toughest nuts to crack seem to be the functions like this, that sit on a few layers of models and lower-level functions and are very dependent on the time, even though these functions may not be super complicated. My overall problem is that no matter how I seem to slice it, my tests are looking way more complex than the functions they are testing.

答:
I'm going to go ahead and register an answer for what I've come up with so far.

My hypothesis is that for a function with deep coupling and state, the reality is that it's simply going to take a lot of lines to control for its outside context.

Here's what my test case looks like roughly, relying on the standard Mock library:

I use the standard ORM to set up the sequence of events

I create my own start datetime and subvert the auto_now_add times to fit a fixed timeline of my design.  I thought that the ORM didn't allow this, but it works fine.

I make sure the function-under-test uses from datetime import datetime so that I can patch datetime.now() in just that function (if I mock the entire datetime class, the ORM pitches a fit).

I create my own replacement for object.key_method(), with simple but well defined functionality that depends on the arguments.  I want it to depend on the arguments, because otherwise I might not know if the logic of the function-under-test is working. In my case, it simply returns the number of seconds between startTime and endTime.  I patch it in by wrapping it in a lambda and patching directly on to object.key_method() using the new_callable kwarg of patch.

Finally, I run a series of asserts on various calls of summary with different arguments to check equality with expected hand-calculated results accounting for the given behavior of the mock key_method

Needless to say, this is significantly longer and more complicated than the function itself.  It depends on the DB, and doesn't really feel like a unit test.  But it is also fairly decoupled from the internals of the function--just its signature and dependencies.  So I think it might actually be a unit test, still.

In my app, the function is quite pivotal, and subject to refactoring to optimize its performance.  So I think the trouble is worth it, complexity notwithstanding.  But I'm still open to better ideas on how to approach this.  All part of my long journey toward a more test-driven style of development...

Title: Unit testing in Django


问:
C++ vs Objective-C design principles of setters and getters
In C++ I was told that my classes shouldn't have getters and setters: Doing it wrong... blog post.

On the other hand, in Objective-C, the direct use of ivar is discouraged, because the getters allow to do lazy instantiation, and setters make KVO easy.

Why is that difference?

答:
As a C# developer, I use getters/setters all the time.  Since I rarely (but still do) use C++, I might could offer a different perspective on this one.

To my eye, the bulk of difference of acceptability between C++ and C# has been due to conventions between users of a language (though there are others I'll get to later...).  Most of the time in C++, I just don't need to use a getter/setter because it is not encouraged to do so.  Unlike the blog post, I don't even view it as a matter of 'right way to code' or 'wrong way to code.'  It's a convention that allows other humans to make heads or tails of what I've written/maintained.

C# does not mitigate that need, and as far as I've seen, there's no evidence to say that getters/setters in C# are any more or less peformant than methods in C++ (I would assume they're on roughly the same order, but that's a gut feeling, there.)  Yet, the general feeling in the C# community is that, while methods are preferable, properties are great for taking methods like:

```<code>public string GetName()
{
    return _lastName + ", " + _firstName + " " + _middleInitial;
}

public string SetName(string fullName)
{
    // Assumptions are made here; this is just example code!
    string[] frags = fullName.Split(' ');
    _firstName = frags[0];
    _middleName = frags[1];
    _lastName = frags[2];
}
</code>```

and creating a slightly 'shorter', different, but reasonably readable syntax like:

```<code>public string Name
{
    get { return _lastName + ", " + _firstName + " " + _middleInitial; }
    private set
    {
        string[] frags = value.Split(' ');
        _firstName = frags[0];
        _middleName = frags[1];
        _lastName = frags[2];
    }
}
</code>```

You could say that to a C# or Java programmer, we view properties as syntactic sugar for simple methods, since that's all a getter/setter really is: a method.

Another wrinkle in the technologies lies in various frameworks.  For instance, in my current shop, our MVC projects are set up such that we're more or less required to use getters and setters by NHibernate and the MVC framework itself.  We've had conversations about the perceived overabundance of properties in our app, but in the end we had no technical recourse to revise those to simple methods.  We have to use properties because reflection is used to retrieve properties, and thus their contents.  Our code would be bigger and nastier without them, so no one really complains all that much.

To finally answer your question, though, I think that dives to the heart of the matter.

A C++ programmer expects to need the deep technical details of a given operation; instead of obscuring this machination with syntactic sugar, it's more understandable to just bite the bullet and do the work.  It's not that C++ programmers are averse to syntactic sugar at all (in fact, I find myself yearning for better ways to express my C++ code when I use it...), but the things you turn to C++ for and the things you use properties for typically don't mesh well on a practical level*.

A C# or Java programmer is taking advantage of the virtual machine interposed between the physical layer and our high-level code; we lose little by utilizing the syntactic sugar, and in return gain (slightly) improved readability without wholly violating encapsulation...providing the getters/setters are implemented correctly.  The things you turn to C# or Java for do mesh well with properties on a practical level.

*: Note that I'm not a frequent C++ user!  I beg for correction, if anyone has any to give.

Body:
As a C# developer, I use getters/setters all the time.  Since I rarely (but still do) use C++, I might could offer a different perspective on this one.

To my eye, the bulk of difference of acceptability between C++ and C# has been due to conventions between users of a language (though there are others I'll get to later...).  Most of the time in C++, I just don't need to use a getter/setter because it is not encouraged to do so.  Unlike the blog post, I don't even view it as a matter of 'right way to code' or 'wrong way to code.'  It's a convention that allows other humans to make heads or tails of what I've written/maintained.

C# does not mitigate that need, and as far as I've seen, there's no evidence to say that getters/setters in C# are any more or less peformant than methods in C++ (I would assume they're on roughly the same order, but that's a gut feeling, there.)  Yet, the general feeling in the C# community is that, while methods are preferable, properties are great for taking methods like:

public string GetName()
{
    return _lastName + ", " + _firstName + " " + _middleInitial;
}

public string SetName(string fullName)
{
    // Assumptions are made here; this is just example code!
    string[] frags = fullName.Split(' ');
    _firstName = frags[0];
    _middleName = frags[1];
    _lastName = frags[2];
}

and creating a slightly 'shorter', different, but reasonably readable syntax like:

public string Name
{
    get { return _lastName + ", " + _firstName + " " + _middleInitial; }
    private set
    {
        string[] frags = value.Split(' ');
        _firstName = frags[0];
        _middleName = frags[1];
        _lastName = frags[2];
    }
}

You could say that to a C# or Java programmer, we view properties as syntactic sugar for simple methods, since that's all a getter/setter really is: a method.

Another wrinkle in the technologies lies in various frameworks.  For instance, in my current shop, our MVC projects are set up such that we're more or less required to use getters and setters by NHibernate and the MVC framework itself.  We've had conversations about the perceived overabundance of properties in our app, but in the end we had no technical recourse to revise those to simple methods.  We have to use properties because reflection is used to retrieve properties, and thus their contents.  Our code would be bigger and nastier without them, so no one really complains all that much.

To finally answer your question, though, I think that dives to the heart of the matter.

A C++ programmer expects to need the deep technical details of a given operation; instead of obscuring this machination with syntactic sugar, it's more understandable to just bite the bullet and do the work.  It's not that C++ programmers are averse to syntactic sugar at all (in fact, I find myself yearning for better ways to express my C++ code when I use it...), but the things you turn to C++ for and the things you use properties for typically don't mesh well on a practical level*.

A C# or Java programmer is taking advantage of the virtual machine interposed between the physical layer and our high-level code; we lose little by utilizing the syntactic sugar, and in return gain (slightly) improved readability without wholly violating encapsulation...providing the getters/setters are implemented correctly.  The things you turn to C# or Java for do mesh well with properties on a practical level.

*: Note that I'm not a frequent C++ user!  I beg for correction, if anyone has any to give.


问:
Is it safe to assume that one controller will only ever use one primary model?
So, I'm designing an MVC framework. In the name of keeping everything statically typed and non-magical, I've come to quite a problem with "automatically" passing models to a controller.

So, traditionally, I usually see no more than one model used at a time in a controller as far as automatic-population.

For instance, take this tutorial. There is a method like this in the controller:

```<code>[HttpPost]
public ActionResult Create(Movie newMovie)
{

    if (ModelState.IsValid)
    {
        db.AddToMovies(newMovie);
        db.SaveChanges();

        return RedirectToAction("Index");
    }
    else
    {
        return View(newMovie);
    }
}
</code>```

My concern is passing a Movie model to the Create method which is populated by FORM values "magically". In my API, this should be easily possible and would look something like this at routing:

```<code>var movie=router.Controller((context) => new MovieController(context))
                 .WithModel(() => new Movie());
movie.Handles("/movie/create").With((controller, model) => controller.Create(model));
</code>```

My concern with this is that it is much harder to have multiple models because of limitations with C#'s type system. Of course, the controller can always manually create the models from FORM values and such, but it's not nearly as pretty.

So, my question: Is it common to have something like Foo(Movie model) and Bar(SomeClass model) in the same controller class? Is it a good idea for me to attempt to support such a scenario, or is it just a symptom of putting too much unrelated logic in a single controller?

Note: if you're concerned about how this fluent API is even possible, the answer is generic delegates.. lots and lots of generic delegates :) (but so far very little reflection)

答: Earlz in my humble opinion first i think that a controller should control a sub-section of your project let's say the messaging system or in your case the movie domain. So in essence i don't think that it's wrong to use the different models required to achieve your goal in a controller. Also, you can use your domain model without sub-classing like entity framework code first developers do. So the most important thing is that you plan your controllers in a way that all the action methods in it will perform a set of related function.</p>


问:
What are the best algorithms out there to retrieve data from a file system?
This is my usecase:

Traverse a filesystem, gauge its entire size and then upload it to Dropbox.

Looks quite easy and is quite easy. Now if I do it using celery and spawn a thread for each folder(With sub files), then it becomes an easier process to gather all the data and gauge the size and then upload it to dropbox.

But I feel I'm doing something wrong here. If I implement this on a server, I'm surely overloading it by spawning a thread for each folder that is out there. Hence, what algorithms should I use to make this a faster process? Both as a data retrieval and data uploading.
Links/References would help.

答:
The short version:  absent unusual circumstances, you should use a single-threaded traversal.  As @CodesInChaos says, your computer is likely to be I/O bound in both phases of your task:  size-checking and uploading alike.

Trying to spawn a thread per directory is a recipe for fork-bombing your machine into oblivion.  More precisely, there is no point in invoking more threads than are necessary to saturate your performance bottlenecks.  Note that there are 2 likely bottlenecks:  the performance of your filesystem, and the performance of your network link to Dropbox.

For uploading data to Dropbox, your network is almost certainly the bottleneck.  You should easily be able to saturate any broadband link with a single-threaded traversal.

For finding the size of the filesystem, your bottleneck will also be I/O, but the details depend on the actual filesystem.  For a solid-state drive, you probably won't benefit from more than a single thread.  I suspect that you may gain a modest benefit from a bounded number of threads in a single-disk filesystem, as the OS can potentially schedule head stops a bit more efficiently if it has a queue.  The question is, would a small performance margin be worth the cost of implementing and maintaining a more complex implementation?  (E.g., handling cases like multiple hard links may be difficult enough with a single-threaded implementation...)

A distributed filesystem might benefit quite a lot from a multithreaded traversal.  However, the details of how to extract the best performance are likely to depend on the specific system.


问:
Are exceptions as control flow considered a serious antipattern? If so, Why?
Back in the late 90's I worked quite a bit with a code base that used exceptions as flow control. It implemented a finite state machine to drive telephony applications.  Lately I am reminded of those days because I've been doing MVC web apps.

They both have Controllers that decide where to go next and supply the data to the destination logic. User actions from the domain of an old-school telephone, like DTMF tones, became parameters to action methods, but instead of returning something like a ViewResult, they threw a StateTransitionException.

I think the main difference was that action methods were void functions.  I don't remember all the things I did with this fact but I've been hesitant to even go down the road of remembering much because since that job, like 15 years ago, I never saw this in production code at any other job. I assumed this was a sign that it was a so-called anti-pattern.

Is this the case, and if so, why?

答:
There's a detailed discussion of this on Ward's Wiki. Generally, the use of exceptions for control flow is an anti-pattern, with many notable situation - and language-specific (see for example Python) cough exceptions cough.

As a quick summary for why, generally, it's an anti-pattern:

Exceptions are, in essence, sophisticated GOTO statements

Programming with exceptions, therefore, leads to more difficult to read, and understand code

Most languages have existing control structures designed to solve your problems without the use of exceptions

Arguments for efficiency tend to be moot for modern compilers, which tend to optimize with the assumption that exceptions are not used for control flow.

Read the discussion at Ward's wiki for much more in-depth information.

See also a duplicate of this question, here

ContentLicense: CC BY-SA 4.0


答:
The use case that exceptions were designed for is "I just encountered a situation that I cannot deal with properly at this point, because I don't have enough context to handle it, but the routine that called me (or something further up the call stack) ought to know how to handle it."

The secondary use case is "I just encountered a serious error, and right now getting out of this control flow to prevent data corruption or other damage is more important than trying to continue onward."

If you're not using exceptions for one of these two reasons, there's probably a better way to do it.

Title: Are exceptions as control flow considered a serious antipattern? If so, Why?

Body:
Back in the late 90's I worked quite a bit with a code base that used exceptions as flow control. It implemented a finite state machine to drive telephony applications.  Lately I am reminded of those days because I've been doing MVC web apps.

They both have Controllers that decide where to go next and supply the data to the destination logic. User actions from the domain of an old-school telephone, like DTMF tones, became parameters to action methods, but instead of returning something like a ViewResult, they threw a StateTransitionException.

I think the main difference was that action methods were void functions.  I don't remember all the things I did with this fact but I've been hesitant to even go down the road of remembering much because since that job, like 15 years ago, I never saw this in production code at any other job. I assumed this was a sign that it was a so-called anti-pattern.

Is this the case, and if so, why?


答:
It's completely possible to handle error conditions without the use of exceptions.  Some languages, most notably C, don't even have exceptions, and people still manage to create quite complex applications with it.  The reason exceptions are useful is they allow you to succinctly specify two essentially independent control flows in the same code:  one if an error occurs and one if it doesn't.  Without them, you end up with code all over the place that looks like this:

```<code>status = getValue(&inout);
if (status < 0)
{
    logError("message");
    return status;
}

doSomething(*inout);
</code>```

Or equivalent in your language, like returning a tuple with one value as an error status, etc.  Often people who point out how "expensive" exception handling is, neglect all the extra if statements like above that you are required to add if you don't use exceptions.

While this pattern happens to occur most often when handling errors or other "exceptional conditions," in my opinion if you start seeing boilerplate code like this in other circumstances, you have a pretty good argument for using exceptions.  Depending on the situation and implementation, I can see exceptions being used validly in a state machine, because you have two orthogonal control flows:  one that's changing the state and one for the events that occur within the states.

However, those situations are rare, and if you're going to make an exception (pun intended) to the rule, you had better be prepared to show its superiority to other solutions.  A deviation without such justification is rightly called an anti-pattern.

Body:
It's completely possible to handle error conditions without the use of exceptions.  Some languages, most notably C, don't even have exceptions, and people still manage to create quite complex applications with it.  The reason exceptions are useful is they allow you to succinctly specify two essentially independent control flows in the same code:  one if an error occurs and one if it doesn't.  Without them, you end up with code all over the place that looks like this:

status = getValue(&inout);
if (status < 0)
{
    logError("message");
    return status;
}

doSomething(*inout);

Or equivalent in your language, like returning a tuple with one value as an error status, etc.  Often people who point out how "expensive" exception handling is, neglect all the extra if statements like above that you are required to add if you don't use exceptions.

While this pattern happens to occur most often when handling errors or other "exceptional conditions," in my opinion if you start seeing boilerplate code like this in other circumstances, you have a pretty good argument for using exceptions.  Depending on the situation and implementation, I can see exceptions being used validly in a state machine, because you have two orthogonal control flows:  one that's changing the state and one for the events that occur within the states.

However, those situations are rare, and if you're going to make an exception (pun intended) to the rule, you had better be prepared to show its superiority to other solutions.  A deviation without such justification is rightly called an anti-pattern.


答:
In Python, exceptions are used for generator and iteration termination.  Python has very efficient try/except blocks, but actually raising an exception has some overhead.

Due to lack of multi-level breaks or an goto statement in Python, I have at times used exceptions:

```<code>class GOTO(Exception):
  pass

try:
  # Do lots of stuff
  # in here with multiple exit points
  # each exit point does a "raise GOTO()"
except GOTO:
  pass
except Exception as e:
  #display error
</code>```

Body:
In Python, exceptions are used for generator and iteration termination.  Python has very efficient try/except blocks, but actually raising an exception has some overhead.

Due to lack of multi-level breaks or an goto statement in Python, I have at times used exceptions:

class GOTO(Exception):
  pass

try:
  # Do lots of stuff
  # in here with multiple exit points
  # each exit point does a "raise GOTO()"
except GOTO:
  pass
except Exception as e:
  #display error


问:
What is the difference between requirements and specifications?
I've been tasked with developing requirements and specifications for a project our group is starting.

I realized that I don't know the difference; a Google search just confused me more -- it seems some people say that specifications are requirements, but at a lower level.

答:
Requirement - what the system or subsystem should (must) do.

Specification - What the component, subsystem or system IS.

This is critical in the medical device manufacturing industry since you must conduct Verification against your requirements (Inputs) to demonstrate that you have valid specifications (Outputs). Typical pitfalls in this industry is that companies (1) forget to define requirements (because they don't understand the difference between requirement versus spec); (2) Conduct Verification against only specifications and (3) Do not assure that Requirements are being translated accurately in to subassembly and component specifications.

Once this is all done, you are then required to Validate the User requirements for the product have been met.


答:
Exceptions are as powerful as Continuations and GOTO. They are a universal control flow construct.

In some languages, they are the only universal control flow construct. JavaScript, for example, has neither Continuations nor GOTO, it doesn't even have Proper Tail Calls. So, if you want to implement sophisticated control flow in JavaScript, you have to use Exceptions.

The Microsoft Volta project was a (now discontinued) research project to compile arbitrary .NET code to JavaScript. .NET has Exceptions whose semantics don't exactly map to JavaScript's, but more importantly, it has Threads, and you have to map those somehow to JavaScript. Volta did this by implementing Volta Continuations using JavaScript Exceptions and then implement all .NET control flow constructs in terms of Volta Continuations. They had to use Exceptions as control flow, because there is no other control flow construct powerful enough.

You mentioned State Machines. SMs are trivial to implement with Proper Tail Calls: every state is a subroutine, every state transition is a subroutine call. SMs can also easily be implemented with GOTO or Coroutines or Continuations. However, Java doesn't have any of those four, but it does have Exceptions. So, it is perfectly acceptable to use those as control flow. (Well, actually, the correct choice would probably be to use a language with the proper control flow construct, but sometimes you may be stuck with Java.)


问:
Web Project Class Architecture
I think this is a good question for here but I'm not 100% sure. Please flag if it's too vague.

I've worked on many websites where common framework classes are overridden.

Since I work mostly in .net these days examples would include Page, Masterpage, UserControl, DbContext ect. I believe this could apply to any language though.

Sometimes I can see why it's done, I overrode entity framework's DbContext to include some logging code.

Allot of the time though I don't see why these base classes were created. Because I've inherited most of the sites I can't really ask why.

My question: Is it a good idea/practice when creating a new site to Override the common framework classes mentioned above? Would doing so be considered more of an old style?

答:
When you create an application, most of what you are doing ought to be framework independent. The framework really ought to be a detail on the side, not an integral part at the centre of your application. Think of it as a delivery mechanism or so. Same goes for databases and whatnot. If you create proper boundaries, you'll be able to switch database, UI, routing framework, etc, without having to rewrite your application.

This means that in general it is not a good idea to have your app work with classes that inherit from things outside of your package boundary. Hard to create a tighter coupling or greater dependency then inheriting. Esp mixing in logging there seems wrong.

On the logging topic - be very careful on what logging code you put in a DbContext. If this DbContext takes a logger using some nice Logger interface, then it can work. Else you are probably violating the Single responsibility principle.

Title: Web Project Class Architecture


问:
How to properly diagram lambda expressions or traversals through them in Architecture Explorer?
I'm exploring a piece of code in Architecture Explorer in Visual Studio 2010 to study the relations between methods. I noticed a strange behavior.

Take the following source code. It generates a hello message based on a template and a template engine, the template engine being a method (a sort of strategy pattern simplified at a maximum for demo purposes).

public string GenerateHelloMessage(string personName)
{
    return this.ApplyTemplate(
        this.DefaultTemplateEngine, this.GenerateLocalizedHelloTemplate(), personName);
}

private string GenerateLocalizedHelloTemplate()
{
    return "Hello {0}!";
}

public string ApplyTemplate(
    Func<string, string, string> templateEngine, string template, string personName)
{
    return templateEngine(template, personName);
}

public string DefaultTemplateEngine(string template, string personName)
{
    return string.Format(template, personName);
}
```

<p>The graph generated from this code is this one:</p>

<p><img src="https://i.stack.imgur.com/khnYr.png" alt="enter image description here"></p>

<p>Change the first method from this:</p>

<pre class="lang-cs prettyprint-override"><code>public string GenerateHelloMessage(string personName)
{
    return this.ApplyTemplate(
        this.DefaultTemplateEngine, this.GenerateLocalizedHelloTemplate(), personName);
}
</code>```

to this:

public string GenerateHelloMessage(string personName)
{
    return this.ApplyTemplate(
        (a, b) => this.DefaultTemplateEngine(a, b),
        this.GenerateLocalizedHelloTemplate(), personName);
}
```

and the graph becomes:

While semantically identical, those two versions of code produce different dependency graphs, and Architecture Explorer shows no trace of the lambda expression (while Visual Studio's code coverage, for example, shows them, as well as Code analysis seems to be able to understand that the link exists).

How would it be possible, without changing the source code, to:

Either force Architecture Explorer to display everything, including lambda expressions,

Or make it traverse lambda expressions while drawing a dependency through them (so in this case, drawing the dependency from GenerateHelloMessage to DefaultTemplateEngine in the second example)?

答:
A workaround would be to explicitly call the template engine method, replacing:

public string GenerateHelloMessage(string personName)
{
    return this.ApplyTemplate(
        (a, b) => this.DefaultTemplateEngine(a, b),
        this.GenerateLocalizedHelloTemplate(), personName);
}
```

<p>by:</p>

<pre class="lang-cs prettyprint-override"><code>public string GenerateHelloMessage(string personName)
{
    Func<string, string, string> engine = this.DefaultTemplateEngine;
    return this.ApplyTemplate(
        (a, b) => engine(a, b), this.GenerateLocalizedHelloTemplate(), personName);
}
</code>```

This change makes the code even more semantically identical; probably even compiler would inline engine variable in the last example to obtain the IL identical to the first example.

Still, this approach requires to change source code, which is unacceptable according to the question.

Body:
A workaround would be to explicitly call the template engine method, replacing:

public string GenerateHelloMessage(string personName)
{
    return this.ApplyTemplate(
        (a, b) => this.DefaultTemplateEngine(a, b),
        this.GenerateLocalizedHelloTemplate(), personName);
}

by:

public string GenerateHelloMessage(string personName)
{
    Func<string, string, string> engine = this.DefaultTemplateEngine;
    return this.ApplyTemplate(
        (a, b) => engine(a, b), this.GenerateLocalizedHelloTemplate(), personName);
}

This change makes the code even more semantically identical; probably even compiler would inline engine variable in the last example to obtain the IL identical to the first example.

Still, this approach requires to change source code, which is unacceptable according to the question.


答:
No it is not a good idea. Unless you are doing a very special job you don't need overriding framework main classes. Problem with rich frameworks i.g. .net and java is understanding the framework takes time based on the parts you mostly use. Only after that, frameworks reduce your work load. These frameworks are designed by top engineers so if you need to overwrite a lot of them, probably you don't know where the feature you are looking for is or how to implement it. I read somewhere time is like money:

You can spend it (doing something)

You can save it (using proper tools)

You can invest it (spending some of it now, to save much more later)

Title: Web Project Class Architecture

Body:
I think this is a good question for here but I'm not 100% sure. Please flag if it's too vague.

I've worked on many websites where common framework classes are overridden.

Since I work mostly in .net these days examples would include Page, Masterpage, UserControl, DbContext ect. I believe this could apply to any language though.

Sometimes I can see why it's done, I overrode entity framework's DbContext to include some logging code.

Allot of the time though I don't see why these base classes were created. Because I've inherited most of the sites I can't really ask why.

My question: Is it a good idea/practice when creating a new site to Override the common framework classes mentioned above? Would doing so be considered more of an old style?


问:
Business Objects - Containers or functional?
This is a question I asked a while back on SO, but it may get discussed better here...

Where I work, we've gone back and forth on this subject a number of times and are looking for a sanity check. Here's the question: Should Business Objects be data containers (more like DTOs) or should they also contain logic that can perform some functionality on that object.

Example - Take a customer object, it probably contains some common properties (Name, Id, etc), should that customer object also include functions (Save, Calc, etc.)?

One line of reasoning says separate the object from the functionality (single responsibility principal) and put the functionality in a Business Logic layer or object.

The other line of reasoning says, no, if I have a customer object I just want to call Customer.Save and be done with it. Why do I need to know about another class to save a customer if I'm consuming the object?

Our last two projects have had the objects separated from the functionality, but the debate has been raised again on a new project.

Which makes more sense and why??

答:
I think you're specifically talking about the difference between the ActiveRecord pattern and the Repository pattern.  In the former, the entities know how to persist themselves, and in the latter, the repository knows about persistence.  I think the latter offers a better separation of concerns.

In a broader sense, if the entities act more like a data structure, then they shouldn't have behaviors, but if they have behaviors, then they shouldn't be used like a data structure.  Example:

Data Structure:

```<code>class CustomerController
{
    public int MostRecentOrderLines(Customer customer)
    {
        var o = (from order in customer.Orders
                orderby order.OrderDate desc
                select order).First();
        return o.OrderLines.ToList().Count;
    }
}
</code>```

Non-Data Structure:

```<code>class Customer
{
    public int MostRecentOrderLines()
    {
        // ... same ...
    }
}
</code>```

In the first case, you can navigate the data structure tree of your model without a problem, from anywhere in your working code, and that's ok, because you're treating it like a data structure.  In the latter case, Customer is more like a service for a given customer, so you shouldn't call methods on the result.  All the things you want to know about the Customer should be available by calling a method on the Customer object.

So do you want your entities to be data structures or services?  For consistency, it seems better to stick with one.  In the former case, put your "service"-type logic somewhere else, not in the entity.

Body:
I think you're specifically talking about the difference between the ActiveRecord pattern and the Repository pattern.  In the former, the entities know how to persist themselves, and in the latter, the repository knows about persistence.  I think the latter offers a better separation of concerns.

In a broader sense, if the entities act more like a data structure, then they shouldn't have behaviors, but if they have behaviors, then they shouldn't be used like a data structure.  Example:

Data Structure:

class CustomerController
{
    public int MostRecentOrderLines(Customer customer)
    {
        var o = (from order in customer.Orders
                orderby order.OrderDate desc
                select order).First();
        return o.OrderLines.ToList().Count;
    }
}

Non-Data Structure:

class Customer
{
    public int MostRecentOrderLines()
    {
        // ... same ...
    }
}

In the first case, you can navigate the data structure tree of your model without a problem, from anywhere in your working code, and that's ok, because you're treating it like a data structure.  In the latter case, Customer is more like a service for a given customer, so you shouldn't call methods on the result.  All the things you want to know about the Customer should be available by calling a method on the Customer object.

So do you want your entities to be data structures or services?  For consistency, it seems better to stick with one.  In the former case, put your "service"-type logic somewhere else, not in the entity.


问:
Flow Chart - While Loops process
I'm having difficulties understanding whether or not this is the right process to use for a flow chart which illustrates the processes involved in an algorithm.

For this, assume the following:

A 1D X = [0, 1, 2, 3,........] data block is split into 2D blocks:

```<code>x = {[0 1]}
    {[2 3]}
</code>```

For each of these blocks, the total energy is counted, if the total energy is less than the threshold value the block is removed. If the energy is higher, then it is kept and the algorithm moves onto the next block.

Here's my flow-chart:

Now the way I look at this is that, I start the algorithm split the signal into frames, calculate the energy for each signal (2D) if the energy < theshold remove the frame AND THEN end the algorithm.

If the energy is higher than the threshold, then, it looks that the signal block (2D) is passed back into the algorithm, the energy for the signal is re-calculated.

My questions:-

1) Should there be a while loop that says "If at the end of the block"?

2) Should I specify that blocks of x[n][n] could be passed into the calculate energy?

Alternatively, does this look fine and I should apply some description of how the process works in written text?

Any help would be greatly appreciated :)

答:
Is the algorithm done once you remove one block that does not meet the threshold? If not, you need a loop that iterates over each block. You also need an exit condition if you have no blocks that fail to meet the threshold. Maybe something like this?

```<code>         Start
          |
          V
         Split signal
          |
          V
 /------ More blocks? <----\  <----\
 | (n)    |(y)             |       |
 V        V                |       |
End      Get next block    |       |
          |                |       |
          V                |       |
         Calculate         |       |
          |                |       |
          V                |       |
         Meets threshold? -/ (y)   |
          | (n)                    |
          V                        |
         Remove frame -------------/
</code>```

Note, I don't normally do flow charts for my day-to-day activities so forgive me if I'm off base here.

Title: Flow Chart - While Loops process

Body:
Is the algorithm done once you remove one block that does not meet the threshold? If not, you need a loop that iterates over each block. You also need an exit condition if you have no blocks that fail to meet the threshold. Maybe something like this?

         Start
          |
          V
         Split signal
          |
          V
 /------ More blocks? <----\  <----\
 | (n)    |(y)             |       |
 V        V                |       |
End      Get next block    |       |
          |                |       |
          V                |       |
         Calculate         |       |
          |                |       |
          V                |       |
         Meets threshold? -/ (y)   |
          | (n)                    |
          V                        |
         Remove frame -------------/

Note, I don't normally do flow charts for my day-to-day activities so forgive me if I'm off base here.


问:
Is NoSQL a good fit for a graphing app, and how can I compare different NoSql Servers?
I am traditionally a MsSQL or MySQL developer - I have been prototyping a new application that involves storing data from many targets.

I have seen that the app appears to get slow after scaling to 10k targets after inputting around 300k results for each (64 bit ints) - especially once I start trying to average and/or graph a few targets at once.

Once the app is deployed I will need to add around 1k targets a month and store one data point from each for each and every minute for approx 2 years.

I have never used NoSql, but from reading, it sounds like a good fit - create a document for each target and keep adding fields for each target.

So, I was just wondering, is NoSQL the way to go for this project or should I be sticking with traditional SQL - and/or can anyone offer any advice?

And the second part - If NoSQL is a solution can anyone recommend a fair comparison as I am getting lost in biased reviews that seem to say each solution is superior!?

答:
graph databases are sub category of NoSQL. I would recommend you to use a specialized DB for your app. from the description of your app I think any graph/key-value store will do the job.
it seems like your have written and tested your app on SQL, moving to noSQl will require you to rewrite/remodel your app. InfiniteGraph, Neo4j and FlockDB are good graph DBs backed my strong community. people from SQL background have complete paradigms shift when working with NOSQL solution, so for the first dive go for the easiest solution. im not the fan boy of any of these, mostly noSQL DBs are free and open source it woldnt take that long to try out few DBs.    </p>


问:
Test driven development - convince me!
I know some people are massive proponents of test driven development. I have used unit tests in the past, but only to test operations that can be tested easily or which I believe will quite possibly be correct. Complete or near complete code coverage sounds like it would take a lot of time.

What projects do you use test-driven development for? Do you only use it for projects above a certain size?

Should I be using it or not? Convince me!

答:
What? No negative answer!?

Disclaimer: I am not anti-unit-testing. When people say TDD, I assume they mean the disease-sounding version where they're writing tests before they write the code for 80-100% of all the code they write.

I would argue:

It's an enabler. If catching regression issues is such a huge problem for you that full-auto TDD from the start seems worthwhile, writing tests for every last piece of code you write, might actually help you ignore the real problem.

It helps people ignore the real problem. When fixing one bug turns into a game of whack-a-mole where two more pop-up, the architecture blows. Focus. Focus on the real problem. Seeing the moles before they must be whacked is neat-o but you shouldn't be there in the first place.

It eats a lot of time. I hit occasional bugs. I do not hit so many that it seems worthwhile to prefix every new thing I write with a test for it. Catch issues where they're likely to happen. Handle errors such that they are easy to diagnose. Validate. Test at key points of overlap/bottleneck. But for crying out loud don't test every last getter and setter in something that probably shouldn't have had those in the first place.

Design Focus: There is absolutely no way even a good developer is going to write the best code they could when they are also focusing on the test. If it seems like the only way you can have a decent design, I'd recommend seeing the above about "focusing on the real problem."

Macro-Design Fail: The codebase at my current job is riddled with interfaces that never get used more than once and massive violations of basic DRY principle that I only finally started to understand when I realized people were writing for the test-frameworks and testing in general. Testing should not lead to stupid architecture. No really, there is nothing that is somehow more scalable or enterprise-worthy about copying and pasting 20 files and then only making significant changes to two of them. The idea is to separate concerns, not split them down the middle. Cruft and pointless abstraction will cost you more than not have 95% coverage ever will.

It's really popular and lots of people really, really like it. If that's not reason enough to at least second-guess and/or vet the crap out of any technology before adoption, learn you some paranoia.

Title: Test driven development - convince me!


问:
What problem domain is LINQ made for?
Each time I see a question posted on Stack Overflow on C#, I see at least one or two answers posted that solve a problem with LINQ. Usually people with very high reputation seem to use LINQ like pros.

So my question is, what problem domain is LINQ supposed to be used for?

Also on side notes: Are there any purposes in which it should be avoided? Does the size of dataset affect the performance of LINQ queries?

答: Different languages have been developed over time for the various types of data sources, for example SQL for relational databases and XQuery for XML. Therefore, developers have had to learn a new query language for each type of data source or data format that they must support. LINQ simplifies this situation by offering a consistent model for working with data across various kinds of data sources and formats. In a LINQ query, you are always working with objects.  for more visit http://msdn.microsoft.com/en-us/library/bb397906.aspx</p>

Title: What problem domain is LINQ made for?