问:
Better to write your .NET library with COM limitations in mind, or separate your .NET library from Interop?
I came across this interesting article: How I Came to Love COM Interoperability on CodeProject, which got me thinking...

The author argues that they do not want any COM-ities in their .NET library because it takes away from the beauty of their .NET library. Instead, they'd rather write a separate Interop library that exposes their .NET library to COM. This Interop library would handle the fact that COM doesn't support Constructors with Parameters, Overloaded Methods, Generics, Inheritance, Static Methods, etc.

And while I think that is very novel, doesn't it just complect the project?

Now you need to unit test your .NET library AND an Interop library.

Now you need to spend time figuring out how to work around your beautiful .NET library and expose it to COM.

You need to, effectively, double or triple your class count.

I can certainly understand if you need your library to support both COM and non-COM. However, if you only intend to use COM does this sort of design bring any benefits that I don't see? Do you only gain the benefits of the C# language?

Or, does it make versioning your library easier by providing you a wrapper? Does it make your Unit Tests run faster by not requiring the use of COM?

答:
it takes away from the beauty of their .NET library

That author needs a wake-up slap to the face. For any professional project, the goal is to make working software that people want to use. Any kind of misguided ideals about beauty come long after that. If that's their only reasoning, the author has lost all credibility.

Being able to mark your classes as com-visible and being able to talk to your .NET code through COM is enormously useful. Discarding that great benefit to productivity for beauty is insane.

However, making things work with COM does require some trade-offs, requiring a no-arg constructor is one of them, and some of the other stuff you mentioned. If those are features you aren't using anyway, or it won't hurt you to not use them, then there is a lot of work to be saved by using the same class for COM and non com.

On the other hand, if your COM clients expect a dramatically different interface, has dependencies or other limitations that are nasty to deal with in your .NET classes, or you expect to be significantly changing your .NET classes and need to maintain COM backward-compatibility, then by all means create an Interop class to bridge that gap.

But don't think about "beauty". Being able to expose COM through .NET is meant to save you work. Don't create more work for yourself.


问:
Alternative to goto-statement in this case?
Currently I am using gotos for closing handles and general cleanup if an error occurs.

Since I don't want to nest all the ifs and a function for cleanup would require a return besides the cleanup(); call, I don't have any good ideas left.

The structure is like so:

```<code>if (condition1) {
   goto cleanup;
}

if (condition2) {
   goto cleanup;
}

if (condition3) {
   goto cleanup;
}

// do stuff only if all checks passed

cleanup:
CloseHandle(x);
CloseHandle(y);
// etc.
</code>```

答:
You could try saying what you mean:

```<code>if (!condition1
 && !condition2
 && !condition3 ) {

// do stuff only if all checks passed
}
CloseHandle(x);
CloseHandle(y);
// etc.
</code>```

As various commenters have pointed out this is only readable/maintaibable if the condition tests are fairly simple where complex conditions are involved something like this is cleaner:-

```<code>if (doAble()) {
   // usefull work here
}
CloseHandle(x);
CloseHandle(y);

boolean doAble() {
  if (condition1) {
     return false;
  }
  if (condition2) {
     return false;
  }
  if (condition3) {
     return false;
  }
  return true;
}
</code>```

However if you need lots of local variables to evaluate the conditions this too can get messy.

ContentLicense: CC BY-SA 3.0

Body:
You could try saying what you mean:

if (!condition1
 && !condition2
 && !condition3 ) {

// do stuff only if all checks passed
}
CloseHandle(x);
CloseHandle(y);
// etc.

As various commenters have pointed out this is only readable/maintaibable if the condition tests are fairly simple where complex conditions are involved something like this is cleaner:-

if (doAble()) {
   // usefull work here
}
CloseHandle(x);
CloseHandle(y);

boolean doAble() {
  if (condition1) {
     return false;
  }
  if (condition2) {
     return false;
  }
  if (condition3) {
     return false;
  }
  return true;
}

However if you need lots of local variables to evaluate the conditions this too can get messy.


问:
What are the real benefits of static code analysis?
Tools like pc-lint or QAC can be used to perform static code analysis on a code base.

In my experience the static analysis often yields a huge amount of noise, i.e. warnings on things that are not real bugs but somehow violate one of the rules in a given rule set. Turning off certain rules (either for good in the rule set or via special comments in the code) can be a real cumbersome process.

What are the real benefits of static code analysis?

答:
Because of the high false positive rate, you should not be using a static analysis tool (like lint or FindBugs) for each compilation.

Rather, it's a nice sanity check to consult once you have a bug and can't figure it out. In that case, you can entertain the false positives, and you may have already narrowed down the possible sources of the error. For example, if you reproduce your bug without even executing some module, you can ignore what FindBugs says for them. This is particularly helpful when you are looking at a piece of code and think it says one thing, whereas the compiler reads it literally (such as in Java when you have an equals method that takes in the type of the class instead of Object).

You can also have static analysis tools be a part of your development process: When a developer gets a code review, they should also run FindBugs on it. In short, it's useful, but you won't use it as often as the compiler or the text editor.

ContentLicense: CC BY-SA 2.5


问:
Is there a reason to have a bottom type in a programming language?
A bottom type is a construct primarily appearing in mathematical type theory. It is also called the empty type. It is a type that has no values, but is a subtype of all types.

If a function's return type is the bottom type, that means that it does not return. Period. Maybe it loops forever, or maybe it throws an exception.

What is the point of having this weird type in a programming language? It's not that common, but it is present in some, such as Scala and Lisp.

答:
Types form a monoid in two ways, together making a semiring. That's what's called algebraic data types. For finite types, this semiring directly relates to the semiring of natural numbers (including zero), which means you count how many possible values the type has (excluding “nonterminating values”).

The bottom type (I'll call it Vacuous) has zero values†.

The unit type has one value. I'll call both the type and its single value ().

Composition (which most programming languages support quite directly, through records / structs / classes with public fields) is a product operation. For instance, (Bool, Bool) has four possible values, namely (False,False), (False,True), (True,False) and (True,True).
 The unit type is the identity element of the composition operation. E.g. ((), False) and ((), True) are the only values of type ((), Bool), so this type is isomorphic to Bool itself.

Alternative types are somewhat neglected in most languages (OO languages kind-of support them with inheritance), but they are no less useful. An alternative between two types A and B basically has all the values of A, plus all the values of B, hence sum type. For instance, Either () Bool has three values, I'll call them Left (), Right False and Right True.
The bottom type is the identity element of the sum: Either Vacuous A has only values of the form Right a, because Left ... doesn't make sense (Vacuous has no values).

What's interesting about these monoids is that, when you introduce functions to your language, the category of these types with the functions as morphisms is a monoidal category. Amongst other things, this allows you to define applicative functors and monads, which turn out to be an excellent abstraction for general computations (possibly involving side-effects etc.) within otherwise purely functional terms.

Now, actually you can get quite far with worrying only one side of the issue (the composition monoid), then you don't really need the bottom type explicitly. For instance, even Haskell did for a long time not have a standard bottom type. Now it has, it's called Void.

But when you consider the full picture, as a bicartesian closed category, then the type system is actually equivalent to the whole lambda calculus, so basically you have the perfect abstraction over everything possible in a Turing-complete language. Great for embedded domain-specific languages, for instance there's a project about directly coding electronic circuits this way.

Of course, you may well say that this is all theoretists' general nonsense. You don't need to know about category theory at all to be a good programmer, but when you do, it gives you powerful and ridiculously general ways to reason about code, and proove invariants.

†mb21 reminds me to note that this should not be confused with bottom values. In lazy languages like Haskell, every type contains a bottom “value”, denoted ⊥. This isn't a concrete thing that you could ever explicitly pass around, instead it's what's “returned” for example when a function loops forever. Even Haskell's Void type “contains” the bottom value, thus the name. In that light, Haskell's bottom type really has one value and its unit type has two values, but in category-theory discussion this is generally ignored.

ContentLicense: CC BY-SA 4.0


问:
How to write tests for function that depends on a config file?
I have a function that uses information from a config file. How do I test the function? Ideally, I'd want to inject my own version of the config file and test from there, but I'm not using dependency injection.</p>

答:
Well, dependency injection comes to mind as a default sort of boxed approach to config testing.

However, there are other ways, specifically designing your code to eliminate the dependency on config file all together.

You can find more details in a canonical example of dependency elimination by Brian Geihsler that talks specifically about config files.


问:
why are globals bad in javascript
I've been writing web applications for a while now , and everyone knows the one golden rule not to assign variables to the window object , don't ever assign a variable without using var.

My question is, why not? In my opinion it is a lot easier especially nice in SPA's to attach objects to the global scope when you have many different scopes in different modules for different modal views if you want to share data.

Now, lets just assume for the sake of this question that I will never ever have the problem of accidentally overriding global variables, meaning - I will take the responsibility to make sure I have very good names and they will never overlap.  If you take that into consideration , then I can't see any other reason why global variables are just bad practice.

答:
Because global variables have global scope, they are visible, and mutable, by anything that runs on the page. That introduces implicit coupling between all code running on the page; everything could interact with everything.

That runs contrary to the concept of encapsulation. If your code and variables are local in scope, it's easier to reason about things; only those parts of the code that can access the variable may have changed it.

When it comes to variables attached to the window object, you never know where they have been, or who has touched them.

Title: why are globals bad in javascript


问:
Is storing data directly in a list node better than storing a pointer to data?
Suppose we have two different doubly-linked list structures:

One has content of the node embedded directly in the node:

```<code>struct Content {
    // some stuff
};
struct Node {
    struct Node *next;
    struct Node *prev;
    struct Content content;
}
</code>```

The other has a pointer to content:

```<code>struct Content;
struct Node {
    struct Node *next;
    struct Node *prev;
    struct Content *content;
}
</code>```

What are considerations to prefer one option to the other? The points can be about everything: performance in different conditions, architecture, ease of modification, ease of manipulating the list, etc.

I'd like to gather knowledge about the trade-offs present.

Shown code is C, but the question also applies to C++, or any other language which has explicit pointers.

答:
It depends on the contents of the Context structure. If it contains less data than is the size of a pointer on your architecture, then the memory is wasted, because the size of the pointer + payload is more than twice as large as the payload itself.

Another problem might be memory access. When you access the data through a pointer, memory has to be read twice, first to retrieve the location and once more to get the actual data. Since it can be stored anywhere in memory, it is unlikely that it got cached with the node itself. However if you worry about performance you shouldn't be using lists in the first place.

If you have a larger context structure, which it is not created at the same time, or for any other reason can't be created with the node itself then the pointers are superior, because you don't have to copy all the data to the node. In any other case it doesn't really matter, because most common operations on lists like sorting, inserting, removing, only modify the next and previous pointers, not the actual data.


答:
For a few reasons:

It often forces you to choose longer names, where a shorter one would be more clear and concise within a limited scope.  For example, filter versus MyModuleNameFilter.

The process of "taking the responsibility to make sure you have very good names and they will never overlap" gets increasingly difficult the larger your code base gets (and the older you get for that matter).

You are unable to share code with anyone else who subscribes to the same philosophy.

Title: why are globals bad in javascript

Body:
I've been writing web applications for a while now , and everyone knows the one golden rule not to assign variables to the window object , don't ever assign a variable without using var.

My question is, why not? In my opinion it is a lot easier especially nice in SPA's to attach objects to the global scope when you have many different scopes in different modules for different modal views if you want to share data.

Now, lets just assume for the sake of this question that I will never ever have the problem of accidentally overriding global variables, meaning - I will take the responsibility to make sure I have very good names and they will never overlap.  If you take that into consideration , then I can't see any other reason why global variables are just bad practice.


答:
"Never put variables in global scope" is a best practice because it makes those variables brittle. A typical web page or especially a typical web application is likely to contain many different scripts from multiple sources, and as careful as you may be to track your own global variables, everyone else whose scripts you're referencing may not be playing along.

Think of it like vaccines. If everyone had a vaccine, there'd be no threat, and if you alone have a vaccine there's no threat, but meanwhile everyone else is trying to get vaccinated, so you could probably get away with not being vaccinated because no one else is your threat, but that's just not playing nicely with the scripting ecosystem you're working in.

There is some latitude with using globals if you namespace. The root of your namespace is a global, but you're allowed only the one namespace root variable. That's a compromise that the Javascript community is usually okay with, particularly if it is limited to your application.

A namespace might look like this:

```<code>window.MyNamespace = {
    ClassA: function() { },
    NestedNamespace1: {
        ClassB: function() { }
    }
};
</code>```

This puts ClassA and ClassB in the nesting of the MyNamespace namespace:

```<code>(function() {
    var myClassAInstance = new MyNamespace.ClassA();
    var myClassBInstance = new MyNamesapce.NestedNamespace1.ClassB();
})();
</code>```

You can also build it up using namespacing functions like the one I created [here], which also explains further how you can take advantage of the simplicity of namespacing.

Generally, however, the recommendation is to use closure variables everywhere. Namespaces are a minimum, but discouraged because of the benefits of closure variables. A closure variable is a variable declared within the execution of a function. All script files that you write should be contained within a function.

```<code>(function() { // IIFE (immediately-invoked function expression)

   var myClosureVariable = 3;
   $('#myDomElement').on('click', function() {
       console.log(myClosureVariable); // outputs 3
   });

})();
console.log(myClosureVariable); // outputs undefined
</code>```

Title: why are globals bad in javascript

Body:
"Never put variables in global scope" is a best practice because it makes those variables brittle. A typical web page or especially a typical web application is likely to contain many different scripts from multiple sources, and as careful as you may be to track your own global variables, everyone else whose scripts you're referencing may not be playing along.

Think of it like vaccines. If everyone had a vaccine, there'd be no threat, and if you alone have a vaccine there's no threat, but meanwhile everyone else is trying to get vaccinated, so you could probably get away with not being vaccinated because no one else is your threat, but that's just not playing nicely with the scripting ecosystem you're working in.

There is some latitude with using globals if you namespace. The root of your namespace is a global, but you're allowed only the one namespace root variable. That's a compromise that the Javascript community is usually okay with, particularly if it is limited to your application.

A namespace might look like this:

window.MyNamespace = {
    ClassA: function() { },
    NestedNamespace1: {
        ClassB: function() { }
    }
};

This puts ClassA and ClassB in the nesting of the MyNamespace namespace:

(function() {
    var myClassAInstance = new MyNamespace.ClassA();
    var myClassBInstance = new MyNamesapce.NestedNamespace1.ClassB();
})();

You can also build it up using namespacing functions like the one I created [here], which also explains further how you can take advantage of the simplicity of namespacing.

Generally, however, the recommendation is to use closure variables everywhere. Namespaces are a minimum, but discouraged because of the benefits of closure variables. A closure variable is a variable declared within the execution of a function. All script files that you write should be contained within a function.

(function() { // IIFE (immediately-invoked function expression)

   var myClosureVariable = 3;
   $('#myDomElement').on('click', function() {
       console.log(myClosureVariable); // outputs 3
   });

})();
console.log(myClosureVariable); // outputs undefined


答:
"I will take the responsibility to make sure...".

Many unexpected babies arrive that way.

But seriously:

keeping names unique with a growing code base that may include other libraries is a difficult and risky process that is ultimately doomed to failure.

your very own code will start to get really hard to read and follow when you set and read these variables in different places.  When it comes to a given section of code, you may not be sure of the value of the variable and that can be a problem.

variable naming should be based on a good name for the method, not on what names you have already

common names should be repeatable.  It should be ok to have names such as 'filter','create','new','index','search', etc. in multiple places.  Without namespacing of some kind you can only have these functions once.

Title: why are globals bad in javascript


问:
Is there a modified LGPL license that allows static linking?
LGPL requires that it if a program uses LGPL-ed library, users must be able to re-link the program with a different version of the library:

...

d) Do one of the following:

0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.

1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.

...

However in some cases, this can pose considerable difficulties. In particular, Haskell programs are almost always statically compiled. Moreover, the compiler does cross-module optimizations so its not possible to take a part of the code out and replace it with another. So it's very hard to satisfy this condition. (See this link at Haskell Wiki.)

Dynamic linking would be a solution, but in many cases, this isn't possible. For example:

Some platforms may not have dynamic linking at all.

Some languages don't have the possibility of dynamic linking. Or, it's not possible to make modules multi-platform.

In some cases dynamic linking would prevent important optimizations. While I'd say this is rarely a serious problem, in languages like Haskell the performance loss could be considerable.

Therefore, I'm looking for a standard LGPL-like license that wouldn't require the possibility of re-linking (and I understand that that removes a bit of freedom given to users). Some projects use their own modification of LGPL, for example wxWidgets. But I'd rather use some standard license that is somewhat more official, perhaps checked by some law experts, and (L)GPL compatible. Is there some like that?

(Also I'd be interested to know if are there some unforeseen consequences of such a modification of LGPL.)

答:
I'm surprised nobody's mentioned the Mozilla Public License. It's similar to the LGPL except it allows static linking. MPL version 2 is compatible with the GPL/LGPL.

Mozilla Public License (MPL 2.0) vs Lesser GNU General Public License (LGPL 3.0)


问:
Abstract classes and constants
I have two classes that share a lot of code and are conceptually variations on a common class. So I want an abstract class that contains all their common code and then they can each inherit from it and fill in the stuff unique to them. However I am running into a problem with constants and static methods. Basically, the relationship I have is like this:

Class A and Class B both have some methods that don't depend on an instance of the class, just the value of a set of constant strings. Basically as such:

```<code>const string onePrefix;
const string differentPrefix;

static string ConvertMethod(string input)
{
  input.replace(onePrefix, differentPrefix);
}
</code>```

The method code is the same between the two classes, so I would like to have it in the abstract class. But the actual values of the two constants are different between the two classes. But abstract constants are not a thing you can do as far as I can tell so I'm not sure how to go about structuring my classes to make this work like I want it to. I've considered just not having the values be constants, but they are used in my constructors before an instanced object is created.

答:
It's a bit of a code smell to me that you have a constant that you want to share polymorphically between two classes so that they can define it on their own.

Constants by design have been made to be unaffected by polymorphism so I would suggest you turn that into an abstract property in your abstract base class.

You could either do that or have a concrete class as your supertype. Then inherit all the common functionality from your concrete class while having your constants defined on each subclass which you can access when you new them up.

Title: Abstract classes and constants


问:
Multiple method calls in the constructor and dependency injection
I was asked to refactor some almost ureadable spaghetti code into object-oriented architecture.

I have some doubts regarding a class that I designed. Here is the class' skeleton:

```<code>require_once 'inc/FeaturedCarousel/Carousel.php';
class FeaturedCarousel
{
    private $currentCategory;
    private $allFeaturedAdvertisers = array();
    private $metaData = array();
    private $featuredAdvertisersIds = array();
    private $dataForDisplay = array();

    public function __construct($currentCategory)
    {
        $this->currentCategory = $currentCategory;
        $this->getAllFeaturedAdvertisers();
        $this->getAllAdvertisersMetaData();
        $this->getFeaturedAdvertisersInCurrentCategory();
        $this->getDataForDisplay();
    }

    private function getAllFeaturedAdvertisers()
    {
    }

    private function getAllAdvertisersMetaData()
    {
    }

    private function getFeaturedAdvertisersInCurrentCategory()
    {
    }

    private function getDataForDisplay()
    {
    }

    public function displayCarousel()
    {
        new FeaturedCarousel\Carousel($this->dataForDisplay);
    }
}
</code>```

The class is initiated like this:

```<code>$carousel = new FeaturedCarousel($currentCategory);
$carousel->displayCarousel();
</code>```

The class' role is to prepare data for display, and then display it using an external Carousel class that is instantiated in the displayCarousel() method.

There may be major aspects of it that should refactored. Please note that I have already implemented all the methods so there is no need to focus on their implementation.

Here are my questions -

All methods required to generate data for display are trigerred one by one in the constructor. Each of these methods generates a private property required by the method called next. Therefore, if any of the methods fails, there is really no point in calling subsequent methods. How should I  address those possible method failures?

The displayCarousel() method instantiates another class that is responsible for the actual rendering of HTML content. At the moment the Carousel class is just required and instantiated in the method call. Should the Carousel class be 'injected' into my class before it is used?

答:
if any of the methods fails, there is really no point in calling subsequent methods. How should I address those possible method failures?

Throw an exception.

Should the Carousel class be 'injected' into my class before it is used?

Yes, if there is more than one implementation of Carousel (including the possibility of a mock object for unit testing purposes).  Then you will inject an ICarousel.


问:
Is this Wikipedia pseudocode for in-order generic tree traversal correct?
Wikipedia states that the following algorithm works for any tree (not necessarily binary trees)

Perform pre-order operation

For each i (with i = 1 to n) do:

Visit i-th, if present

Perform in-order operation

Perform post-order operation

where n is the number of child nodes.

The pre-order and post-order parts make sense. The in-order one does not make sense to me however. By performing this algorithm I would perform the in-order operation on the same node several times. Basically, if I have a node with 5 child nodes, then I will perform the in-order operation on the node 5 times, once after visiting each child node. This does not make sense to me. Isn't a tree traversal supposed to go through each node once?

Actually, does an in-order traversal even make sense for generic trees? Doesn't it only apply to binary trees, or trees where the "order" is not ambiguous?

答:
In the algorithm you provided, although it is true that the same in-order operation is performed in the same node multiple times, it is still ran once for each node and each node is visited only once.

Note that this isn't a "in-order" tree traversal, you can't make such a traversal on a ntree, it just doesn't make sense. This is simply a deep-first traversal and the in-order operation is something that is ran after the node has been visited. It has nothing to do with the "in-order functions" that are mentioned elsewhere in on the page.

Maybe I should add, visit is the recursive call in this case, not the in-order operation.


问:
Can the GitHub pull request process constitute an electronic signature of a CLA?
I appreciate the need for a Contributor License Agreement (CLA) in open source software projects and even understand that some tools are starting to make this process easier (like the low-friction CLAHub for GitHub and Project Harmony). However, rather than requiring a third-party form submission for an electronic signature, would adding an extra sentence and the CLA itself to CONTRIBUTING.md, which GitHub links to when a contributor files a pull request (displayed as "Please review the guideline for contributing to this repository"), allow for a valid electronic signature (e.g. "Submitting a pull request to this repository on GitHub with your name and email constitutes your agreement to and electronic signature of the following Contributor License Agreement...")? Perhaps that argument hinges on the definition of "electronic signature" (ESIGN, UETA, etc.):

"Electronic signature" means an electronic sound, symbol, or process attached to or logically associated with a record and executed or adopted by a person with the intent to sign the record.

And I would like to propose that the GitHub pull request "process" is "logically associated" with the CONTRIBUTING.md/CLA "record" and that the contributor has the "intent to sign" by adopting the process...

(Since the Open Source Licensing Q&A site is still a just a proposal, I will accept IANAL answers here.)

答: No. You need to have contributors explicitly sign a CLA, as GitHub themselves do.


问:
Is it OK for an MVC view to request data from other sources than just the model?
I'm working in ASP.NET MVC, but this question is pretty much applicable to any MVC framework (and maybe even others).

In a typical MVC application a request arrives at the controller, which then prepares a model object and then calls the view, passing the model object as a parameter. The view then uses the data in the model to generate a response to the original request. Any data in thew model object can be freely used by the view, but I'm wondering - is it OK for a view to request data from elsewhere, like a direct call to a service or something?

At the first moment the answer seems to be a clear "no, why would you need that? Just add everything the view needs to the model object". But I did arrive at this question while working on a practical project, so here's my situation that causes me doubt:

The view needs a lot of data to be able to display itself. Most notably, there is the data of the actual form fields, and also data for all the dropdowns that are on the form (lists of potential values for different fields).

On the other hand, in my project the views are themeable. That is, different customers (our customers, who have bought our website and use it in their business) will have the views customized to suit their needs. Different customers need different fields displayed, and sometimes the data sources for the same dropdown can differ significantly as well.

One possible way would be to query all possible data on every request and add it all to the model object. But there will be a significant performance penalty for this. Better if only the necessary data was queried, however the controller doesn't know what the view will need.

So I see 2 options:

Allow the view to call external functions that return the value lists for the dropdowns;

In the model object, add delegates (or actually add methods to the model object) which will perform the query when the view asks it to.

Neither approach seems very elegant to me. Are there any other alternatives, or if not, which one is better and why?

答:
Obtain the external data in the controller method, and pass the data to the view there.

If you need more finesse, write a repository, service layer or data context that contains the needed data retrieval methods.

Any customization or view switching can also take place in the controller, using helper objects or methods as needed.

The view should only be as smart as necessary to display the data.  If the view needs to obtain data in real-time, it can do that by calling a controller method via AJAX.


问:
Entity Framework Code First Centralized database deployment
I originally posted this on stack overflow but was told that here is a better place to ask this kinda stuff. I couldn't find any other similar answered question but if there is one please give me a link.

I am developing a software which uses a database that is hosted on a main server(MSSQL). Multiple clients can be connected to the same server at any given time. I am using Entity Framework with the Code-First approach.

My concern is how the database is going to be deployed and later updated. Since we are talking about a centralized database, automatic database migration being performed by any of the clients is out of the question in my opinion. I have been thinking of using a separate server configuration app that is going to connect to the server(database) and perform database creation(first time only) and migration when needed.

Also the reason why I think automatic database migration cannot work in my case is because whenever a client is run, it will check if it there is a migration available for the database and if there is, it is going to apply it. That, though, might result in problems for other clients which haven't been updated yet. That is why I think there should be a configuration app that updates the database independently of any of the clients.

Do you think this is a good way to solve the problem or is there a better one?

答:
Hey I know it has been a while since I posted this, but I noticed there are people still interested in the answer so I thought I should update with what I chose to go with.

I decided to use a self-hosted WCF service that clients connect to and get their data from. The service is responsible for database creation and migration and also notifies clients if they need to update in order to be able to connect.

I think this is the best solution for my case.


问:
Objects or primitives as arguments
I have come across the term "garbage disposal" and now I'm worried about using up too much memory. Apparently (correct me if I'm wrong) every time an object is created, memory is reserved for it, and that object must be properly disposed of if not needed anymore.
My question is if one should avoid instantiating objects then whenever possible. For example, if a function requires a coordinate as arguments, should I have

```<code>example(int x,int y)
</code>```

or is it okay to have

```<code>example(Point p)
</code>```

and during the actual call I do something like

```<code>example(new Point(5,5));
</code>```

I'm worried about not slowing down the application, so I would like to know if having primitives as arguments is better than having objects which will usually be instantiated on the spot

答:
It really depends upon the programming language, and the implementation. Read also Scott's book on Programming Language Pragmatics.

Read the wikipage on garbage collection (GC). GC can be quite efficient, read A.Appel old's paper: Garbage Collection Can be Faster than Stack Allocation and for a good overview the GC handbook

Some programming languages, like C, don't even have any objects, and require manual memory management, read more about C dynamic memory allocation.

C++ is slightly better, notably because it has programming idioms like RAII and because of its destructors (implicitly called at end of block).

Java is compiled to JVM bytecode which generally has quite a good GC.

Functional languages like Ocaml, SML, Haskell, Common Lisp implementations (and most JVMs) usually have good generational GC which handles differently fresh values or objects and older ones.

When coding, favor readable and maintainable code and efficient algorithms. Remember the adage that premature optimization is evil (the compiler is optimizing quite well, and could even optimize example(new Point(x,y)) as example(x,y) in some cases). If you really care, profile and benchmark your application then put your recoding efforts on small hot spots. Don't worry!

Title: Objects or primitives as arguments


答:
now I'm worried about using up too much memory

You are not talking about a real program, just some "feeling" your programs might use up too much memory? Why? Ask this question when you have a written a program which uses too much memory, not beforehand.

My question is if one should avoid instantiating objects then whenever possible

Short answer: no, not "whenever possible", not "most times", maybe "in some rare cases". The decision to create classes and objects should be guided first and almost by the question if they form proper abstractions for your task or algorithm. Performance or memory optimizations on that level you have in mind should be done when needed, never beforehand.

should I have example(int x,int y) or is it okay to have example(Point p)

Actually, that example might be a little bit misleading, since it will lead to calls

```<code> example(new Point(5,5))
</code>```

vs.

```<code> example(5,5)
</code>```

and the latter one looks more readable than the first on a first glance. In a real world program, however, you will probably not have to write something like example(new Point(5,5)) too often, instead you have to process a set of points in a way like this:

```<code>foreach(Point p in setOfPoints)
   example(p);
</code>```

which is more comprehensive than example(p.X,p.Y). And if you have really lots of calls with hard-encoded literals like example(new Point(5,5)), you could provide both example variants as some syntactic sugar. Note that the primary question here is "what makes the program more readable?", not "does this make a slight difference in memory usage on a micro scale level?".

Imagine what happens if you have lots of functions with more than one Point parameter, like

```<code> bool doPointsFormATriangle(Point p1, Point p2, point p3)
</code>```

vs

```<code> bool doPointsFormATriangle(double x1, double y1, double x2, double y2,double x3, double y3)
</code>```

you get twice the number of parameters in the second case, and readability of calls to that function decreases by the same factor of two.

Indeed, where I work, I still have to maintain some older programs which were written by a beginners guy some years ago in the style like the second doPointsFormATriangle, with hundreds of function calls passing all 3D points as primitive coordinates. From that experience I can tell you its horrible - so do yourself a favor and avoid that style.

Title: Objects or primitives as arguments

Body:
I have come across the term "garbage disposal" and now I'm worried about using up too much memory. Apparently (correct me if I'm wrong) every time an object is created, memory is reserved for it, and that object must be properly disposed of if not needed anymore.
My question is if one should avoid instantiating objects then whenever possible. For example, if a function requires a coordinate as arguments, should I have

```<code>example(int x,int y)
</code>```

or is it okay to have

```<code>example(Point p)
</code>```

and during the actual call I do something like

```<code>example(new Point(5,5));
</code>```

I'm worried about not slowing down the application, so I would like to know if having primitives as arguments is better than having objects which will usually be instantiated on the spot

Body:
now I'm worried about using up too much memory

You are not talking about a real program, just some "feeling" your programs might use up too much memory? Why? Ask this question when you have a written a program which uses too much memory, not beforehand.

My question is if one should avoid instantiating objects then whenever possible

Short answer: no, not "whenever possible", not "most times", maybe "in some rare cases". The decision to create classes and objects should be guided first and almost by the question if they form proper abstractions for your task or algorithm. Performance or memory optimizations on that level you have in mind should be done when needed, never beforehand.

should I have example(int x,int y) or is it okay to have example(Point p)

Actually, that example might be a little bit misleading, since it will lead to calls

 example(new Point(5,5))

vs.

 example(5,5)

and the latter one looks more readable than the first on a first glance. In a real world program, however, you will probably not have to write something like example(new Point(5,5)) too often, instead you have to process a set of points in a way like this:

foreach(Point p in setOfPoints)
   example(p);

which is more comprehensive than example(p.X,p.Y). And if you have really lots of calls with hard-encoded literals like example(new Point(5,5)), you could provide both example variants as some syntactic sugar. Note that the primary question here is "what makes the program more readable?", not "does this make a slight difference in memory usage on a micro scale level?".

Imagine what happens if you have lots of functions with more than one Point parameter, like

 bool doPointsFormATriangle(Point p1, Point p2, point p3)

vs

 bool doPointsFormATriangle(double x1, double y1, double x2, double y2,double x3, double y3)

you get twice the number of parameters in the second case, and readability of calls to that function decreases by the same factor of two.

Indeed, where I work, I still have to maintain some older programs which were written by a beginners guy some years ago in the style like the second doPointsFormATriangle, with hundreds of function calls passing all 3D points as primitive coordinates. From that experience I can tell you its horrible - so do yourself a favor and avoid that style.


答: OK, I guess I figured out the answer to my own question. If I want to go down this road, I need to provide meta-information together with the selected theme. The controllers can then look at this meta-information to adjust their own behavior.</p>

Title: Is it OK for an MVC view to request data from other sources than just the model?

Body:
I'm working in ASP.NET MVC, but this question is pretty much applicable to any MVC framework (and maybe even others).

In a typical MVC application a request arrives at the controller, which then prepares a model object and then calls the view, passing the model object as a parameter. The view then uses the data in the model to generate a response to the original request. Any data in thew model object can be freely used by the view, but I'm wondering - is it OK for a view to request data from elsewhere, like a direct call to a service or something?

At the first moment the answer seems to be a clear "no, why would you need that? Just add everything the view needs to the model object". But I did arrive at this question while working on a practical project, so here's my situation that causes me doubt:

The view needs a lot of data to be able to display itself. Most notably, there is the data of the actual form fields, and also data for all the dropdowns that are on the form (lists of potential values for different fields).

On the other hand, in my project the views are themeable. That is, different customers (our customers, who have bought our website and use it in their business) will have the views customized to suit their needs. Different customers need different fields displayed, and sometimes the data sources for the same dropdown can differ significantly as well.

One possible way would be to query all possible data on every request and add it all to the model object. But there will be a significant performance penalty for this. Better if only the necessary data was queried, however the controller doesn't know what the view will need.

So I see 2 options:

Allow the view to call external functions that return the value lists for the dropdowns;

In the model object, add delegates (or actually add methods to the model object) which will perform the query when the view asks it to.

Neither approach seems very elegant to me. Are there any other alternatives, or if not, which one is better and why?


问:
How would a one man team benefit from a continous integration setup?
I am a one man team. I develop an in house database, and the web interface.

My current workflow is code on my development machine. Test.

Push to a central git server.

Log into the production server pull the changes over. Restart the production server.

It's Python based. I tried setting up Fabric one time, but I felt it was a fair bit of setup, and I didn't really gain anything, as such I didn't end up using it.

Would someone like to convince me otherwise? (Or agree).

On a side note, is Hudson/ Jenkins doing the same job as Fabric? Or are these for different purposes. Am I misunderstanding the concepts?

答:
Fabric is a deployment tool, not a CI server. Jenkins is and its awesome. Its basically a glorified script-runner that's integrated into your SCM (with lots of extras), so it looks at your SCM and runs scripts when commits are made. One of those scripts will be to deploy automatically.

A CI server is basically an automated way of performing half the tasks you did manually. Instead of logging into the production server, pulling the changes and restarting it, Jenkins can do it instead. (However, production sounds warning bells to me, you really want to do this to a QA server to test again and make sure its right before copying to production as a manually-invoked controlled process).

Still, if a CI server is set up to deploy from a know position on your SCM (eg latest from trunk) then you just have to commit changes - and after a short while, its on your QA server. If you had a test team, you might set this up to deploy overnight so they could come in and begin testing against latest code without having to worry about getting the latest deployed.

CI servers are also used to build (might not be applicable to you), run static analysis tools (always a good idea) and run tests scripts.

One thing that might be worrying if the push-pull nature of your work. You should be working on a branch, then merge that to master when its ready. Your CI server should be watching master so you can work as much as you like on your branch before hitting the 'merge which triggers all the deployments' button.


问:
Test logic with external data
I have a site programmed in PHP where I make more call to external server that return me big xml of data.
For each record of the xml I have to make other external call to get other data.

So my function logic is:

1) make external request in XML

2) get the response XML

3) for each record of the XML make another external request in XML

So there are three functions to get all data for my page.
In theory to make good tests I need to create a test for each function, but the problem is that every function is linked with the other function because I need record data to make the last function.

So is correct to create a big test that include all functions in sequence to have all data to make all functions or is better another way that I don't know?

I make test with PHPUnit but I would like to know if this practice is a good practice or there is another way to make good test for this feature.

Consider that I make more external request (Point 3) not only one so I have more functions to get all data that I need (I have already cut data that I don't need).

Thanks

答:
Ideally, you want both unit tests (which test individual functions) and integration tests (which test all the functions together), not just one or the other. You will also need a way to mock out the web service you're calling so that these tests don't depend on it.

To directly address a few of the sub-questions:

So is correct to create a big test that include all functions in sequence to have all data to make all functions or is better another way that I don't know?

Yes, that's called an integration test. It is not correct to rely exclusively on integration tests, but you definitely want some of them.

I make test with PHPUnit but I would like to know if this practice is a good practice or there is another way to make good test for this feature.

This part is essentially a software recommendation question so it's technically off-topic here, but from what I can tell that framework does have a way to mock web services, declare how many calls the mock service should expect and what it should return each time, so it should do the job. In general, using a testing framework for your tests is almost always a good idea, since the alternative is writing and maintaining a lot of service mocking code and error message presentation code yourself.

Title: Test logic with external data


问:
Technique to synchronize error codes in a same-project-API
In the project I am working right now, we have some python and some C# code. At some point, I call from python a subprocess which starts a C# executable. This C# code returns an error code, which has to be understood on the python side and a readable report has to be created.

This means, both sides "must speak the same language". So, at the end I have to handle a mapping {error codes: readable explanation} (normally we implement this as static properties of a enumeration class). This is of course a case of code duplication, and prone to be inconsistent.

My ideas to mitigate this have been so far:

Automatically generate code: let's say when the mapping on the C# part changes, the code will be parsed and automatically generated on the the python side. While I think this is technically quite correct, I have to somehow parse C# code and translate it to valid python code, which is something probably hard to get it right at the first time.

Partial processing of error code on the python side. This means, just check for zero or non-zero return value, and if non-zero, read the stdout of the C# process and report it, no matter what. While this is very easy to implement, I see some possible caveats, like the C# process crashing in an unexpected way and reporting some exception traceback or similar.

Since this must be a quite common problem, I would like to know what are the easiest and more maintainable approaches used in the industry.

答:
I would use code generation from single source.

E.g. define error codes in a text file and use T4 to generate C# enum and something similar to generate python code. Or write C# enums directly and use code generation to generate python only. You dont have to parse C# code necessarily, you can use some .net tool that dynamically loads your .net assembly and uses reflection to get enum members. Why not to use T4 to generate python enums as well? :)

I believe code generation is the best way to avoid violation of DRY principle in this case.


答:
Let us consider some different use cases:

You have a variable that is only relevant for the duration of a function call, or within a specific closure. While using a global may not turn out to become a problem, it doesn't give you any benefit either. Making it local is the safe and easy choice.

You are writing a library, your code will be used in conjunction with code that you have no control of. The global scope is not yours to mess with. The only legitimate reason for using the global scope is in order to expose public library functions. These cases must of course be documented so that the library user can avoid name collisions.

You are writing your own project and you have a variable with a lifespan beyond your functions. You could do any number of things to avoid making it a global, but that tend to simply make your code more complicated, with no real advantage to show for it. Just make it global, it is the simple solution to a simple problem. Declaring it explicitly in your globals declaration section will document its existence.

You are part of a team, and you have a reasonable need for a global. This falls somewhere between case 2 and 3. If the variable need only be global to your module, then making a closure for it may be the best tradeoff. If it transcends what is possible with your own closure, a global may still be the best choice. Remember to document it in whatever fashion is customary for the project.

Globals are just fine when used in a prudent manner. The tricky part of the debate is that you can't ignore the broader context in which the code is written.

Title: why are globals bad in javascript


问:
Why not using questions in TDD tests descriptions
I've been a (small) while (ten months more or less) doing TDD for my own applications, trying to improve my skills following this workflow. Thus I am comfortable writing tests, stubbing, mocking, etc. But what I've been noticing recently is that I prefer writing questions instead of affirmations in the tests descriptions, e.g.

```<code>describe('library', function(){
  it('How many books does it have?', function() {
    expect(library.books).to.equal(100);
  });
});
</code>```

(instead of describe('library', ... it('has 100 books'...)

As when the test fails, I can see the expected and real value. I think writing questions eases the application development workflow as what you try to code is to give an answer to the test. I am aware that this method might not always be suitable, but what do you think about this?

答:
BDD style tests (as might be the case with the framework you're using) follow the Given-When-Then convention, not Question-Answer. Depending on the approach prescribed by your testing library, shoehorning questions in there might feel awkward.

However, questions could fit well in more classical test schemes where the test description is entirely contained in the test method name.

I like the idea, not so much because you "what you try to code is to give an answer to the test" (I most often write the assertion part of the test first, and the assertion basically is the answer), but because a question-based test suite would read like an FAQ and could make requirements more easily understandable.


答:
There are many cases where you write a test that is not simply the answer to a question. Compare 'does the controller send a notification mail' with 'controller should send notification mail'. Both are valid, but it is much easier to read a list of tests formulated as 'should' rather than formulated as questions.

Another major point in TDD is that the test name should in some way indicate the nature of the test. 'how many books does it have' does nothing to indicate WHY the test is even there. 'the number of books should be equal to the number of titles times the number of copies it has' at least gives you some indication of why the test exists and what it is trying to do.

Still, your tests, above all, should be readable and allow you to pinpoint mistakes quickly. If this style is beneficial to you and the people working on your project just go ahead and use it.

Title: Why not using questions in TDD tests descriptions

Body:
I've been a (small) while (ten months more or less) doing TDD for my own applications, trying to improve my skills following this workflow. Thus I am comfortable writing tests, stubbing, mocking, etc. But what I've been noticing recently is that I prefer writing questions instead of affirmations in the tests descriptions, e.g.

```<code>describe('library', function(){
  it('How many books does it have?', function() {
    expect(library.books).to.equal(100);
  });
});
</code>```

(instead of describe('library', ... it('has 100 books'...)

As when the test fails, I can see the expected and real value. I think writing questions eases the application development workflow as what you try to code is to give an answer to the test. I am aware that this method might not always be suitable, but what do you think about this?


问:
Understanding Bob Martin's Closed For Modification Explanation

“Closed for modification.” Extending the behavior of a module does not
  result in changes to the source or binary code of the module. The
  binary executable version of the module, whether in a linkable
  library, a DLL, or a Java .jar, remains untouched.

Hall, Gary McLean (2014-10-10). Adaptive Code via C#: Agile coding
  with design patterns and SOLID principles (Developer Reference) (p.
  208). Pearson Education. Kindle Edition.

In Adaptive Code via C#, the author quotes Robert C. Martin's explanation for Closed for Modification. How should we understand "The binary executable version of the module, whether in a linkable library, a DLL, or a Java .jar, remains untouched."

We can use staircase patterns for dependency tree in which interfaces and implementations are in different assemblies, and we can extend implementations in different assemblies, but not sure how reasonable this is. I don't think copying over the rest of the behavior to the new assembly makes sense. Can someone please visualize this explanation with an example.

答: I don't have access to the larger context of your quote, but I believe the discussion of executables is mostly rhetorical.  The idea behind the open-closed principle isn't that you necessarily would create a new dynamic library for every extension to your program, but that your architecture is structured so that you could if you wanted to.  In other words, new features should primarily be implemented by creating new files, not by modifying old ones, even modifications that don't change the source but would require recompiling the object file (for example, because of a change in the size of a dependent object it stores).


问:
Finding the shortest path through a digraph that visits all nodes
I am trying to find the shortest possible path that visits every node through a graph (a node may be visited more than once, the solution may pick any node as the starting node.). The graph is directed, meaning that being able to travel from node A to node B does not mean one can travel from node B to node A. All distances between nodes are equal. I was able to code a brute force search that found a path of only 27 nodes when I had 27 nodes and each node had a connection to 2 or 1 other node. However, the actual problem that I am trying to solve consists of 256 nodes, with each node connecting to either 4 or 3 other nodes. The brute force algorithm that solved the 27 node graph can produce a 415 node solution (not optimal) within a few seconds, but using the processing power I have at my disposal takes about 6 hours to arrive at a 402 node solution.

What approach should I use to arrive at a solution that I can be certain is the optimal one? For example, use an optimizer algorithm to shorten a non-optimal solution? Or somehow adopt a brute force search that discards paths that are not optimal?

EDIT: (Copying a comment to an answer here to better clarify the question) To clarify, I am not saying that there is a Hamiltonian path and I need to find it, I am trying to find the shortest path in the 256 node graph that visits each node AT LEAST once. With the 27 node run, I was able to find a Hamiltonian path, which assured me that it was an optimal solution. I want to find a solution for the 256 node graph which is the shortest.

答:
DFS can solve this problem. However, you must define an efficient evaluation function to prun the branch earlier. Some hints on the evaluation:
- use greedy to find a good path first, this may be not a shortest path, but it allows to stop on other not good path
- for each state, try the nearest state first
- for each state, evaluation the minimum length to visit all state. The evaluation should be as tight as possible. This problem is more difficult but you can refer to my post on this problem here http://www.capacode.com/?p=650</p>


问:
What belongs in an HTTP request header vs the request body?
I'm working on a set of web services for a mobile client, and the requirements call for a unique device id to be included with all requests, to be stored in certain requests, and used to filter results in others.

A suggestion was made that it be put in a custom HTTP header since it will be included with all requests, so I began to wonder what criteria might be used to determine if a given piece of data belongs in a header or along with other data in the request body.

Is there any such criteria?

答:
When the information is important, you should put it into the body.

Why?

proxy servers are allowed to modify headers. Many are configured to strip any headers they don't know. This, however, only applies when you use unencrypted HTTP. When you use HTTPS, the proxy can't change the headers because they are encrypted.

When you use a webservice, you usually do so for interoperability with other devices, services and tools. Most APIs and tools which work with webservices can easily change requests, but many make it difficult or even impossible to add custom headers. This, of course, only applies when interoperability is a concern. But when you don't care, you might want to ask yourself why you are using webservices in the first place instead of just building your own protocol on raw TCP.


问:
Is there a correlation between the scale of the project and the strictness of the language?
Explaining the difference between strictness of languages and paradigms to a colleague of mine, I ended up asserting that:

Tolerant languages, such as dynamic and interpreted languages, are used best for prototypes and small projects or medium-size web applications. When choosing elegant dynamic languages such as Python or JavaScript with Node.js, the benefits are:

Fast development,

Reduced boilerplate code,

Ability to attract young, creative programmers who flee “corporate languages”  like Java.

Statically typed/compiled languages are best for applications which require higher strictness such as business-critical apps or apps for medium to large-size apps.

Well-known paradigms and patterns developed for decades,

Ease of static checking,

Ability to find many professional developers with decades of experience.

Strict languages such as Haskell, Ada or techniques such as Code contracts in C# are better for systems which favor safety over flexibility (even if Haskell can be extremely flexible), such as life critical systems and systems which are expected to be extremely stable. The benefits are:

Ability to catch as many bugs as possible at compile time,

Ease of static checking,

Ease of formal proofs.

However, by looking at the languages and technologies used for large-scale projects by large corporations, it seems that my assertion is wrong. For example, Python is successfully used for large systems such as YouTube or other Google applications which require an important amount of strictness.

Is there still a correlation between the scale of the project and the strictness of the language/paradigm which should be used?

Is there a third factor that I've forgotten to take in account?

Where am I wrong?

答:
My experience with large systems is that they stand or fall not by language choice, but by issues of design/architecture or test coverage. I'd rather have a talented Python team on my big enterprise project, than a mediocre Java one.

Having said that, any language that let's you write significantly less code, has to be worth looking at (e.g. Python vs Java). Perhaps the future is in clever, statically-typed languages with advanced type-inference (e.g. in the Scala mold). Or hybrid, such as C# is attempting with its dynamic qualifier...?

And let's not forget the "other" static typing benefit: proper IDE code-completion/intellisense, which in my view is an essential feature, not a nice-to-have.


答:
From a lone developer point of view, it may seem contrived to extend your own modules or implement your own interfaces in distinct binaries.

However, bear in mind that it is not always the case. You might have distributed teams with a provider/customer relationship and no access to each other's source code. You might be a consumer of a third party framework, and happy to not have to touch the framework's code to adapt it to your needs.

Deployability is also a reason. If you can identify a base part of your module's behavior that will be relatively stable over time and families of peripheral behaviors which will evolve much more often, you can place those in their own executables (or any independently deployable unit). This will allow for a much more manageable deployment process in terms of continuity of service, update package size, potential side effect scope, etc.

Title: Understanding Bob Martin's Closed For Modification Explanation

Body:
“Closed for modification.” Extending the behavior of a module does not
  result in changes to the source or binary code of the module. The
  binary executable version of the module, whether in a linkable
  library, a DLL, or a Java .jar, remains untouched.

Hall, Gary McLean (2014-10-10). Adaptive Code via C#: Agile coding
  with design patterns and SOLID principles (Developer Reference) (p.
  208). Pearson Education. Kindle Edition.

In Adaptive Code via C#, the author quotes Robert C. Martin's explanation for Closed for Modification. How should we understand "The binary executable version of the module, whether in a linkable library, a DLL, or a Java .jar, remains untouched."

We can use staircase patterns for dependency tree in which interfaces and implementations are in different assemblies, and we can extend implementations in different assemblies, but not sure how reasonable this is. I don't think copying over the rest of the behavior to the new assembly makes sense. Can someone please visualize this explanation with an example.


问:
Unit Testing and dependencies
I'm just learning how to do proper unit testing, and a lot of resources make reference to using explicit dependencies, ie dependencies that are passed into the constructor, to allow for easy mocking/stubbing, etc.

This obviously makes sense.

What isn't clear to me is where should these objects be created, and how do you unit test those methods?

As an example, say you have an ASP.net ActionMethod.  This makes use of a class that requires 3 dependencies, would you simply 'new' those up in the ActionMethod?  If so, how then would you test that ActionMethod?

答: I don't know ASP.NET, but generally your dependencies would be on interfaces, and in your unit tests you provide mock, stub, or fake implementations of those interfaces. This lets you test your class in isolation, since the only code under test is the class itself plus your "skeleton" dependencies.</p>

Title: Unit Testing and dependencies


答:
Most likely those objects are created from a factory or from a single point where the object graph is created as indicated from @guillaume31 comments.  If from factory it would look something like this:

```<code>namespace Repository.Lookup
{
    public class LookupRepositoryFactory
    {
        public static ILookupRepository Create()
        {
            ILookupRepository lookupRepository = new LookupRepository();

            return lookupRepository;
        }
    }
}
</code>```

Then the test for the factory:

```<code>namespace RepositoryTests.Lookup
{
    [TestClass]
    public class LookupRepositoryFactoryTests
    {
        [TestMethod]
        public void TestCreateLookupRepository()
        {
            var expectedType = typeof(LookupRepository);

            var repository = LookupRepositoryFactory.Create();

            Assert.IsInstanceOfType(repository, expectedType);
        }
    }
}
</code>```

Then usage:

```<code>var lookupRepository = LookupRepositoryFactory.Create();
</code>```

Then you just pass in that on the constructor as you have mentioned, like so:

```<code>namespace CommonLookupAPI
{
    public class GenericLookup
    {
        private readonly ILookupRepository _repository;

        public GenericLookup(ILookupRepository repository)
        {
            _repository = repository;
        }

        public List<CommonLookup> GetCommonLookup(LineOfBusiness lineOfBusiness, ClassificationType classificationType,
            State state, Grouping grouping, SubGrouping subGrouping)
        {
            var commonLookups = _repository.GetCommonLookup(lineOfBusiness, classificationType, state, grouping, subGrouping);
            return commonLookups;
        }
    }
}
</code>```

This allows one to mock the repository with a fake implementation so you can test generic lookup without using the real repository.

Here are the tests:

```<code>namespace CommonLookupAPITests
{
    [TestClass]
    public class GenericLookupTests
    {
        [TestMethod]
        public void TestGenericLookupReturnsLookup()
        {
            ILookupRepository repository = MockRepositories.CreateMockSuccessRepository();
            var genericLookup = new GenericLookup(repository);

            var lookups = genericLookup.GetCommonLookup(LineOfBusiness.AssistedLivingProfessionalLiability, ClassificationType.ClaimLimit, State.NotDefined, Grouping.NotDefined, SubGrouping.NotDefined);

            Assert.AreEqual(lookups.Count, 0);
        }

        [TestMethod]
        [ExpectedException(typeof(Exception))]
        public void TestGenericLookupReturnsFailUnExpected()
        {
            ILookupRepository repository = MockRepositories.CreateMockFailRepositoryException();
            var genericLookup = new GenericLookup(repository);

            var lookups = genericLookup.GetCommonLookup(LineOfBusiness.AssistedLivingProfessionalLiability, ClassificationType.ClaimLimit, State.NotDefined, Grouping.NotDefined, SubGrouping.NotDefined);
        }

        [TestMethod]
        [ExpectedException(typeof(DataAccessException))]
        public void TestGenericLookupReturnsFailDataAccess()
        {
            ILookupRepository repository = MockRepositories.CreateMockFailRepositoryDataAccessException();
            var genericLookup = new GenericLookup(repository);

            var lookups = genericLookup.GetCommonLookup(LineOfBusiness.AssistedLivingProfessionalLiability, ClassificationType.ClaimLimit, State.NotDefined, Grouping.NotDefined, SubGrouping.NotDefined);
        }
    }
}
</code>```

And finally the Mock Repositories that the tests use:

```<code>namespace CommonLookupAPITests
{

    public class MockRepositories
    {
        public static ILookupRepository CreateMockSuccessRepository()
        {
            ILookupRepository repository = new MockSuccessRepository();
            return repository;
        }

        public static ILookupRepository CreateMockFailRepositoryException()
        {
            ILookupRepository repository = new MockFailRepositoryException();
            return repository;
        }

        public static ILookupRepository CreateMockFailRepositoryDataAccessException()
        {
            ILookupRepository repository = new MockFailRepositoryDataAccessException();
            return repository;
        }
    }

    public class MockSuccessRepository : ILookupRepository
    {
        public List<CommonLookup> GetCommonLookup(LineOfBusiness lineOfBusiness, ClassificationType classificationType,
            State state, Grouping grouping, SubGrouping subGrouping)
        {
            var commonLookup = new List<CommonLookup>();
            return commonLookup;
        }
    }

    public class MockFailRepositoryException : ILookupRepository
    {
        public List<CommonLookup> GetCommonLookup(LineOfBusiness lineOfBusiness, ClassificationType classificationType,
            State state, Grouping grouping, SubGrouping subGrouping)
        {
            throw new Exception();
        }
    }

    public class MockFailRepositoryDataAccessException : ILookupRepository
    {
        public List<CommonLookup> GetCommonLookup(LineOfBusiness lineOfBusiness, ClassificationType classificationType,
            State state, Grouping grouping, SubGrouping subGrouping)
        {
            throw new DataAccessException();
        }
    }
}
</code>```

Title: Unit Testing and dependencies

Body:
I'm just learning how to do proper unit testing, and a lot of resources make reference to using explicit dependencies, ie dependencies that are passed into the constructor, to allow for easy mocking/stubbing, etc.

This obviously makes sense.

What isn't clear to me is where should these objects be created, and how do you unit test those methods?

As an example, say you have an ASP.net ActionMethod.  This makes use of a class that requires 3 dependencies, would you simply 'new' those up in the ActionMethod?  If so, how then would you test that ActionMethod?

Body:
Most likely those objects are created from a factory or from a single point where the object graph is created as indicated from @guillaume31 comments.  If from factory it would look something like this:

namespace Repository.Lookup
{
    public class LookupRepositoryFactory
    {
        public static ILookupRepository Create()
        {
            ILookupRepository lookupRepository = new LookupRepository();

            return lookupRepository;
        }
    }
}

Then the test for the factory:

namespace RepositoryTests.Lookup
{
    [TestClass]
    public class LookupRepositoryFactoryTests
    {
        [TestMethod]
        public void TestCreateLookupRepository()
        {
            var expectedType = typeof(LookupRepository);

            var repository = LookupRepositoryFactory.Create();

            Assert.IsInstanceOfType(repository, expectedType);
        }
    }
}

Then usage:

var lookupRepository = LookupRepositoryFactory.Create();

Then you just pass in that on the constructor as you have mentioned, like so:

namespace CommonLookupAPI
{
    public class GenericLookup
    {
        private readonly ILookupRepository _repository;

        public GenericLookup(ILookupRepository repository)
        {
            _repository = repository;
        }

        public List<CommonLookup> GetCommonLookup(LineOfBusiness lineOfBusiness, ClassificationType classificationType,
            State state, Grouping grouping, SubGrouping subGrouping)
        {
            var commonLookups = _repository.GetCommonLookup(lineOfBusiness, classificationType, state, grouping, subGrouping);
            return commonLookups;
        }
    }
}

This allows one to mock the repository with a fake implementation so you can test generic lookup without using the real repository.

Here are the tests:

namespace CommonLookupAPITests
{
    [TestClass]
    public class GenericLookupTests
    {
        [TestMethod]
        public void TestGenericLookupReturnsLookup()
        {
            ILookupRepository repository = MockRepositories.CreateMockSuccessRepository();
            var genericLookup = new GenericLookup(repository);

            var lookups = genericLookup.GetCommonLookup(LineOfBusiness.AssistedLivingProfessionalLiability, ClassificationType.ClaimLimit, State.NotDefined, Grouping.NotDefined, SubGrouping.NotDefined);

            Assert.AreEqual(lookups.Count, 0);
        }

        [TestMethod]
        [ExpectedException(typeof(Exception))]
        public void TestGenericLookupReturnsFailUnExpected()
        {
            ILookupRepository repository = MockRepositories.CreateMockFailRepositoryException();
            var genericLookup = new GenericLookup(repository);

            var lookups = genericLookup.GetCommonLookup(LineOfBusiness.AssistedLivingProfessionalLiability, ClassificationType.ClaimLimit, State.NotDefined, Grouping.NotDefined, SubGrouping.NotDefined);
        }

        [TestMethod]
        [ExpectedException(typeof(DataAccessException))]
        public void TestGenericLookupReturnsFailDataAccess()
        {
            ILookupRepository repository = MockRepositories.CreateMockFailRepositoryDataAccessException();
            var genericLookup = new GenericLookup(repository);

            var lookups = genericLookup.GetCommonLookup(LineOfBusiness.AssistedLivingProfessionalLiability, ClassificationType.ClaimLimit, State.NotDefined, Grouping.NotDefined, SubGrouping.NotDefined);
        }
    }
}

And finally the Mock Repositories that the tests use:

namespace CommonLookupAPITests
{

    public class MockRepositories
    {
        public static ILookupRepository CreateMockSuccessRepository()
        {
            ILookupRepository repository = new MockSuccessRepository();
            return repository;
        }

        public static ILookupRepository CreateMockFailRepositoryException()
        {
            ILookupRepository repository = new MockFailRepositoryException();
            return repository;
        }

        public static ILookupRepository CreateMockFailRepositoryDataAccessException()
        {
            ILookupRepository repository = new MockFailRepositoryDataAccessException();
            return repository;
        }
    }

    public class MockSuccessRepository : ILookupRepository
    {
        public List<CommonLookup> GetCommonLookup(LineOfBusiness lineOfBusiness, ClassificationType classificationType,
            State state, Grouping grouping, SubGrouping subGrouping)
        {
            var commonLookup = new List<CommonLookup>();
            return commonLookup;
        }
    }

    public class MockFailRepositoryException : ILookupRepository
    {
        public List<CommonLookup> GetCommonLookup(LineOfBusiness lineOfBusiness, ClassificationType classificationType,
            State state, Grouping grouping, SubGrouping subGrouping)
        {
            throw new Exception();
        }
    }

    public class MockFailRepositoryDataAccessException : ILookupRepository
    {
        public List<CommonLookup> GetCommonLookup(LineOfBusiness lineOfBusiness, ClassificationType classificationType,
            State state, Grouping grouping, SubGrouping subGrouping)
        {
            throw new DataAccessException();
        }
    }
}


问:
When designing a data structure, should I implement very inefficient operations for convenience?
(I've added the .NET tags because the data structures are for .NET, and this question should be considered in the context of the conventions for that platform.)

I'm writing a library of immutable and persistent data structures for .NET. One of my data structures, a type of vector, supports the following core operations:

Addition and removal at the end

Lookup and update by index

Starting subsequence

(Uninteresting things like length, etc)

In addition, there is a special implementation of bulk operations (involving sequences, such as addition of many elements) that is extremely fast for large inputs. This makes addition of many elements to the end very, very fast.

My issue is a bit more complicated than the title of the question makes out. I can implement the following additional operations:

Addition of many elements at the beginning

Insertion of many elements in the middle

Addition of many elements to the end is O(m + logn), where m is the number of elements to be added. These operations would be O(n + m), and if m = n then they are almost as fast as addition to the end. In practice, they would be many orders of magnitude faster than if the user implemented them naively. However, for small numbers of elements, they would still be very slow.

My first problem is that the normal operations are so fast, they might confuse users and make them think these additional operations perform in a similar manner. Unlike for regular collections where even List<T>.Insert is fast, this can actually bottleneck the application. How should I deal with this?

My second problem is that, if I implement these additional operations, should I also provide similar (extremely inefficient) operations that work with single elements? It seems strange not to provide these apparently simpler operations, and I'm sure they will be handy (performance isn't important at all sometimes), but that surprise factor is even worse here, since these operations can never be efficient.

A similar consideration applies for a Skip (ending subsequence) operation.

答:
Addition of many elements to the end is O(m + logn), where m is the number of elements to be added. These operations would be O(n + m), and if m = n then they are almost as fast as addition to the end. In practice, they would be many orders of magnitude faster than if the user implemented them naively. However, for small numbers of elements, they would still be very slow.

To me, the fact that the user simply can't obtain similar performance for these operations without access to the source code of the data structure is reason enough. To do otherwise punishes the users that actually need the performance while giving no major benefits to those that don't.

I can see where you're coming from; there's certainly something to be said for following the principle of least surprise. However, I don't think there's anything surprising about insertion into the beginning of a vector being slower than insertion at the end, and users that haven't bothered to read about the time complexity of the operations are in no position to complain about them. What's more, regardless of how much slower insertion at the beginning is, that may not be the performance bottleneck in the user's application, or the user may never create vectors big enough that the difference would matter.

What would be surprising is if the user could implement a faster insertion than you despite not having access to the data structure's innards.


答:
What isn't clear to me is where should these objects be created

Anywhere except in the dependent object itself, obviously. The point is that the consumer object doesn't control its dependency's lifecycle, someone else does.

One possible global approach to this is to compose the entire application's object graph in a single place, the Composition Root, located as close as possible to the application entry point. What it does concretely is new up all objects that are predictably instantiatable at that point and wire them up together using constructors.

As an example, say you have an ASP.net ActionMethod. This makes use of
  a class that requires 3 dependencies, would you simply 'new' those up
  in the ActionMethod?

Of course not -- the ActionMethod doesn't know how the class it uses is built, let alone controls how this dependency's dependencies are newed up :)

how then would you test that ActionMethod?

As you said, by passing mocks or stubs in the Controller's constructor or as arguments to the ActionMethod itself.

Title: Unit Testing and dependencies


答:
I think the easiest visualization is the extension methods on C#. You can add additional behaviour to a class, without needing to change that class. The extension method itself can be set on a different dll. Ruby is another example in which this ability was baked in from the beginning.

public static class Extensions
{
    public static bool IsAllCapitals (this string text)
    {
        return text.All(x => Char.IsUpper(x));
    }
}

// Then called
string text = "TEXT";
text.IsAllCapitals();
```

<p>Although the main idea on the SOLID principles, I believe, is the use of inheritance, which can add additional behaviour to the class, without having to do the copy/paste that you are talking about. On this case, if you override any method of a class you should still be calling the base implementation. The child class can/should be in a separate dll. You can, of course, create additional public methods or implement other interfaces.</p>

<pre class="lang-cs prettyprint-override"><code>    public interface IA
{
void DoSomething();
}

public class A : IA
{
public virtual void DoSomething()
{
    Console.WriteLine("In A");
}
}

public class B : A
{
    public override void DoSomething()
    {
        base.DoSomething();
        Console.WriteLine("In B");
    }
}
</code>```

Using DI then you can select at runtime which version you want to use, the original, or the extended one.

Body:
I think the easiest visualization is the extension methods on C#. You can add additional behaviour to a class, without needing to change that class. The extension method itself can be set on a different dll. Ruby is another example in which this ability was baked in from the beginning.

public static class Extensions
{
    public static bool IsAllCapitals (this string text)
    {
        return text.All(x => Char.IsUpper(x));
    }
}

// Then called
string text = "TEXT";
text.IsAllCapitals();

Although the main idea on the SOLID principles, I believe, is the use of inheritance, which can add additional behaviour to the class, without having to do the copy/paste that you are talking about. On this case, if you override any method of a class you should still be calling the base implementation. The child class can/should be in a separate dll. You can, of course, create additional public methods or implement other interfaces.

    public interface IA
{
void DoSomething();
}

public class A : IA
{
public virtual void DoSomething()
{
    Console.WriteLine("In A");
}
}

public class B : A
{
    public override void DoSomething()
    {
        base.DoSomething();
        Console.WriteLine("In B");
    }
}

Using DI then you can select at runtime which version you want to use, the original, or the extended one.


问:
Are project naming conventions more important than language naming conventions?
I'm working on a project with a senior developer and he doesn't really abide by the naming conventions of the language that we're using. The project is in Go and he uses underscores for everything. For instance, in Go public fields on structs should be named something like TeamID, but in his code it's Team_id. There is already a lot of code written that follows this naming convention.

So basically my questions is, should I ensure that my code follows the naming conventions of the language or should I focus on keeping things consistent and use the naming conventions set forth by the original developer.

I spoke a little about it to him, but he doesn't really care about stuff like that and thinks it's unimportant.

答:
If most people don't mind along with the senior developer then you will have very difficult time persuading them all. In this case I would recommend just keep going with the original convention set forth by the original developer and at least keep things consistent.

If other people are not okay with that as well then you can focus on the ROI of converting already existing project naming convention to language naming convention and present that to the management along with the senior developer. This will most certainly cause some friction.

In conclusion, I would say that language naming conventions are very important because new people coming into your project are more comfortable with the codebase requiring less explanation and causing less friction.

The reason being that language naming conventions are global and project naming conventions are local so people would need more time getting used to it.

As new developers are getting used to the project naming conventions they are bound to mix it up with language naming conventions if that's what they were used to. Code reviews could solve this issue but it is an unpleasant element of going with the project naming conventions nevertheless.

Hence, from that perspective language naming conventions are more important than project naming conventions.


问:
Implementing common logic in base class

Background

In the documentation of a project I'm working on I came across the following sentence which immediately triggered an alarm for me:

when having several concrete classes that inherits from the same base class, logic which is common for all sub classes should NOT be implemented in the base class.

This is a pretty bold statement which kind of conflicts with everything I think of OOP.

The reason stated was testability. It said that when writing unit tests, if a common logic is implemented in the base class, it will be tested multiple times for each concrete sub class and cannot be mocked out.

Question

Where or how can one implement a common logic for multiple sub classes so it can be easily mocked when they are being tested?

答:
You stumbled on one of the Bigger problems that tends to get swept under the rug in unit testing/TDD discussions. Well designed code from an object oriented perspective is generally hard to unit test, code that is easy to write unit tests for usually is compromising some paradigms of object oriented design.

Most approaches to unit testing tend to drive towards a design that makes unit testing easier, which isn't bad depending on what rules you bend/break. These designs tend to over expose methods so they can be more easily isolated, using interfaces or utility classes to handle common code.

Dependency injection is one of the more popular ways to handle these situations. Here is a pretty simple example in C#. Essentially rather than inheriting directly from a base class, each class will instead implement an interface that is dependent upon an object that handles the common operations. This way you can simply pass MyMockedCommonClass instead of MyCommonClass in your unit tests. This also allows your code to still be pretty Object Oriented friendly.

Title: Implementing common logic in base class


答: Consistency within the project is the most important thing. I hate underscores and Hungarian notation, but if you are working on a project full of them then its best to keep doing it the same way. Changing to different standards makes everything a mess in the project and you end up with no real standards, unless you took the time to go through and change everything which is essentially a rewrite.</p>

Title: Are project naming conventions more important than language naming conventions?

Body:
I'm working on a project with a senior developer and he doesn't really abide by the naming conventions of the language that we're using. The project is in Go and he uses underscores for everything. For instance, in Go public fields on structs should be named something like TeamID, but in his code it's Team_id. There is already a lot of code written that follows this naming convention.

So basically my questions is, should I ensure that my code follows the naming conventions of the language or should I focus on keeping things consistent and use the naming conventions set forth by the original developer.

I spoke a little about it to him, but he doesn't really care about stuff like that and thinks it's unimportant.


答:
It doesn't matter what convention you use, as long as you are consistent in your convention.

But when you deviate from the default naming convention of the programming language, you are making it impossible to stay consistent, because any interactions with the standard library will use a different naming convention than interactions with your own code.

For that reason it is generally a good idea to adopt the naming conventions used by the standard library.


问:
How should I handle database failures in a web application?
I'm developing a simple RESTful API using Go's Goji framework (although this question is language-agnostic), in which parameters from the URL are queried against a PostgreSQL database.  Here's how it works:

First we define a struct that holds a reference to our ORM

This struct contains an Init method that allows us to initialize a connection.  This struct contains other methods to handle HTTP requests and exists primarily as a means to associate the database with the request handler.

```<code>type Context struct {
    db *gorm.DB
}

func (ctx Context) Init(user string, name string) (Context, error) {
    db, err := gorm.Open(
        "postgres",
        fmt.Sprintf("port=5432 sslmode=require host=domain.xxx"),
    )
    ctx.db = &db
    return ctx, err
}

func (ctx Context) handleGetRequest(c web.C, w http.ResponseWriter, r *http.Request) {
    // ... business logic
}
</code>```

This structure is then initialized exatly once when the web application starts up

With this architecture, any database failure implies that the web app must be restarted.

```<code>func main() {
    // "Context" is a means of including a DB object with route handlers
    ctx, err := context.Context{}.Init(dbuser, dbname)
    if err != nil {
        panic(err)
    }
    defer ctx.Close()

    // do other stuff, e.g. set up routing and whatnot ...
}
</code>```

My questions are as follows:

From a software architecture point of view, what is a reasonable approach for gracefully handling database downtime and automatically reconnecting when the DB becomes available?

How can I work the recommendations in this answer into my design?

tl;dr:  what's the industry standard for handing DB failures within web applications, from a software architecture perspective?

答:
Requiring a reboot of the application when the database goes down is definitely a bad design, because it increases maintainance effort which will negatively affect your uptime.

A good design would try to reconnect to the database every few seconds so business can continue as soon as the database is available again.

In the meantime, returning a "500 Internal Server Error" is reasonable, although it would be better when those features of the application which don't strictly require the database would still work to avoid hurting the users faith in the reliability of your service (under the premise that your application has such features).


问:
Is Red Star OS released under the GPL?
According to Wikipedia, Red Star OS is

is a North Korean Linux-based operating system

Does that mean it's covered by the GPL, or are there exceptions?

答:
As a Linux derivate, it should be licensed under the GNU GPL, but it isn't. That means that by distributing it under a different license, the KCC is violating the copyright of thousands of Linux contributors.

However, that does not mean that someone who obtained a copy of it can redistribute it under GPL, as that would also be a copyright violation, in this case of the copyright of the modifications the KCC did. Two wrongs don't make a right.

Good luck, however, with fighting a copyright lawsuit across the border of North-Korea.

Title: Is Red Star OS released under the GPL?


问:
What happens to database design process when ORM tools are used?
I have learned about database design, including normalization during my undergraduate course. When we have to model a database for a system, we can start with an ER model and then convert it to the relational model and then we could normalize the design, to come up with the final schema of the database.

This was the approach I was thought at college. Now with the adoption of different ORM tools like hibernate, the object classes are directly mapped into tables with annotations(in java).

Does it mean that if we are using an ORM tool we do not need to design our database like before? Does it mean that we do not even have to come up with an ER-Model for our database? It turns out that if we have our object model(in a class diagram), by deciding what objects should be stored, we could automatically arrive at a database design.
If so what happens to the normalization? What happens for the tables we would have designed for different relationships(1 to many, many to many etc;) in ER model?

Does it mean that we have traded good database design for ease of programmability?

Thinking about this makes me confused. please explain.

答:
Does it mean that if we are using an ORM tool we do not need to design our database like before?

You still need a design; it just takes a somewhat different form.  The nature of the design shouldn't change all that much; you're still going to have records and relations, they'll just look a bit different.

Does it mean that we do not even have to come up with an ER-Model for our database?

The entity-relationship model is implied in the class design.

What happens to the normalization?

Same as before.  You still store each bit of domain information in one place.

What happens for the tables we would have designed for different relationships (1 to many, many to many etc;) in ER model?

They become collections in the object model.


答:
If that common behavior sees frequent use, it will admittedly be executed multiple times during tests for each of the subclasses, but so will it at runtime in production, there's nothing wrong with it. However, that doesn't mean you should specifically test the common logic multiple times.

Concrete/abstract superclass

If the superclass is not abstract and the behavior public, you should have one test for it. Plain and simple. No need to repeat the test for each child.

What I often found though was that you mostly don't have concrete superclasses but abstract ones. Common behavior contained in an abstract class isn't tested per se but as part of the derived classes tests. I don't see it as a problem, it's much like when a private method is tested indirectly as part of a public method test.

Mocking

You shouldn't need to mock or stub out common behavior from a base class (or from one of your own private methods, which is exactly the same), because what belongs to your superclass also belongs to you, and trying to mock yourself is stupid.

If you feel that need, it's probably that your class is not cohesive enough and you should extract that behavior to a separate unrelated class instead of using inheritance.

Title: Implementing common logic in base class

Body:
Background

In the documentation of a project I'm working on I came across the following sentence which immediately triggered an alarm for me:

when having several concrete classes that inherits from the same base class, logic which is common for all sub classes should NOT be implemented in the base class.

This is a pretty bold statement which kind of conflicts with everything I think of OOP.

The reason stated was testability. It said that when writing unit tests, if a common logic is implemented in the base class, it will be tested multiple times for each concrete sub class and cannot be mocked out.

Question

Where or how can one implement a common logic for multiple sub classes so it can be easily mocked when they are being tested?