答:
There are a couple of principles that apply here

SOLID design principles for OO
The main one that applies to your description is the single responsibility principle.
Although the Interface segregation principle by its nature tends to keep class sizes reasonable.

Refactoring Question
So whilst it is better to keep classes smaller, the decision to refactor is a more cokplex one.

Do you have good Test cases.

With good test cases you can be more adventurous with refactoring . But as usual if the original developers were getting OO build done with a good set of test classes, then they would have already refactored.

Did the large class need to be changed?
If you have to change of fix something, that is often a point were a refactor can be worth the investment.

Refactoring to make it more elegant
As much as it is nice to have clean and more easily maintained code, without sufficient maintainability issues it is most likely hard to justify refactoring for elegance.

When to refactor Blog, worth a look

if you happen to have a pluralsight subscription, there is an excellent course on this  topic refactoring on plural - subscription fee applies


问:
Do named arguments replace the builder pattern?
When using a language that supports named and optional arguments, does the builder pattern no longer have a practical use?

Builder:

new Builder(requiredA, requiredB).setOptionalA("optional").Build();
```
<p><strong>Optional/named arguments:</strong></p>
<pre class="lang-cs prettyprint-override"><code>new Object(requiredA, requiredB, optionalA: "optional");
</code>```

答:
In addition to what Ixrec said, the constructors or method named parameters won't allow you to have your object in a to-be-constructed state in which it can still be modified before building it. This is the beauty of the Builder, where you can delegate parts of its construction to different methods or classes altgether:

```<code>var myThingBuilder = new ThingBuilder("table");
myThingBuilder.setAttribute(Attributes.Legs, 4);

inventoryManager.setPrices(myThingBuilder);

// inventory manager
var availableCheapestMaterial = getMaterial();
myThingBuilder.setMaterial(availableCheapestMaterial);
</code>```

Basically, you're also able to throw your builder around your system until it is ready to build the final object, allowing you to decrease the amount of knowledge that your builder-consumer needs to have.

ContentLicense: CC BY-SA 4.0

Body:
In addition to what Ixrec said, the constructors or method named parameters won't allow you to have your object in a to-be-constructed state in which it can still be modified before building it. This is the beauty of the Builder, where you can delegate parts of its construction to different methods or classes altgether:

var myThingBuilder = new ThingBuilder("table");
myThingBuilder.setAttribute(Attributes.Legs, 4);

inventoryManager.setPrices(myThingBuilder);

// inventory manager
var availableCheapestMaterial = getMaterial();
myThingBuilder.setMaterial(availableCheapestMaterial);

Basically, you're also able to throw your builder around your system until it is ready to build the final object, allowing you to decrease the amount of knowledge that your builder-consumer needs to have.

ContentLicense: CC BY-SA 3.0


问:
fast, say O(log2(N)), sliding median algorithm
So I know how to do a fast O(log2(N)) sliding max or sliding min algorithm.

Brookes: "Algorithms for Max and Min Filters with Improved Worst-Case Performance"  IEEE TRANSACTIONS ON CIRCUITS AND SYSTEMS—II: ANALOG AND DIGITAL SIGNAL PROCESSING, VOL. 47, NO. 9, SEPTEMBER 2000

But I just cannot figure out how to do a sliding median without first sorting the buffer (or at least sorting it half way) and then picking the value halfway into the buffer (or midway between the bottom and the top of the sorted buffer).

Given a finite-length buffer (length N) that is chronologically sorted (like a FIFO) and another with the same N values sorted by value, then when the buffer window "slides" by one and the oldest value falls offa the edge and a new one is input, to insert that new value into the sorted buffer, that is an O(N) operation (probabilistically).

What's a faster way to do this?

答:
Lets assume N=100. You have the raw values in chronological order raw[1],...,raw[100] and you have the ordered list of the same values as ordered[1],...,ordered[100]. What is the median? The median will be (ordered[50]+ordered[51])/2.

Lets now move the window one position so raw data will be raw[2],...,raw[101]. How do you generate an updated list for ordered[1],...,ordered[100]? Simple. Do a binary search for raw[1] value in the ordered array (ordered[1],...,ordered[100]) and remove it from the list. I am assuming a binary search tree or skip list implementation so you don't need to move all values higher than raw[1] one position down. Now do another binary search for raw[101] value in the ordered array and add it to the list. I am again assuming a binary search tree or skip list so you don't need to move all values higher than raw[101] one position up.

How you calculate the median now? The same way as before, it will be (ordered[50]+ordered[51])/2. But now ordered[50] and ordered[51] may be different values now.

So the sliding median is O(Log(N)) because that is what a binary search takes which is what you are looking for. Yes, you need to sort the first N values, but once you do that, you just keep the numbers ordered as you slide thought the chronological values (signal). In the long run, the time you took to order those first values will just be diluted.


问:
Dealing with class optional dependencies
I am wondering how are you guys handling an optional class properties.
Let's say I have a product that can bud doesn't have to have a color property. Is that really the best way of doing that? Should I use null object pattern? Should I use strategy pattern maybe? Should I maybe use a decorator pattern here so I'll have Product and ProductWithColor? What if another property will be added and become optional?

<?php

class Product
{
    private $id;
    private $title;

    /**
     * @var string|null
     */
    private $color;

    function __construct($id, $title, array $color = null)
    {
        $this->id              = $id;
        $this->title           = $title;
        $this->color           = $color;
    }
}
```

答:
What if another property will be added and become optional?

I have done precisely this when I needed to inject some new functionality into that method. This does not break existing code; you gotta love that! In my case I bypass the new thing if the parameter is null.

I generally prefer to use a more meaningfully named value/enum. For example, "Unassigned/Unknown/NotSet".

I strongly disagree with this (quote from a comment). Doing this with a string is a big hassle - typos, casing, lack of type checking (I do C#). However if this was an enum then absolutely, have a "undefined" enum value (in C# I would have this correspond to zero because that's the default for enums).

Should I use null object pattern?

Not exactly. We're dealing with a single property, but the idea is the same. Make the optional/default method parameters behave benignly. For example, I set my optional string parameters to string.Empty (C#) so calling members on it does not blow up.

Should I use strategy pattern maybe? Should I maybe ...

No. Strategy is for polymorphic behavior - i.e. functions/methods with the same parameters (signature) on different types.

Optional parameters is a technique for creating concise method overloads.

I'll have Product and ProductWithColor

Well, if your design calls for that but I suspect not. Why are you letting a single optional parameter for a single function drive your design? null has "special handling required", sure, but so would any property with any value that had special meaning. Here it is just a mechanism for allowing client code to ignore color for the call. How is this a whole different class?


问:
Understanding VB.NET variable scope
What's the difference between this code snippet:

```<code>Sub Test()
  Dim i as Integer = 0
  Dim q as String = ""
  While i<10
    q=String.Format("Some text {0}", i)
    Console.WriteLn(q)
    i=i+1
  End While
End Dub
</code>```

and this one:

```<code>Sub Test()
  Dim i as Integer = 0
  While i<10
    Dim q as String = String.Format("Some text {0}", i)
    Console.WriteLn(q)
    i=i+1
  End While
End Dub
</code>```

in terms of memory allocation and performance ...

答: In the first example, I would assume that the variable has been declared in advance to avoid garbage collection issues, except there are only 10 iterations, and if you don't have enough ram to handle that, then you have a bigger issue on your hands than memory management. This might be useful to declare a variable only once, if that object takes up a lot of memory, but forcing a garbage collection may still be necessary, as the garbage collector doesn't instantly collect when the reference to an object goes out of scope. In general I try to keep declarations within the scope they are used, but sometimes there could be a reason to pre define your variables. Just think about why you are doing it, and run a benchmark to see if it helps improve your performance. Use whichever one works better for your situation, if both work the same, try to keep things declared within the scope they are used.</p>

Title: Understanding VB.NET variable scope


问:
What do you get when you cross a multi-precision integer with a floating-point number?
I'm working on adding multi-precision integers to the suite of numeric types in my APL interpreter, but I'm not sure what to do about the odd type-combinations that now arise. I now have the following types:

```<code>IMM "atomic" small integer
FIX full-width integer
FLO floating-point double
MPI multi-precision integer
</code>```

I have a variable which controls which larger type to use for integer overflow, either FLO or MPI. Mixed MPI/IMM/FIX operations, since they're all integers, can simply promote to the widest type and produce a result of that type. And mixed FLO/IMM/FIX operations can follow the same pattern since a double can comfortably accommodate all the values of a 32-bit integer. This covers most of the cases. But it leaves me with these type combinations which don't have an obvious (to me) rule to follow.

```<code>FLO {+-*/} MPI
MPI {+-*/} FLO
</code>```

Having written this out, I suppose there really is an obvious solution (multi-precision floating-point). But I don't want to do that right now. Is there a sensible shortcut I can take (for now)?

As a "worst case" scenario that at least delivers some kind of result, I can implement conversions between these two types. But there's potential loss of data each way.

```<code>FLO -> MPI loses fractional part of floating-point number
MPI -> FLO loses precision from integer
</code>```

答:
As a start, if we begin to consider the actual quantities involved then some subcases might be handled easily. It might also depend upon the operation we want to do.

```<code>MPI {+-} FLO
FLO {+-} MPI
</code>```

If the FLO has a zero fractional part, then it can be converted to MPI losslessly. If it does have a fraction, then we probably want to keep the fraction and we ought to convert the MPI to FLO and cope with the loss of precision somehow.

```<code>MPI * FLO
FLO * MPI
</code>```

Now here, we might want to perform a scaling operation on the MPI, so perhaps a little algebra can wiggle us out a result.

```<code>FLO = int + (1/frac)
R = MPI * FLO
  = MPI * (int + (1/frac))
  = (MPI * int) + (MPI/frac)
</code>```

All of this seems to lead to a user-configurable parameter that selects which type to yield.

Or if the MPI is exactly representable as a double, then it can be converted without fear. Although the result may lose precision if the values are near the representation limits.

Body:
As a start, if we begin to consider the actual quantities involved then some subcases might be handled easily. It might also depend upon the operation we want to do.

MPI {+-} FLO
FLO {+-} MPI

If the FLO has a zero fractional part, then it can be converted to MPI losslessly. If it does have a fraction, then we probably want to keep the fraction and we ought to convert the MPI to FLO and cope with the loss of precision somehow.

MPI * FLO
FLO * MPI

Now here, we might want to perform a scaling operation on the MPI, so perhaps a little algebra can wiggle us out a result.

FLO = int + (1/frac)
R = MPI * FLO
  = MPI * (int + (1/frac))
  = (MPI * int) + (MPI/frac)

All of this seems to lead to a user-configurable parameter that selects which type to yield.

Or if the MPI is exactly representable as a double, then it can be converted without fear. Although the result may lose precision if the values are near the representation limits.


问:
Where to put a common database connection for my classes
I have several classes (Repositories) which do the task of saving/retrieving some objects in/from database; all of them need to establish a connection to one database.

I thought in order to avoid redefining the ConnectionString and the SqlConnection in each class, passing an open connection to them. Then where/when is the best place/time to define/open that connection and pass it to the classes?

Are there better approaches/patterns to have access to this common resource?

答:
Passing an open connection to each class is probably not the best idea.
Take a read of Creating database connections - Do it once or for each query?

It recommends opening and closing the connection per each query you wish to run, rather than passing the open connection to your repository.

You could try something like this to help you with managing your connections.

```<code>public class Repository
{
    private readonly string _connectionString;

    public Repository()
    {
        _connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString
    }

    protected SqlConnection GetConnection()
    {
         return new SqlConnection(_connectionString);
    }

}

public sealed class UserRespository : Repository
{

    public User GetUsers()
    {
        using (var connection = GetConnection())
        {
            using (var commnad = new SqlCommand("SqlQuery", connection))
            {
                //Execute Query
                //Return results
            }
        }
    }
}
</code>```

Body:
Passing an open connection to each class is probably not the best idea.
Take a read of Creating database connections - Do it once or for each query?

It recommends opening and closing the connection per each query you wish to run, rather than passing the open connection to your repository.

You could try something like this to help you with managing your connections.

public class Repository
{
    private readonly string _connectionString;

    public Repository()
    {
        _connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString
    }

    protected SqlConnection GetConnection()
    {
         return new SqlConnection(_connectionString);
    }

}

public sealed class UserRespository : Repository
{

    public User GetUsers()
    {
        using (var connection = GetConnection())
        {
            using (var commnad = new SqlCommand("SqlQuery", connection))
            {
                //Execute Query
                //Return results
            }
        }
    }
}


问:
Fastest way to determine if a value is in a list?
I'm aware there may not be a good solution to this problem. I'm looking for a fast algorithm that determines whether or not a value (let's say an integer) exists in a set of values, however I need the algorithm to also be fast if the value is not in the set. I.e.: Most methods I can think of right now that determine if a value is in a list will take longer to determine that it is not as they will not exit early.

I've been experimenting with using the keys of an unordered set but found them to actually be rather slow to verify. I'm not really sure what's going on behind the scenes with this data type. I'm aware that a straight forward array search might be faster than looking up a key but the size of the array is not properly known yet, only that it will be very large.

Properties and assumptions:

Assume all the values are integers between 0 and N, where N is likely to be in the millions.

The list will need to be checked very quickly, several 100 times per millisecond, but usually roughly in the same place each time with only a gradual deviation in the target area.

There is no constraint on the preparation time available for setting up a data structure, i.e.: the list could be organised specially somehow before hand.

There will be no duplicate values in the data.

答:
If there is a known maximum N, you can use a Bit array for really fast lookup time.

Simply keep an array of size N/8 (rounded up) around, with each bit corresponding to a number, 1 if it is in the set, 0 if it isn't. Lookup the relevant bit to check whether a number is in the set.

If this is too slow, and you have the megabytes ("millions" doesn't sound very high), then just keep a boolean array of size N.

Edit: for much larger values of N this won't fit into memory, and you probably need some sort of hashing. It'd still be nice to use the fact that subsequent calls are likely to be close to each other, though.

So a sketch of an idea: use the number divided by 256 as the key, and store a 256-bit bit array as the value (for all the numbers that divide to this key). Store the most recently retrieved key and bit array. If the next call divides to the same key, you can look it up in the cache bit array immediately. The number 256 can be tweaked a lot, of course. I'm not sure this is actually faster than just using map without extra gimmicks, so profile it.

For large values of N it's going to depend on lot on the sparseness of the data; clearly if you have max N 10^12 and a lot of the values are in the set, then it's not going to fit into memory anyway.


答:
For certain types of data, you can achieve constant time median filtering (Perreault et al, 2007).

That paper describes 2D median filtering on images, assuming the pixels are 8-bit integers.

Note that "constant time" refers to constant time in the size of the window; it is not constant time in the size of data, or in the precision (bits) of data. As explained below, using this algorithm with high-precision data will dramatically increase the memory usage by the algorithm, due to the histogram.

Firstly it is necessary to understand multi-level histograms.

When the alphabet set (the set of allowed pixel values) has 256 symbols, the histogram has 256 bins.

A multi-level histogram for 256 bins will have two levels. The first level will have 16 bins, and the second level will have the full 256 bins.

Each of the 16 first-level bin corresponds to some 16 consecutive bins on the second level, in the most straightforward way.

Each increment (add-sample) operation will increment the bin on the second level, as well as one of the 16 bins on the first level.

Likewise, decrement (remove-sample) operation will decrement a bin on both the first and second levels.

When one needs to search for the median, one will first search among the first-level bins, as there are fewer of them. Once the correct first-level bin is found, one will then search among the 16 second-level bins, where it is guaranteed that one of those will contain the median.

From this, you can see why the algorithm time complexity is proportional to the number of bits in the data precision.

Then, for each dimension of data, you will maintain the histogram for a sliding window, each time adding one sample and removing one sample.

If the data has multiple dimensions, then an array of histograms (as many as the width of the input in the first dimension) will need to be maintained.

Obviously this quickly grows out of hand for higher dimensions, but for some combinations of input sizes and window sizes, this scheme turns out to have better performance than previously known approaches.

Whether this algorithm can be used in your application will depend on the type of data you need to sort.

For example, if your data contains 32-bit integers, and all 2^32 different values are equally likely to appear in the data, then you will need a histogram having 2^32 bins, which is a somewhat insane requirement, but might still be doable. If your data contains IEEE double-precision floating point values, and all 1023 * 2^52 values are likely to occur, then the histogram will apparently not fit in any kind of computers currently available.

You can reduce the number of histogram bins needed by lowering the resolution (precision) of your data.

Title: fast, say O(log2(N)), sliding median algorithm

Body:
So I know how to do a fast O(log2(N)) sliding max or sliding min algorithm.

Brookes: "Algorithms for Max and Min Filters with Improved Worst-Case Performance"  IEEE TRANSACTIONS ON CIRCUITS AND SYSTEMS—II: ANALOG AND DIGITAL SIGNAL PROCESSING, VOL. 47, NO. 9, SEPTEMBER 2000

But I just cannot figure out how to do a sliding median without first sorting the buffer (or at least sorting it half way) and then picking the value halfway into the buffer (or midway between the bottom and the top of the sorted buffer).

Given a finite-length buffer (length N) that is chronologically sorted (like a FIFO) and another with the same N values sorted by value, then when the buffer window "slides" by one and the oldest value falls offa the edge and a new one is input, to insert that new value into the sorted buffer, that is an O(N) operation (probabilistically).

What's a faster way to do this?


答:
You could generate a binary tree (radix tree aka trie).  To prepare for the search, for each number in your array, starting with the least significant bit, if it is 0, you look to the left node.  If it is 1, you look to the right node.  You follow the tree until you find no more nodes, and from there you create the tree one node at a time.

To search, taking each bit, starting with the least significant bit, if bit is 0, go left.  if bit is 1, go right.  No node found?  Your number isn't in the tree, you're done.  Otherwise, continue with the next bit on that node.  If you run out of bits and you are on a node, then you've found your number.

It takes O(nlog n) to construct binary tree and O(log n) to determine if any number exists.  It should be faster than a traditional hash map, but it is also more restrictive so this implementation would only work with numbers.

The reason why you'd start with the least significant bit is to keep the table somewhat balanced (otherwise a good many of the numbers would likely start with 0).  Hope that helps!

Title: Fastest way to determine if a value is in a list?

Body:
I'm aware there may not be a good solution to this problem. I'm looking for a fast algorithm that determines whether or not a value (let's say an integer) exists in a set of values, however I need the algorithm to also be fast if the value is not in the set. I.e.: Most methods I can think of right now that determine if a value is in a list will take longer to determine that it is not as they will not exit early.

I've been experimenting with using the keys of an unordered set but found them to actually be rather slow to verify. I'm not really sure what's going on behind the scenes with this data type. I'm aware that a straight forward array search might be faster than looking up a key but the size of the array is not properly known yet, only that it will be very large.

Properties and assumptions:

Assume all the values are integers between 0 and N, where N is likely to be in the millions.

The list will need to be checked very quickly, several 100 times per millisecond, but usually roughly in the same place each time with only a gradual deviation in the target area.

There is no constraint on the preparation time available for setting up a data structure, i.e.: the list could be organised specially somehow before hand.

There will be no duplicate values in the data.


答:
I would try to go for the bitfield too, but if the data is sparse and the range too great to make this work, a splay tree might be a good data structure to use.

Splay trees are modified on each access (so they are not thread-safe, which could be an exclusion reason for you) to optimize repeated access to the same element. Often-used elements bubble to the top. If your access pattern really stays in the same area for a while then this could make for fast lookup in your case.

But this depends on usage pattern. You still have to traverse the entire tree height for non-existent elements.


答:
Having an open connection and passing it between classes are generally a bad idea.
Sure, opening a connection is quite a performance hit, but that's already taken care of by the connection pool by reusing already opened connections. A remark though: always wait as long as possible to call connection.Open(), especially in multithreaded code since this will assign the connection to your method (wich will potentionally increase the needed amount of open connections to the database).

To make your classes as generic as possible, I would recommend having a base class exposing a method with IDbConnection, and your repositories will have a more generic implementation.

```<code>internal abstract class Repository
{
    private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;

    protected IDbConnection GetConnection()
    {
        return new SqlConnection(ConnectionString);
    }
}

public class MyRepository : Repository
{
    public IEnumerable<object> Get()
    {
        using (var connection = GetConnection())
        {
            connection.Open();

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

Title: Where to put a common database connection for my classes

Body:
I have several classes (Repositories) which do the task of saving/retrieving some objects in/from database; all of them need to establish a connection to one database.

I thought in order to avoid redefining the ConnectionString and the SqlConnection in each class, passing an open connection to them. Then where/when is the best place/time to define/open that connection and pass it to the classes?

Are there better approaches/patterns to have access to this common resource?

Body:
Having an open connection and passing it between classes are generally a bad idea.
Sure, opening a connection is quite a performance hit, but that's already taken care of by the connection pool by reusing already opened connections. A remark though: always wait as long as possible to call connection.Open(), especially in multithreaded code since this will assign the connection to your method (wich will potentionally increase the needed amount of open connections to the database).

To make your classes as generic as possible, I would recommend having a base class exposing a method with IDbConnection, and your repositories will have a more generic implementation.

internal abstract class Repository
{
    private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["myconnectionstring"].ConnectionString;

    protected IDbConnection GetConnection()
    {
        return new SqlConnection(ConnectionString);
    }
}

public class MyRepository : Repository
{
    public IEnumerable<object> Get()
    {
        using (var connection = GetConnection())
        {
            connection.Open();

            ...
        }
    }
}


问:
Translation algorithm - combinations to indices
I have a deck of 52 poker cards represented as array of int - [0, 1, ... 51].

There are 2.598.960 possible combinations of 5 cards. I can generate all combinations like this:

```<code>#id      #combination
0 -       0,  1,  2,  3,  4
1 -       0,  1,  2,  3,  5
2 -       0,  1,  2,  3,  6
   ...omitted data..
2598957 - 46, 47, 49, 50, 51
2598958 - 46, 48, 49, 50, 51
2598959 - 47, 48, 49, 50, 51
</code>```

How I can effectively find #id for given #combination and #combination for given #id?

答:
For the first card you have 52 options for the second you have 51 and so on. You need to encode a sequence c1, c2, c3, c4 and c5 where there are 52, 51, 50 ,49, 48 options resp.

You can adjust the numbers by counting how many of the previous numbers are smaller: a5 = c5 - sum(x < c5 for x in [c1, c2, c3, c4])

you can simply encode it as a single integer  output =(((a1*51 + a2)*50 + a3)*49 + a4)*48 + a5.

you can extract it by using the modulo operation and integer divide.

```<code>int input = //...

a5 = input%48;
input/=48;
a4 = input%49;
input/=49;
a3 = input%50;
input/=50;
a2 = input%51;
input/=51;
a1 = input;
</code>```

And then the reverse operation is needed to adjust them all back into the range [0..52).

Body:
For the first card you have 52 options for the second you have 51 and so on. You need to encode a sequence c1, c2, c3, c4 and c5 where there are 52, 51, 50 ,49, 48 options resp.

You can adjust the numbers by counting how many of the previous numbers are smaller: a5 = c5 - sum(x < c5 for x in [c1, c2, c3, c4])

you can simply encode it as a single integer  output =(((a1*51 + a2)*50 + a3)*49 + a4)*48 + a5.

you can extract it by using the modulo operation and integer divide.

int input = //...

a5 = input%48;
input/=48;
a4 = input%49;
input/=49;
a3 = input%50;
input/=50;
a2 = input%51;
input/=51;
a1 = input;

And then the reverse operation is needed to adjust them all back into the range [0..52).


答:
Just to add a suggestion to the other solutions.

In the biomedical world we often search for specific strings of data (ie genetic patterns).

Research has shown that attacking the parent string in the reverse direction, the last entry to the first, is faster that going forward through the string.

I guess this is some how related to slurping in all the data into memory, it then being quicker to pop the last entry off the end.

I remember being really chuffed when I had this idea, I thought I was thinking well outside the box.

I expect the same principle would apply to simple arrays also where the search time is proportional to the size.


答:
We were told numbers could be up to about 10^12 and about 20% of numbers would be used. That is 2 * 10^11 numbers actually used. With these numbers, the best you can do is a bitmap of about 125 GBytes, and if you can't afford the RAM, an SSD drive and virtual memory will have to do. You should probably measure whether "normal" file access is faster than relying on virtual memory. Obviously a bitmap that exceeds physical memory will be slooooooow. It's still the fastest that you can do.

If the map is less dense then you can do it quicker. Say you have a billion numbers from 0 to 10^12. So on average a range of thousand numbers only contains one number. You could have a bitmap to represent the fact that "the range 128k to 128k + 127 contains at least one number". That takes 8 billion bits or one GB, fitting into RAM, so you check this map first, chance is 87% that you find there is no number, so whatever slower algorithm you wanted to use will only be used for one in eight numbers.

Obviously your access pattern will be incredibly important. If 99% of the time you are searching for numbers that are actually present then the method described above will be useless.


问:
Is it better to make database calls or external API calls first in the context of a single Web request?
Say you have a Web app that uses data from both a database and an external API, and for certain pieces of functionality, you need to call in to both in order to read/write the necessary data.

Is it better to:

A) First start a DB transaction and then make all of the necessary calls to the DB BEFORE calling in to the API, and then roll the transaction back if the API call fails.

OR

B) Make the API call first and then call in to the DB upon success.

Pros and Cons of each option as I see them:

The big Pro with A is that data integrity remains intact, regardless of any failures.  If the DB calls fail before I hit the API, then I return before making the call, and if the API call fails, I can roll back my DB transaction.  If everything succeeds, then I commit the DB transaction and go on my merry way.

The big Con with A is that due to the transaction, the DB will be locked for an uncontrollable amount of time during the external API call, potentially affecting performance.

The Pros and Cons of B are essentially the opposite of the Ps and Cs for A. The Pro is that you avoid a DB lock during the API call.  The Con is that if the API call succeeds but your DB calls fail, you essentially need to roll back the changes you just made thru the API, which may or may not be possible for any given context.

I'm partial to option A personally, as I'm a big fan of "better safe than sorry" approaches, but what do you all think?

答:
It's far easier to roll back changes made in a database that it is at the "other end" of an API call.

Here's how I'd do it:

Start a database transaction and make the changes there.

Do the API calls.

If those work, then commit the database changes; if not, roll the changes back.


问:
How do you maintain productivity outside of work? (Programming Schedule)
I enjoy programming, but programming at work is just that, work. I would like to further develop my own personal interests in programming. Throughout the week I imagine myself completing a small project on the weekend or finishing up a programming related book. However, in reality I often fall short of my expectations. I often will get just one or two chapters of reading done and even less coding. In reality I will spend time surfing the net, watching television, or visiting friends and slacking off... because it is the weekend. But when Sunday evening rolls around I often reflect on my weekend and I am sorely disappointed with my use of time.

So my question is how do you maintain your productivity outside of work? I am sure some programmers could care less about programming on their free time. Although, I think the majority of programmers, especially on stackexchange, are passionate about programming.

Should I spend the weekend programming, or will I burn out and resent programming if I dedicate that much time to it?

How should I go about programming on my free time? Should I set a schedule? How much time should I dedicate to it? Most importantly how do I follow that schedule? Its only human nature to procrastinate.

I know there is a lot of questions here. Feel free to answer the ones that relate to how you remained focused outside of work. I am passionate about programming but after 40 hours of programming it can be difficult to maintain that enthusiasm.

答:
Do you have a specific application that you would like to develop in your free time? By the sound of it, you just haven't found an interesting enough application or challenge to catch your interest yet and so you fall back to surfing the net.

I suspect if you found a project that interested you enough, this topic would be a non-issue, you would just naturally work on it whenever you can.

ContentLicense: CC BY-SA 2.5


问:
List comparing techniques for faster performance
I need to cross names from two lists, and find all occurrences of one name in the other. The lists are too big, one have 50k elements and the other 400k.

For a small list I would use two foreach cycles or Linq, but I can't be running the program for days.

What is your advice to perform a fast comparisons?

EDIT: In some cases I need to find more than occurrence on the second list, by other words, all the names are repeated and have different information associated. Then the intention is to merge the information from the two sources.

答: Finding things in one set that match those in another set and merging data is something that relational databases excel at. If this is something you need to do a lot, loading your lists into tables in your choice of SQL DB is probably your best option.</p>


问:
Factory for creating a singleton instance
We have some legacy code that has a bunch of singletons all over the place (written in C#).

The singleton is a fairly "classic" implementation of the pattern:

```<code>public class SomeSingleton
{
    private static SomeSingleton instance;

    private SomeSingleton()
    {
    }

    public static SomeSingleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new SomeSingleton();
            }

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

Note that thread safety is not a concern, so no locks are used.

In order to make the code more testable, and without making too many modifications, I'd like to modify this code to delegate the creation of the singleton instance in another class (a factory or similar pattern).

This can assist in creating a "test" instance for testing purposes, or the real version, as it is used now.

Is this a common practice? I could not find any reference to such pattern being used.

答:
This calls for inversion of control. Just start by adding an interface to SomeSingleton say ISomeSingleton. Then all consumers of ISomeSingleton will just get an constructor parameter of ISomeSingleton.

Example:

```<code>public class Consumer1 {
    readonly ISomeSingleton _mySingleton;
    public Consumer1(ISomeSingleton mySingleton) {_mySingleton = mySingleton;}
}

public interface ISomeSingleton{//All your methods you ned.}

public class SomeSingleton : ISomeSingleton
{
    private static SomeSingleton instance;

    public SomeSingleton() // constructor is now public
    {
    }

    public static SomeSingleton Instance // todo remove this when all consumers follow inversino of control pattern.
    {
        get
        {
            if (instance == null)
            {
                instance = new SomeSingleton();
            }

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

When no consumer calls the SomeSingleton directly you can just remove it. This allows you to make the change at your own pace.

Now you just need to figure out how to instantiate SomeSingleton. You can just do this manually or you can start using an IOC container of you feel like it.

In testing you can just create a different implementation of ISomeSingleton.

Body:
This calls for inversion of control. Just start by adding an interface to SomeSingleton say ISomeSingleton. Then all consumers of ISomeSingleton will just get an constructor parameter of ISomeSingleton.

Example:

public class Consumer1 {
    readonly ISomeSingleton _mySingleton;
    public Consumer1(ISomeSingleton mySingleton) {_mySingleton = mySingleton;}
}

public interface ISomeSingleton{//All your methods you ned.}

public class SomeSingleton : ISomeSingleton
{
    private static SomeSingleton instance;

    public SomeSingleton() // constructor is now public
    {
    }

    public static SomeSingleton Instance // todo remove this when all consumers follow inversino of control pattern.
    {
        get
        {
            if (instance == null)
            {
                instance = new SomeSingleton();
            }

        return instance;
        }
    }
}

When no consumer calls the SomeSingleton directly you can just remove it. This allows you to make the change at your own pace.

Now you just need to figure out how to instantiate SomeSingleton. You can just do this manually or you can start using an IOC container of you feel like it.

In testing you can just create a different implementation of ISomeSingleton.


答: Sort the small list with an efficient sorting algorithm, traverse the big list and for every item in the big list use a binary search to find whether there's a matching item in the small list.</p>

Title: List comparing techniques for faster performance

Body:
I need to cross names from two lists, and find all occurrences of one name in the other. The lists are too big, one have 50k elements and the other 400k.

For a small list I would use two foreach cycles or Linq, but I can't be running the program for days.

What is your advice to perform a fast comparisons?

EDIT: In some cases I need to find more than occurrence on the second list, by other words, all the names are repeated and have different information associated. Then the intention is to merge the information from the two sources.


答:
Sort both lists with an efficient sorting algorithm (or ensure that the lists are "pre-sorted" by whoever/whatever created them).

Then, if the first name in both lists is the same you've found a match, otherwise discard whichever name is "earlier"; and do that until one of the lists are empty.

Some crude pseudo-code:

```<code>    do {
        status = compare(shortList[i], longList[j]);
        if(status == EQUAL) {
            // Found match!
            i++;
            j++;
        } else if(status == EARLIER) {
            // No match, discard first entry in short list
            i++;
        } else {
            // No match, discard first entry in long list
            j++;
        }
    } while( (i < shortListEntries) && (j < longListEntries) );
</code>```

Body:
Sort both lists with an efficient sorting algorithm (or ensure that the lists are "pre-sorted" by whoever/whatever created them).

Then, if the first name in both lists is the same you've found a match, otherwise discard whichever name is "earlier"; and do that until one of the lists are empty.

Some crude pseudo-code:

    do {
        status = compare(shortList[i], longList[j]);
        if(status == EQUAL) {
            // Found match!
            i++;
            j++;
        } else if(status == EARLIER) {
            // No match, discard first entry in short list
            i++;
        } else {
            // No match, discard first entry in long list
            j++;
        }
    } while( (i < shortListEntries) && (j < longListEntries) );


答:
Don't spend your entire weekend doing any one thing anyway, otherwise you'd simply loose interest.

Programming in your free time is definitely a very strong recommendation. Don't choose too many programming languages -- just 1 or max 2, and along with that choose a domain where that language is used and make sure the domain excites you as much as the language itself.

Personally, I don't look at it like this is a weekend and I'd spend time coding or studying. The trick is to do something (albeit small) daily. If open source is your thing, consider adding something new on an ongoing basis. If you like studying about programming, schedule some time on a regular basis where you could put your kindle (:P) or whatever to good use.

Finally, after 10 years in the coding business I might sound a bit cynical but believe me when I tell you that life is an ongoing learning process. Age finally tells you that Newton was right when he was collecting those sea shells :).

Title: How do you maintain productivity outside of work? (Programming Schedule)

Body:
I enjoy programming, but programming at work is just that, work. I would like to further develop my own personal interests in programming. Throughout the week I imagine myself completing a small project on the weekend or finishing up a programming related book. However, in reality I often fall short of my expectations. I often will get just one or two chapters of reading done and even less coding. In reality I will spend time surfing the net, watching television, or visiting friends and slacking off... because it is the weekend. But when Sunday evening rolls around I often reflect on my weekend and I am sorely disappointed with my use of time.

So my question is how do you maintain your productivity outside of work? I am sure some programmers could care less about programming on their free time. Although, I think the majority of programmers, especially on stackexchange, are passionate about programming.

Should I spend the weekend programming, or will I burn out and resent programming if I dedicate that much time to it?

How should I go about programming on my free time? Should I set a schedule? How much time should I dedicate to it? Most importantly how do I follow that schedule? Its only human nature to procrastinate.

I know there is a lot of questions here. Feel free to answer the ones that relate to how you remained focused outside of work. I am passionate about programming but after 40 hours of programming it can be difficult to maintain that enthusiasm.


答: Maybe consider a variation of two-phase commit: Make and commit your changes to the database first, then do your API calls. If the API calls fail, then make compensatory changes to the database (basically, update the database with the previous values). This had the virtue of not locking the database for any appreciable length of time, but gives you a method to keep your changes in sync across the DB and API.</p>

Title: Is it better to make database calls or external API calls first in the context of a single Web request?

Body:
Say you have a Web app that uses data from both a database and an external API, and for certain pieces of functionality, you need to call in to both in order to read/write the necessary data.

Is it better to:

A) First start a DB transaction and then make all of the necessary calls to the DB BEFORE calling in to the API, and then roll the transaction back if the API call fails.

OR

B) Make the API call first and then call in to the DB upon success.

Pros and Cons of each option as I see them:

The big Pro with A is that data integrity remains intact, regardless of any failures.  If the DB calls fail before I hit the API, then I return before making the call, and if the API call fails, I can roll back my DB transaction.  If everything succeeds, then I commit the DB transaction and go on my merry way.

The big Con with A is that due to the transaction, the DB will be locked for an uncontrollable amount of time during the external API call, potentially affecting performance.

The Pros and Cons of B are essentially the opposite of the Ps and Cs for A. The Pro is that you avoid a DB lock during the API call.  The Con is that if the API call succeeds but your DB calls fail, you essentially need to roll back the changes you just made thru the API, which may or may not be possible for any given context.

I'm partial to option A personally, as I'm a big fan of "better safe than sorry" approaches, but what do you all think?


问:
Generics in C# Test Class
I'm learning about unit testing in C#. Languages_Service and PlaceOfWork_Service are classes for SOAP services which Microsoft Navision generated for me. There are several methods that are very similar (see the two examples below).

```<code>[TestMethod]
public void Languages()
{
    string serviceUrl = Helper.GetBaseUrl() + "Languages";
    Languages_Service service = new Languages_Service();
    service.Credentials = Helper.GetCredentials();
    service.Url = serviceUrl;
    Languages_Filter[] filter = { new Languages_Filter() };
    service.ReadMultiple(filter, null, 0);
}
[TestMethod]
public void PlaceOfWork()
{
    string serviceUrl = Helper.GetBaseUrl() + "PlaceOfWork";
    PlaceOfWork_Service service = new PlaceOfWork_Service();
    service.Credentials = Helper.GetCredentials();
    service.Url = serviceUrl;
    PlaceOfWork_Filter[] filter = { new PlaceOfWork_Filter() };
    service.ReadMultiple(filter, null, 0);
}
</code>```

Method ReadMultiple of Language_Service looks like so:

```<code>public Languages[] ReadMultiple([System.Xml.Serialization.XmlElementAttribute("filter")] Languages_Filter[] filter, string bookmarkKey, int setSize)
    {
        object[] results = this.Invoke("ReadMultiple", new object[] {
        filter,
        bookmarkKey,
        setSize});
     return ((Languages[])(results[0]));}
</code>```

Method ReadMultiple of PlaceOfWork_Service looks like so:

```<code>public PlaceOfWork[] ReadMultiple([System.Xml.Serialization.XmlElementAttribute("filter")] PlaceOfWork_Filter[] filter, string bookmarkKey, int setSize) {
        object[] results = this.Invoke("ReadMultiple", new object[] {
                    filter,
                    bookmarkKey,
                    setSize});
        return ((PlaceOfWork[])(results[0]));
    }
</code>```

How could one write something like the (pseudo) code below?

```<code>[TestMethod]
public void GunAndSmokeTestAllSerivces()
{
    Dictionary<String, List<Type>> servicesToTest = new Dictionary<String, List<Type>>();
    servicesToTest.Add("Languages", new List<Type>(new Type[] { typeof(Languages_Service), typeof(Languages_Filter) }));
    servicesToTest.Add("PlaceOfWork", new List<Type>(new Type[] { typeof(PlaceOfWork_Service), typeof(PlaceOfWork_Filter) }));
    foreach (KeyValuePair<String, List<Type>> entry in servicesToTest)
    {
        var t1 = entry.Value.ToArray()[0];
        var t2 = entry.Value.ToArray()[1];
        SoapHttpClientProtocol service = (SoapHttpClientProtocol)Activator.CreateInstance(t1);
        service.Credentials = Helper.GetCredentials();
        service.Url = Helper.GetBaseUrl() + entry.Key;
        object[] filter = { (object)Activator.CreateInstance(t2) };
        service.ReadMultiple(filter, null, 0);
    }
}
</code>```

Languages_Service and PlaceOfWork_Service are subclasses of System.Web.Services.Protocols.SoapHttpClientProtocol.

答:
I modified Ben Aaronsons idea slighly:

```<code>public class NavisionSoapService : SoapHttpClientProtocol
{
    public object[] ReadMultiple([System.Xml.Serialization.XmlElementAttribute("filter")] object[] filter, string bookmarkKey, int setSize)
    {
        return this.Invoke("ReadMultiple", new object[] {filter,bookmarkKey,setSize});
    }
}

    [TestClass]
    public class SoapServiceGunSmokeTests
    {
        private void Test<TService>(string urlSuffix)
            where TService : NavisionSoapService, new()
        {
            string serviceUrl = Helper.GetBaseUrl() + urlSuffix;
            TService service = new TService();
            service.Credentials = Helper.GetCredentials();
            service.Url = serviceUrl;
            // something is fishy here: object [] filter = [System.Xml.Serialization.XmlElementAttribute("filter")] object[] filter;
            service.ReadMultiple(filter,null,0);
        }
    [TestMethod]
    public void PlaceOfWork()
    {
        Test<PlaceOfWork_Service>("PlaceOfWork");
    }
}
</code>```

Now, I get: "The type 'PlaceOfWork_Service' cannot be used as type parameter 'TService' in the generic type or method 'MyProject.SoapServiceGunSmokeTests.Test(string)'. There is no implicit reference conversion from 'MyProject.WSPlaceOfWork.PlaceOfWork_Service' to 'MyProject.NavisionSoapService'.

Obviously, I am doing something wrong with the superclass NavisionSoapService. How do I have to do it?

Moreover, somehow I can not manage to import System.Xml.Serialization I get "The type or namespace name 'Xml' does not exist in the namespace 'System' (are you missing an assembly reference?)". I added System.Xml.Serialization (Version 4.0.0.0) as a reference.

Finally, I am doing something wrong by creating an instance of filter (see code above).

Title: Generics in C# Test Class

Body:
I modified Ben Aaronsons idea slighly:

public class NavisionSoapService : SoapHttpClientProtocol
{
    public object[] ReadMultiple([System.Xml.Serialization.XmlElementAttribute("filter")] object[] filter, string bookmarkKey, int setSize)
    {
        return this.Invoke("ReadMultiple", new object[] {filter,bookmarkKey,setSize});
    }
}

    [TestClass]
    public class SoapServiceGunSmokeTests
    {
        private void Test<TService>(string urlSuffix)
            where TService : NavisionSoapService, new()
        {
            string serviceUrl = Helper.GetBaseUrl() + urlSuffix;
            TService service = new TService();
            service.Credentials = Helper.GetCredentials();
            service.Url = serviceUrl;
            // something is fishy here: object [] filter = [System.Xml.Serialization.XmlElementAttribute("filter")] object[] filter;
            service.ReadMultiple(filter,null,0);
        }
    [TestMethod]
    public void PlaceOfWork()
    {
        Test<PlaceOfWork_Service>("PlaceOfWork");
    }
}

Now, I get: "The type 'PlaceOfWork_Service' cannot be used as type parameter 'TService' in the generic type or method 'MyProject.SoapServiceGunSmokeTests.Test(string)'. There is no implicit reference conversion from 'MyProject.WSPlaceOfWork.PlaceOfWork_Service' to 'MyProject.NavisionSoapService'.

Obviously, I am doing something wrong with the superclass NavisionSoapService. How do I have to do it?

Moreover, somehow I can not manage to import System.Xml.Serialization I get "The type or namespace name 'Xml' does not exist in the namespace 'System' (are you missing an assembly reference?)". I added System.Xml.Serialization (Version 4.0.0.0) as a reference.

Finally, I am doing something wrong by creating an instance of filter (see code above).


问:
Should we always DRY? Any edge case examples of when not to?
I've only ever been working in higher level languages such as C# and JavaScript.

A couple of moments ago someone asked this question on SO.

Now I'm curious to know, for some of the lower level languages or specifically the ones I haven't encountered, any other for that matter...

What would be a valid situation to not apply the DRY principle / guideline?

I realize that thing like unit tests are an example of this, and the link shared by @mkk is an excellent example of DRY-over engineering, but in discussion with one of my colleague we where attempting to think of a few other just out of a matter of interest.

答:
SQL Server. Scalar user-defined functions in a T-SQL query prevent a parallel execution plan and can also have other negative effects on performance.

Hugo Kornelis explains it nicely here.

...it’s easy to see why using functions to encapsulate and reuse common computations is considered a best practice. But SQL Server isn’t a traditional programming language. It’s a declarative language, with an optimizer that has been designed to optimize the execution order within queries to make sure that the results are returned as fast as possible


答:
The problem with lower level languages is not that it "may be a good idea" not to stay DRY when using the specific language. The problem is that it can be hard to impossible to stay DRY if your language lacks certain means of abstraction.

For example, if your language does not provide any kind of higher order functions (or at least pointer-to-functions), try to implement something like a generic, reusable root finder, for example, a generic Newton solver. If your language does neither support generics nor an "common object base class" nor a void *, try to implement something like a reusable list.

For such examples, it maybe the only feasible solution to implement an algorithm or datastructure more than once, each time adapted to the specific situation.

Title: Should we always DRY? Any edge case examples of when not to?

Body:
I've only ever been working in higher level languages such as C# and JavaScript.

A couple of moments ago someone asked this question on SO.

Now I'm curious to know, for some of the lower level languages or specifically the ones I haven't encountered, any other for that matter...

What would be a valid situation to not apply the DRY principle / guideline?

I realize that thing like unit tests are an example of this, and the link shared by @mkk is an excellent example of DRY-over engineering, but in discussion with one of my colleague we where attempting to think of a few other just out of a matter of interest.


答:
Having a happy, healthy life is all about finding balance in the things you do.  Some weeks you'll find yourself coding all weekend and wonder where the weekend went.  Other weeks you'll find that you didn't even open up that book you'd plan on reading.

Don't get too down when reality doesn't meet your expectations, life happens.  If you set small, simple, concrete goals then it will be much easier to keep your weekend programming needs moving forward.  But also set aside time for yourself... there's nothing wrong with being a couch potato every once in a while.


答:
There's always a time when you simply have to break a rule, even if everything you know as a coder says there must be another way.

Good examples of when DRY may not be the best strategy to use right off the mark include:

Code that, for all you know, is a one-off. I generally have a "three-strikes" rule for refactoring; "make it work, make it clean, make it SOLID". If I'm writing a line of code to do something, and I have another line of code somewhere else that would do that thing with a tweak here and there, then I hit Ctrl-C, Ctrl-V and don't give it a second thought. Why? Because I'm not getting paid for pretty code, I get paid for working code. Easy-to-maintain, reusable code is for my benefit, and it's only a benefit if I expect to go in and make changes. If I don't, then until I'm proven wrong, ivory-tower development rules just get in the way of a working program (and my paycheck). HOWEVER, once I am proven wrong, by having to go back in that code file and make a change, then I have to be disciplined enough to go back in and clean up, paying off the "technical debt" early instead of compounding it with more spaghetti.

Testing code. This is a significant subset of the above point. If you are writing a test for a variation on existing behavior, and you have a test exercising pre-existing behavior, then copy the test. Tests are typically "write once, run many", with very little maintenance needed once the tests go green, so they're the perfect example of a piece of code you'll likely never see again. Of course, you still have to be disciplined enough that the first time a change is required to both tests (or the fourth of fifth time you copy the same test to make another), you look for ways to ensure further changes happen in one place, not two (or six or ten or...).

Implementations of an interface or abstract base class. Even though you might think of these as being the primary way to avoid repeating yourself, the truth is that setting up multiple classes as implementations of some base type involves a lot of very similar-looking boilerplate, not all of which you can avoid. This is especially true if the hierarchy follows a Template Method pattern where a big driving function in a base type depends on specifics in derived types; if you have ten classes implementing this base type, odds are good at least two of them will end up with the same implementation for one of the stubbed methods. Not enough to justify pulling that implementation up into the base, but it's repeated code. Interfaces, which can't have any code, suffer from duplicate implementations almost by definition.

There are other examples, but these are a few of the ones I typically encounter. In short, DRY is not a hard and fast rule, it's just one of those things you keep in mind, and when you do repeat yourself, it's a "code smell", indicating you might be incurring technical debt or just generally screwing up. When your code "smells", it's worth a second look, but a smell is not always a genuine problem, and even if it is it may not be one worth solving (or even one that is possible to solve).


问:
Where we should not use MVC?
I have a software engineering course project that we should design a web application, so I've decided to read about software architecture patterns.

I've read a lot about what is MVC and its structure, also I know about advantages of breaking an application into layers.

But I can not find an answer to this question, so I appreciate anybody who can tell me:

Where should we not use MVC pattern in a web application?

答:
In my experience, a web application would have to be trivially small to not benefit from the organization and decoupling that MVC provides.

Perhaps a bit of explanation about the MV* family of architectural patterns is in order.

The MV* patterns concern themselves primarily with the User Interface.  Their primary purpose is to provide decoupling between the UI and the rest of the application.

In Winforms and other event-driven UI, we create a user interface by inserting objects that represent form elements such as text boxes into a Form container, and then attach events to those objects (such as Click or LostFocus) to perform actions in code.

I've drawn a thick arrow between the boxes to represent the fact that both data and commands are passed back and forth; this creates a user interface that is tightly-bound to the rest of the application.  Anyone who has ever built an application this way knows that it's difficult to make it large, because you quickly end up with a plate of spaghetti code.

To solve this problem, we add a Presenter (sometimes called a Supervising Controller) to the mix, creating Model-View-Presenter.  This arrangement pushes most of the UI logic out of the View, and into the Presenter, allowing for better maintainability.

Notice that I've drawn a thin line between the Model and the Presenter, indicating that only data is passed back and forth, not commands.  This provides some decoupling between the Model and the View.

Model-View-ViewModel is very similar, except that there's a ViewModel instead of a Presenter.  This arrangement is seen most often in Windows Presentation Foundation and in Single-Page Web Applications (SPA) using an MVVM framework such as Angular. In addition to command and control, MVVM also concerns itself specifically with data binding.

Model-View-Controller is primarily associated with web applications.  In MVC, commands aren't routinely exchanged between the Model and the View.  Instead, the View is POSTed to the Controller using an HTTP verb, and the controller decides what to do with it.  Most of the domain logic is pushed back into the model.

Because MVC still binds the view rather tightly to actual domain objects, you can insert a View Model to get some additional indirection.

This View Model is not a command layer, like it is in Model-View-ViewModel; it's simply a data translation layer between the model and the UI.  A good example of this would be a ViewModel for an invoice, which would contain everything that you need to display and update an invoice, such as names, addresses, and invoice line items.  This data would then map to actual Model domain objects, such as Customers, Products, Pricing, etc.

When to use them?

When you need them for the purpose that they serve: to decouple the UI from the rest of the system.  The flavor you use will depend on the kind of web application you are building.  If your pages are mostly being generated server-side, you will use MVC.  If your pages are being generated mostly on the client, using Javascript (as in a SPA application), you will use MVVM.

Title: Where we should not use MVC?


答:
My suggestion would be to slurp the large list into a hash set, then use that to match items from the small list.

A hash set is a structure that stores elements in an indexable memory structure, like an array, where the position of the element is equal to some hash value calculated using the object. That means that looking for a value in the hashset is a relatively fast operation; calculate the hash of the object you're looking for, go to that index, and check the actual objects stored there, which for a good implementation will be a very small number (hashset implementations have to strike a balance between the size of the hash and therefore the number of first-dimension elements, and the number of collisions and therefore the average number of items in each element).

Ideally, hashsets approach a constant lookup time (specifically it's O(log2^HN) where H is the bitsize of the hash function, so for all N < 2^H it's effectively constant), so overall, your matching algorithm would approach linear complexity. Two major downsides are first that unless you have access to a built-in efficient implementation (Java's HashMap is built on this structure, as is .NET's Dictionary class), you have to roll your own which is quite a bit of code, and second, hashsets are real memory hogs because there's virtually guaranteed to be a lot of empty spaces in the array unless your implementation varies its hash function based on expected or actual capacity (which could, if naively done, involve re-hashing every element several times as the first dimension is extended to limit growth in the second dimension).


答:
DRY exists for a reason, because the more places that the same code exists, the more chances there are of bugs arising from one of those places not being changed when the system needs to change. It is also, obviously enough, easier to test if you only have any given part of your code in one place. Consequently, in most cases where I need to do something more than once I will break it out into it's own function or method.

One place where I think repetition is alright, or even helpful, is when you have the same code working with different intents - so you might have a function or method that shows very similar behaviour, but in one place it is part of the system for retrieving a user from an authentication system and in another it is retrieving some data from a store. Even if the code is identical this can exist in different places because it is part of different flows and with these divergent intentions it is very likely that they will diverge at some point in functionality. If I was sharing the code at that point, I would have to make things more complex and less readable.

That said, if I have the same or very similar code in multiple places that starts to smell WET to me and I will certainly get to thinking about whether I could be abstracting the relevant behaviour in a way that would facilitate sharing.


问:
Why is Javascript used in MongoDB and CouchDB instead of other languages such as Java, C++?
I asked this question on SO but was suggested to try here. So here it goes:

My understanding of Javascript so far has been that it is a client-side language that capture events and makes a web-page dynamic.

But on reading the comparison between MongoDB and CouchDB I noticed that both are using Javascript. This makes me wonder the reason behind the choice of JavaScript over other conventional languages.

I guess I am trying to understand the role of JavaScript and its advantages over other languages.

Update: I am not asking about the languages / drivers supported by the two databases. The comparison says:

Both CouchDB and MongoDB make use of Javascript. CouchDB uses Javascript extensively including in the building of views.

MongoDB also supports running arbitrary javascript functions server-side and uses javascript for map/reduce operations.

My lack of understanding pertains to why is Javascript being used at all for the backend work. Why is it preferred for building views in CouchDB, or for using map/reduce operations? Why C/C++ or Java were not used? What are the advantages in using Javascript for such back-end work?

答:
Event driven programming model

JavaScript was created with an event driven non-shared-memory approach to computing. In UI development this is completely old hat. There is no assumption that your "application" is in control of a process. There is no process API. Nor is there a main function.

Your "application" is a collection of scripts that will be executed when a particular thing happens such as

the script is loaded in the browser

the html page loading reaches a certain point

on a particular user interaction with a given element

This matches quite well with the small chunks of processing logic needed for data transforms.

Scripting Language

Being able to execute without a compile stage means that processing instructions can be stored easily. You can save the script easily as text and pass it around without any special data types or knowledge.

Quite Simple, Stable and Backwards compatible

The code you write today isn't that much different from 10 years ago. Versioning isn't likely to be much of an issue for people embedding it.

Performant

There are several good open source engines out there with a ton of work put into them. It executes quite a bit faster than many alternatives.

Curly Braces

Many people are restricted in their comfort with a range of programming languages. They only know how to program Java or C# for instance. So they expect to learn JavaScript easily because it looks familiar. That is of course an illusion. When I learned Python it was at pretty much the same pace as learning JavaScript. Syntax is only emotionally significant assuming it isn't completely obscure.


答:
When runtime efficiency matters, repeating yourself (e.g. unrolling loops) might be beneficial because some work that should be made at runtime is done earlier. Ideally, such things should be done by a compiler.

Also, when you work with a language that does not offer the kind of genericity that would allow you to avoid repeating yourself, you might need to duplicate things.

Apart from that, stick with the two rules of DRY:

Do not repeat yourself

See 1.


问:
Bad Practice using Auto Generated Classes for Data Access
I've seen this before but haven't found concrete reasons.

When you add Entities to your EF model, EF auto generates classes for these entities.

In terms of DataAccess, why is it preferred to not use these Auto Generated Classes, and instead use your own Data Models for Data Access.

Ex.

```<code> EFAutoGeneratedClass = //query = BAD

 SeparateModelClass = //query = Good
</code>```

答:
A database, being data and generally being optimized for storage efficiency and retrieval, does not necessarily map directly to business domain classes. The less perfectly an auto-generated class fits into a proper domain model the greater the code maintenance problems.

Database design is now driving domain design.

A Domain model should model your domain, not your database.

How the hell does one decouple from a data-store if the domain is the data store?

Extra code to get DB-classes to work with proper domain classes.

Good design tends to be given short shrift because... "click" - look! instant classes and their CRUD[1] code. Design done.

If you insist on ensuring correct, consistent storage of domain object data then you still must write CRUD code to integrate the instant-classes.

Rational might be: "Let's read all that data now - avoid using the sloooow I/O." This old, original, spiel about .NET "working disconnected" is @(#*$&; it makes for very slow UI response.

In the final analysis the database is just an implementation detail.

[1]: Create Read Update Delete


问:
Managing sets of configuration data for an Excel/VBA program
I have two versions of an "Excel-Tool", i.e. a spreadsheet with a lot of vba code. Lets say, this tool is used to monitor two facilities. Both facilities differ in minor aspects.

That means, I have magic numbers in both versions to set the correct ranges for each facility in the spreadsheets.

I have refactored the vba to isolate the magic numbers. I have separated the business logic into one module and the magic numbers for ranges in a second module. Now I can reuse the logic module in both versions and only have to maintain one logic module and don't have to keep two files synchronized. That is a great improvement.

But it feels like I'm not done. I want to have only one masterfile (excel+imported vba modules) to distribute and some kind of configuration file to store the magic numbers for the actual facility.

Has anybody experience with such concept? Is there a primer or even an out-of-the-box solution for configuring a vba-program?

2015-04-29 Edit:

I didn't want to post code in the first place, but let me clarify through numbers.

Let's say we have to facilities, each with a number of machines. The whole business is about generating facility performance charts. The rawdata for each facility (and each machine) has the same format, but the number of machines varies between facilities.

I have a vba-function to create standardized charts. This function is called for each machine with an array of ranges, pointing to the rawdata.

For facilitiy 1 it could look like:

```<code>Set Inputdata(0) = Sheet1.Ranges("A2:A20")
Set Inputdata(1) = Sheet1.Ranges("B2:B20")
Set newChart = ChartCreator("Facility 1", Inputdata)
</code>```

And for facility 2:

```<code>Set Inputdata(0) = Sheet1.Ranges("A2:A25")
Set Inputdata(1) = Sheet1.Ranges("B2:B25")
Set Inputdata(2) = Sheet1.Ranges("C2:C25")
Set newChart = ChartCreator("Facility 2", Inputdata)
</code>```

I have separated the logic, the ChartCreator, but still have those numbers. Since the data for Sheet1 is generated by a SQL-Query, something similar is going on there.

If I would use the suggestion of James, I would have another sheet with the configuration. I still have to maintain two excel-files with differences in a configuration-sheet.

But what I want is to have an Excel-Sheet I can pass to both facilities and add something like an ini-file to store the specific data. Therefore I can just keep one generic copy of the excel file for me to add new stuff or do bugfixing and then I can just sent a new version of that out to both facilities and don't have to think about configuration.

答:
The right approach for this is to have the configuration information in a worksheet - then it can be changed even by people who don't want to touch VBA.

The architecture is to have a macro-enabled worksheet with a sheet called, say, Configuration, with each piece of configuration in a cell which is a named range that the macro can refer to. You should have descriptions and help in this worksheet too.


问:
What OpenID Connect flow is right for me?
Here's the deal. I have a .NET MVC5 web application that I'm moving up to the OpenID Connect standard.

I also would like to be able to access controller methods from a mobile app (much like an API) to send and receive JSON data.

If I understand it correctly, the Implicit Flow has clients retrieving an id_token from the OpenID provider for the sake of authentication. In the case of a mobile app, if I retrieve an id_token for a client_id that matches the client_id of my web application, I should be able to use it to authenticate the app with my web back-end, right?

And an Authorization Code Flow gives me an access token, which allows me to retrieve refresh tokens so I retain authorization for longer periods of time. Does this authorization then automatically apply to my web back end, or must I also ping my web site in order for it to assign me an authorization code it retrieves from, say, Google?

Lastly, there's a Hybrid Flow that combines the two, giving an id_token for authentication, an access token that can be used immediately to access my web application resources, and an offline_access code that allows the web application to get refresh tokens on the user's behalf even when they're not using the application.

Am I thinking about this all wrong? Is my method of authenticating with my web application from my native Android client really not an OpenID Connect problem at all? What would any of you use in this situation?

答:
As it turns out, it's sort of a combination of the Authorization flow and the Implicit flow. The Implicit flow is for client-based applications, and the authorization flow allows for server-to-server access, I think.

What ended up being the right answer is retrieving an access_code from Google, with a specific audience specified. The audience is the client_id of my web application. The access_code is then given to the web application to authenticate my client (be it browser or mobile app). The web application exchanges the access_code for an id_token and a refresh_token using the Google token endpoint. Then these tokens are verified and used to authenticate subsequent requests.

From there the user identity is authenticated, and it's up to me how I'd like to handle that - be it token-based authentication for the native mobile app or cookie authentication for the browser.


问:
What is a reasonable and secure password requirement for user registration?
This is the password policy I just got from UPS (just for package status checking):

Your password must be between 8 and 26 characters long. It must
  contain at least three of the following character types: lowercase
  letters, capital letters, numerals, special characters, or spaces. The
  password may not contain your User ID, your name, or your e-mail
  address. (SSO_1007)

I actually have to wrack my brain somewhat to generate this password, but not only that, most importantly, I am sure that after 3 days I will forget what this password is.  Users won't be so happy.  Password reset can be frequent.  I think users will try to avoid using the site unless they have to.

What is a reasonable and secure password policy when setting up a website?   I think some companies may fear some hackers trying passwords a million times or more, so they add all those requirements for "special characters, lower case, upper case", but won't it be reasonable to turn off the account or just disable the password and require a password reset if a user has tried 30 times or 100 times?  Or, add a 5 second delay each time after the user tried 30 times?  If so, then those special characters won't be that much needed.

答: The complexity of password requirement should be balanced with the contents of your sites. A bank should require a highly complex password (uppercase, lowercase, number, and special characters). However, if the content is trivial, like saved searches and tracking numbers, the password requirement should be relaxed. Minimum length of 6 characters should be sufficient. Otherwise, it will simply annoy your audience and deter them from creating a login.</p>


问:
Including compiled application in build
I currently maintain the build process of a suite of applications through TFS.  Our nightly build, in addition to compiling the code checked in that day, uses InstallAware to produce an installer for the application suite.  In addition to all of the items that have been compiled, there are three applications that have already been compiled and must be included in the installer.  What is the best way to get these applications to the folder where InstallAware expects to pick them up so they are properly included in the installer?</p>

答:
Assumed your additional applications are not part of the nightly build: add the application binaries to the repository. See them as "artifacts", since they have to be created by a manual build step outside of your regular build.

A more sophisticated option might be to utilize NuGet for this, but that would mean to setup your own NuGet server, which is probably oversized for your needs.

Title: Including compiled application in build


问:
What do you get when you cross a multi-precision integer with a floating-point number?
I'm working on adding multi-precision integers to the suite of numeric types in my APL interpreter, but I'm not sure what to do about the odd type-combinations that now arise. I now have the following types:

```<code>IMM "atomic" small integer
FIX full-width integer
FLO floating-point double
MPI multi-precision integer
</code>```

I have a variable which controls which larger type to use for integer overflow, either FLO or MPI. Mixed MPI/IMM/FIX operations, since they're all integers, can simply promote to the widest type and produce a result of that type. And mixed FLO/IMM/FIX operations can follow the same pattern since a double can comfortably accommodate all the values of a 32-bit integer. This covers most of the cases. But it leaves me with these type combinations which don't have an obvious (to me) rule to follow.

```<code>FLO {+-*/} MPI
MPI {+-*/} FLO
</code>```

Having written this out, I suppose there really is an obvious solution (multi-precision floating-point). But I don't want to do that right now. Is there a sensible shortcut I can take (for now)?

As a "worst case" scenario that at least delivers some kind of result, I can implement conversions between these two types. But there's potential loss of data each way.

```<code>FLO -> MPI loses fractional part of floating-point number
MPI -> FLO loses precision from integer
</code>```

答:
Another option is to add a rational number type. This is stored as two integers, which usually will need to be multi-precision, and can represent any floating point value including the result of an operation between floating point and a multi-precision integer.

This way there is no loss of information. But there is a lot of work involved and should only be done if the user wants it.


问:
fast, say O(log2(N)), sliding median algorithm
So I know how to do a fast O(log2(N)) sliding max or sliding min algorithm.

Brookes: "Algorithms for Max and Min Filters with Improved Worst-Case Performance"  IEEE TRANSACTIONS ON CIRCUITS AND SYSTEMS—II: ANALOG AND DIGITAL SIGNAL PROCESSING, VOL. 47, NO. 9, SEPTEMBER 2000

But I just cannot figure out how to do a sliding median without first sorting the buffer (or at least sorting it half way) and then picking the value halfway into the buffer (or midway between the bottom and the top of the sorted buffer).

Given a finite-length buffer (length N) that is chronologically sorted (like a FIFO) and another with the same N values sorted by value, then when the buffer window "slides" by one and the oldest value falls offa the edge and a new one is input, to insert that new value into the sorted buffer, that is an O(N) operation (probabilistically).

What's a faster way to do this?

答: See https://stackoverflow.com/q/5527437/10396 for an implementation of a rolling median that uses a min-max heap to process each new sample in O(lgN).  The heap keeps the data loosely sorted into two groups, one bigger than the median, one smaller.  For each new sample, it swaps the the oldest item in the heap with the newest one. Rebalancing the heap takes up to 2 O(lgN) steps: a sift-up to make sure the new item is closer to the median than any parents, and maybe a sift-down to push it down the other side.</p>


问:
Should I validate a method call's return value even if I know that the method can't return bad input?
I'm wondering if I should defend against a method call's return value by validating that they meet my expectations even if I know that the method I'm calling will meet such expectations.

GIVEN

```<code>User getUser(Int id)
{
    User temp = new User(id);
    temp.setName("John");

    return temp;
}
</code>```

SHOULD I DO

```<code>void myMethod()
{
    User user = getUser(1234);
    System.out.println(user.getName());
}
</code>```

OR

```<code>void myMethod()
{
    User user = getUser(1234);

    // Validating
    Preconditions.checkNotNull(user, "User can not be null.");
    Preconditions.checkNotNull(user.getName(), "User's name can not be null.");

    System.out.println(user.getName());
}
</code>```

I'm asking this at the conceptual level. If I know the inner workings of the method I'm calling. Either because I wrote it or I inspected it. And the logic of the possible values it returns meet my preconditions. Is it "better" or "more appropriate" to skip the validation, or should I still defend against wrong values before proceeding with the method I'm currently implementing even if it should always pass.

My conclusion from all answers (feel free to come to your own):

Assert when

The method has shown to misbehave in the past

The method is from an untrusted source

The method is used from other places, and does not explicitly state it's post-conditions

Do not assert when:

The method lives closely to yours (see chosen answer for details)

The method explicitly defines it's contract with something like proper doc, type safety, a unit test, or a post-condition check

Performance is critical (in which case, a debug mode assert could work as a hybrid approach)

答:
That depends on how likely getUser and myMethod are to change, and more importantly, how likely they are to change independently of each other.

If you somehow know for certain that getUser will never, ever, ever change in the future, then yes it's a waste of time validating it, as much as it is to waste time validating that i has a value of 3 immediately after an i = 3; statement. In reality, you don't know that. But there are some things you do know:

Do these two functions "live together"? In other words, do they have the same people maintaining them, are they part of the same file, and thus are they likely to stay "in sync" with each other on their own? In this case it's probably overkill to add validation checks, since that merely means more code that has to change (and potentially spawn bugs) every time the two functions change or get refactored into a different number of functions.

Is the getUser function is part of a documented API with a specific contract, and myMethod merely a client of said API in another codebase? If so, you can read that documentation to find out whether you should be validating return values (or pre-validating input parameters!) or if it really is safe to blindly follow the happy path. If the documentation does not make this clear, ask the maintainer to fix that.

Finally, if this particular function has suddenly and unexpectedly changed its behavior in the past, in a way that broke your code, you have every right to be paranoid about it. Bugs tend to cluster.

Note that all of the above applies even if you are the original author of both functions. We don't know if these two functions are expected to "live together" for the rest of their lives, or if they'll slowly drift apart into separate modules, or if you have somehow shot yourself in the foot with a bug in older versions of getUser. But you can probably make a pretty decent guess.


问:
License opensource app for non-commercial
I wish to create an app for studying Japanese Kanji. However I'm uncertain which license would best fit it. I want my app to be Opensource so that I can use the code for tutorials and other people may benefit from the example. I want to release the app for free so that I can improve the Japanese learning community, however I don't want that a person/company rips all my source code, polishes it a bit and sells it for money. When I look at the available popular Opensource licenses they all allow "Commercial Use" (http://choosealicense.com/licenses/). I don't mind people using my source code for practice or their own apps, as long as they also published it for free and Opensource. So what would be appropriate licenses?

The Attribution-NonCommercial-ShareAlike CC BY-NC-SA seems like what I want, but it's mentioned in their FAQ that they don't recommend this license for software (https://wiki.creativecommons.org/Frequently_Asked_Questions#Can_I_apply_a_Creative_Commons_license_to_software.3F).

答:
I would recommend you to use a copyleft license like the GPL. While the GPL does not forbid to sell the software, it requires to license it under GPL when sold, so when someone polishes your application and sells it, they can sell it exactly once, because their customer can then also sell it or give it away for free. When each of their customers can underbid them on the market, their business model simply isn't sustainable. So the business model you are afraid of simply doesn't work for GPL software.

You don't find many widely used software licenses which forbid "commercial use", because "commercial use" is something which is very hard to define in a way that it isn't overly restrictive.

Some examples:

A website offers the software (or a modified form of it) for download. The website has banner ads to cover their cost. Is that commercial use?

A website without advertising offers an improved version for download, but the software is modified to show banner ads. Is that commercial use?

I create a fork of your software and offer it for free under the same license conditions. But I ask people to send me voluntary donations when they want to support my work on the software. Is that commercial use?

A private school wants to use a modified version in their lessons. The program is given to the students for free, but the version is heavily optimized for the schools curriculum and teaching practices. Is that commercial use?

I use your program to learn Japanese and/or programming. Then I use the skills I learned to make lots of money. Is that commercial use?

Maybe you say "yes" to some and "no" to others of these examples. But I think it should give you an idea how hard it can be to define "commercial use".

<advertising>When you have more questions about open source licenses, you might want to commit to the new proposal Open Source Stackexchange. It still needs people to commit to it so it can go into beta phase.</advertising>


答:
Generally, I'd say that depends mainly on the following three aspects:

robustness: can the calling method cope with the null value? If a null value might result in a RuntimeException I'd recommend a check - unless complexity is low and called/calling methods are created by the same author, and null is not expected (e.g. both private in the same package).

code responsibility: if developer A is responsible for the getUser() method, and developer B uses it (e.g. as part of a library), I'd strongly recommend to validate its value. Just because developer B might not know about a change that results in a potential null return value.

complexity: the higher the overall complexity of the program or environment is, the more I'd recommend to validate the return value. Even if you feel sure about that it cannot be null today in the context of the calling method, it might be that you have have to change getUser() for another use case. Once some months or years are gone, and some thousand lines of codes have been added, this can be quite a trap.

In addition, I'd recommend to document potential null return values in a JavaDoc comment. Due to highlighting of JavaDoc descriptions in the most IDEs, this can be a helpful warning for whoever uses getUser().

```<code>/** Returns ....
  * @param: id id of the user
  * @return: a User instance related to the id;
  *          null, if no user with identifier id exists
 **/
User getUser(Int id)
{
    ...
}
</code>```

Title: Should I validate a method call's return value even if I know that the method can't return bad input?

Body:
I'm wondering if I should defend against a method call's return value by validating that they meet my expectations even if I know that the method I'm calling will meet such expectations.

GIVEN

```<code>User getUser(Int id)
{
    User temp = new User(id);
    temp.setName("John");

    return temp;
}
</code>```

SHOULD I DO

```<code>void myMethod()
{
    User user = getUser(1234);
    System.out.println(user.getName());
}
</code>```

OR

```<code>void myMethod()
{
    User user = getUser(1234);

    // Validating
    Preconditions.checkNotNull(user, "User can not be null.");
    Preconditions.checkNotNull(user.getName(), "User's name can not be null.");

    System.out.println(user.getName());
}
</code>```

I'm asking this at the conceptual level. If I know the inner workings of the method I'm calling. Either because I wrote it or I inspected it. And the logic of the possible values it returns meet my preconditions. Is it "better" or "more appropriate" to skip the validation, or should I still defend against wrong values before proceeding with the method I'm currently implementing even if it should always pass.

My conclusion from all answers (feel free to come to your own):

Assert when

The method has shown to misbehave in the past

The method is from an untrusted source

The method is used from other places, and does not explicitly state it's post-conditions

Do not assert when:

The method lives closely to yours (see chosen answer for details)

The method explicitly defines it's contract with something like proper doc, type safety, a unit test, or a post-condition check

Performance is critical (in which case, a debug mode assert could work as a hybrid approach)

Body:
Generally, I'd say that depends mainly on the following three aspects:

robustness: can the calling method cope with the null value? If a null value might result in a RuntimeException I'd recommend a check - unless complexity is low and called/calling methods are created by the same author, and null is not expected (e.g. both private in the same package).

code responsibility: if developer A is responsible for the getUser() method, and developer B uses it (e.g. as part of a library), I'd strongly recommend to validate its value. Just because developer B might not know about a change that results in a potential null return value.

complexity: the higher the overall complexity of the program or environment is, the more I'd recommend to validate the return value. Even if you feel sure about that it cannot be null today in the context of the calling method, it might be that you have have to change getUser() for another use case. Once some months or years are gone, and some thousand lines of codes have been added, this can be quite a trap.

In addition, I'd recommend to document potential null return values in a JavaDoc comment. Due to highlighting of JavaDoc descriptions in the most IDEs, this can be a helpful warning for whoever uses getUser().

/** Returns ....
  * @param: id id of the user
  * @return: a User instance related to the id;
  *          null, if no user with identifier id exists
 **/
User getUser(Int id)
{
    ...
}


问:
Why are the types in Java considered less 'strong' than haskell?
I asked this question a while ago - the answers were really helpful, and as I read them and the questions that were linked - I also saw this, and the first answer I think really addresses what I thought was the essence of the more powerful type system.

I was trying to really understand the pseudo-implementation of the functor that the author gives in his example - and I wondered if anyone can give me a slightly simpler explanation of this part of his answer.

Directly quoted from the answer - it's these bits that I don't quite get.

for this block of code.

interface Functor {
    Functor map(Function f);
}
```

The type system doesn't allow us to express the invariant that the
  map method always returns the same Functor subclass as the receiver.

Therefore, there's no statically type-safe manner to invoke a
      non-Functor method on the result of map.

Is a simple way of looking at this that in a concrete implementation of Functor, you can declare what you want to use as A,  but not what you want to use as B, or even the B is the same on both sides of the map function?

More generall, my slightly simplistic interpretation of this is that single-kinded types really mean that it limits how far you can "reach" or "specify" the contract you are trying to specify with your types. With higher kinded types, you get much more flexibility on how you specify your types, i.e you can constrain and bind your functions more specifically that you can with simple java generics.

... or I really it could be that I just don't understand what a Type Constructor is or why it's useful!

答:
About the point 1., let's discuss it with an example:

```<code>class Maybe<A> implements Functor<A> {
  public <B> Functor<B> map(Function<A, B> f) {
    // implementation....
  }
}

class List<A> implements Functor<A> {
  public <B> Functor<B> map(Function<A, B> f) {
    return new Maybe<B>(); // error, but I can do this
  }
}
</code>```

See the problem? The map implementation of List is returning Maybe just because Maybe implements Functor. This is about the power of the type system: I want to say that map not only returns a Functor but it returns a very specific Functor.

About the point 2.,  type safety, I think the problem described by the post is the following: let's imagine that you want to call the get(0) method on the list and you want to call it after you call map

```<code>list.map(...).get(0) // error because Functor doesn't have add
</code>```

You have to actually downcast the return of map to List.

```<code>((List<B>)list.map(...)).get(0)
</code>```

In a language like Haskell, the fmap function takes a Functor F and returns another instance of that Functor F, so one can do:

```<code> head (fmap (...) list)
</code>```

Body:
About the point 1., let's discuss it with an example:

class Maybe<A> implements Functor<A> {
  public <B> Functor<B> map(Function<A, B> f) {
    // implementation....
  }
}

class List<A> implements Functor<A> {
  public <B> Functor<B> map(Function<A, B> f) {
    return new Maybe<B>(); // error, but I can do this
  }
}

See the problem? The map implementation of List is returning Maybe just because Maybe implements Functor. This is about the power of the type system: I want to say that map not only returns a Functor but it returns a very specific Functor.

About the point 2.,  type safety, I think the problem described by the post is the following: let's imagine that you want to call the get(0) method on the list and you want to call it after you call map

list.map(...).get(0) // error because Functor doesn't have add

You have to actually downcast the return of map to List.

((List<B>)list.map(...)).get(0)

In a language like Haskell, the fmap function takes a Functor F and returns another instance of that Functor F, so one can do:

 head (fmap (...) list)