答:
There are two questions I ask when it comes to magic numbers.

Does the number have a name?

Names are useful because we can read the name and understand the purpose of the number behind it. Naming constants may increase readability if the name is easier to understand than the number it replaces and the constant name is concise.

Clearly, constants such as pi, e, et al. have meaningful names. A value such as 1024 could be BYTES_PER_KB but I would also expect that any developer would know what 1024 means. The intended audience for source code is professional programmers who should have the background to know various powers of two and why they are used.

Is it used in multiple locations?

While names are one strength of constants, another is reusability. If a value is likely to change, it can be changed in one place instead of needing to hunt it down in multiple locations.

Your Question

In the case of your question, I would use the number as-is.

Name: there is a name for that number, but it is nothing really useful. It does not represent a mathematical constant or value specified in any requirements document.

Locations: even if used in multiple locations, it will never change, negating this benefit.

Title: Are all magic numbers created the same?

Body:
On a recent project, I needed to convert from bytes to <s>kilobytes</s> kibibyte. The code was straightforward enough:

var kBval = byteVal / 1024;
```

After writing that, I got the rest of the function working & moved on.

But later on, I started to wonder if I had just embedded a magic number within my code. Part of me says it was fine because the number is a fixed constant and should be readily understood. But another part of me thinks it would have been super clear if wrapped in a defined constant like BYTES_PER_KBYTE.

So are numbers that are well known constants really all that magical or not?

Related questions:

When is a number a magic number? and Is every number in the code considered a "magic number"? - are similar, but are much broader questions than what I'm asking.  My question is focused on well-known constant numbers which is not addressed in those questions.

Eliminating Magic Numbers: When is it time to say "No"? is also related, but is focused on refactoring as opposed to whether or not a constant number is a magic number.


问:
Are all magic numbers created the same?
On a recent project, I needed to convert from bytes to <s>kilobytes</s> kibibyte. The code was straightforward enough:

var kBval = byteVal / 1024;
```

After writing that, I got the rest of the function working & moved on.

But later on, I started to wonder if I had just embedded a magic number within my code. Part of me says it was fine because the number is a fixed constant and should be readily understood. But another part of me thinks it would have been super clear if wrapped in a defined constant like BYTES_PER_KBYTE.

So are numbers that are well known constants really all that magical or not?

Related questions:

When is a number a magic number? and Is every number in the code considered a "magic number"? - are similar, but are much broader questions than what I'm asking.  My question is focused on well-known constant numbers which is not addressed in those questions.

Eliminating Magic Numbers: When is it time to say "No"? is also related, but is focused on refactoring as opposed to whether or not a constant number is a magic number.

答:
This quote

It's not the number that's the problem, it's the magic.

as said by Jörg W Mittag answers this question quite well.

Some numbers simply aren't magical within a particular context.  In the example provided in the question, the units of measure were specified by the variable names and the operation that was taking place was quite clear.

So 1024 isn't magical because the context makes it very clear that it's the appropriate, constant value to use for conversions.

Likewise, an example of:

var numDays = numHours / 24;
```

is equally clear and not magical because it's well known that there are 24 hours in the day.

ContentLicense: CC BY-SA 3.0

Title: Are all magic numbers created the same?

Body:
This quote

It's not the number that's the problem, it's the magic.

as said by Jörg W Mittag answers this question quite well.

Some numbers simply aren't magical within a particular context.  In the example provided in the question, the units of measure were specified by the variable names and the operation that was taking place was quite clear.

So 1024 isn't magical because the context makes it very clear that it's the appropriate, constant value to use for conversions.

Likewise, an example of:

var numDays = numHours / 24;

is equally clear and not magical because it's well known that there are 24 hours in the day.


答:
Defining a name as referring to a numeric value suggests that whenever a different value is needed in one place that uses that name, it will likely be needed in all.  It also tends to suggest that changing the numeric value assigned to the name is a legitimate way of changing the value.  Such an implication can be useful when it's true, and dangerous when it's false.

The fact that two different places use a particular literal value (e.g. 1024) will weakly suggest that changes which would prompt a programmer to change one are somewhat likely to inspire the programmer to want to change others, but that implication is much weaker than would apply if the programmer assigned a name to such a constant.

A major danger with something like #define BYTES_PER_KBYTE 1024 is that it might suggest to someone who encounters printf("File size is %1.1fkB",size*(1.0/BYTES_PER_KBYTE)); that a safe way to make the code use thousands of bytes would be to change the #define statement. Such a change could be disastrous, however, if e.g. some other unrelated code receives the size of an object in Kbytes and uses that constant when allocating a buffer for it.

It might be reasonable to use #define BYTES_PER_KBYTE_FOR_USAGE_REPORT 1024 and #define BYTES_PER_KBYTE_REPORTED_BY_FNOBULATOR 1024, assigning a different name for every different purpose served by the constant 1024, but that would result in many identifiers getting defined and used exactly once.  Further, in many cases, it's easiest to understand what a value means if one sees the code where it's used, and it's easiest to figure out where code means if one sees the values of any constants used therein.  If a numeric literal is only used once for a particular purpose, writing the literal at the place where it's used will often yield more understandable code than assigning a label to it in one place and using its value somewhere else.

Title: Are all magic numbers created the same?


问:
Is there any algorithm pattern to protect any content in the web to ensure I am the first one who created it?
A few years ago there was this hacker (don't remember who he was) that full disclosed a vulnerability in a given system, but to make sure nobody took credit for that, he created some kind of PGP key.

What I understood at the time is that he created a key to ensure he was the one who discovered it, but didn't disclosed who he was actually, just created some mechanism to be able to prove that he was the one who created the disclosure.

Ok. I get how algorithms and cryptography works. But I still don't understand how you can create a key to protect a given content disclosed in the web to prove you are the one who created it first! It is just words!

Is it really possible? What should be the process to ensure you can empirically prove it? Did I understood it correctly or I probably missed something regarding this case?

I hope this question is specific enough, basically it is just how to protect a content that you created in the web (a paragraph, a code, a word, etc.) and make sure you are the one who created it first, inside a given context.

With my knowledge I don't see how that is possible, but I am intrigued if there is a practical way to do it. Is there?

答:
Ugh, so many of these answers are missing the point.

1) What the hacker did had nothing to do with encryption.

2) What the hacker did had nothing to do with time (the time stamp, etc).

What the hacker did was Publicly Sign the release document. When you PGP sign something (an e-mail, a word document, etc), you create a hash which is the sum of the hash of the document being signed, and your own private key. Now, to prove that you are the creator of the document, you just need to "show" the private key, as presumably only the author knows it. Cryptographically speaking, you can "show" that you are in possession of the private key without actually showing the key itself.

So, in effect, he digitally signed the document. The only person who can copy that signature, is someone with his private key.
There is nothing to say that the document was made today, or yesterday, or was the first instance of it to exist ever. No amount of hashing timestamps or whatever will change that.

The only way to digitally sign something IN TIME, is to use the blockchain a la bitcoin. There could be no digital currency without time verification - the fact that person A sent money to person B is irrelevant unless we know when.
You cannot go into a shop with a piece of paper and say "my mum sent me $100 once. I would like to buy some bread", because a receipt of a transaction doesn't mean the money still belongs to you. You might have given it to someone else in the interim.
The blockchain solves this issue by getting a large number of people (bitcoin miners) to all agree on the fact that the transaction happened at a certain time (and then by recording that time in the blockchain forever).


问:
Is it OK to partially change a collection with PUT or DELETE?
I have a collection of products in a product group e.g.:

```<code>product-groups/123/products
</code>```

If I need to add to the collection, is it OK that I pass only some products with PUT?

If I need to delete some products from the collection, is it OK that I pass filter data (an array of ID's) with DELETE?

What's the best way to implement the functionality in the spirit of ReST?

Edit: the items are links to separate entities, basically ID's of products.

答:
In general you have one endpoint which represents the whole collection of x:

```<code>/products
</code>```

Say, you want to update a single product, you make a PUT to /products/{id}.
If you want to partially update a single product (not updating every field), you could also use a PATCH to /products/{id}. The same goes for deletion of a single entity (DELETE to /products/{id}).

If you want to target a single ressource, you qualify via path, which single ressource, you want to modify.

The only action which breaks the scheme is the creation of a ressource. When creating a ressource you target the collection as a whole, say POST to /products.

That said, it should be clear, that the target for operations affecting the collection as a whole, should go to the appropriate collection-endpoint.

E.g. you want to retrieve a subset of products which are red, you ask for it by

GET to /products?colour=red.

So, if you want to delete all of these, you DELETE /products?colour=red. Or if you want to delete some of the products via id, you could DELETE /products?id=1&id=2&id=3.

What about bulk creation of ressources? POST your collection [{...},{...},{...}] simply to /products. The same goes for PUT and PATCH.

That's really straightforward.

To answer your questions:

If I need to add to the collection, is it OK that I pass only some products with PUT?

It is not only OK, you are encouraged to do it like that.

If I need to delete some products from the collection, is it OK that I pass filter data (an array of ID's) with DELETE?

That is okay. As Eneko Alonso wrote, sometimes there are bulkoperations encapsulated via "controller"-endpoints, i.e. a POST is used to trigger (complex) operations.

Body:
In general you have one endpoint which represents the whole collection of x:

/products

Say, you want to update a single product, you make a PUT to /products/{id}.
If you want to partially update a single product (not updating every field), you could also use a PATCH to /products/{id}. The same goes for deletion of a single entity (DELETE to /products/{id}).

If you want to target a single ressource, you qualify via path, which single ressource, you want to modify.

The only action which breaks the scheme is the creation of a ressource. When creating a ressource you target the collection as a whole, say POST to /products.

That said, it should be clear, that the target for operations affecting the collection as a whole, should go to the appropriate collection-endpoint.

E.g. you want to retrieve a subset of products which are red, you ask for it by

GET to /products?colour=red.

So, if you want to delete all of these, you DELETE /products?colour=red. Or if you want to delete some of the products via id, you could DELETE /products?id=1&id=2&id=3.

What about bulk creation of ressources? POST your collection [{...},{...},{...}] simply to /products. The same goes for PUT and PATCH.

That's really straightforward.

To answer your questions:

If I need to add to the collection, is it OK that I pass only some products with PUT?

It is not only OK, you are encouraged to do it like that.

If I need to delete some products from the collection, is it OK that I pass filter data (an array of ID's) with DELETE?

That is okay. As Eneko Alonso wrote, sometimes there are bulkoperations encapsulated via "controller"-endpoints, i.e. a POST is used to trigger (complex) operations.


问:
AJAX - What exactly does that encompass?
So I see on a lot of people's resumes they list AJAX in their technologies (or programming languages - and I recognize that it is not a language). To me, AJAX seems like such a small concept to be individually listed. It seems it is almost as useful as listing MVC experience (because MVC too is a concept), which is good to know, but AJAX, like MVC, is just a facet of one's abilities as a developer. However, saying "I know AJAX" seems like it is much smaller thing than saying "I know MVC".

What does saying "I know AJAX" actually cover?

To me, it seems like you are saying, I know how to use JavaScript to send of an asynchronous call (via some data format like XML or JSON) to a web endpoint, and use the endpoint's response to manipulate a web page's DOM for visual effects and data.

The wikipedia page on AJAX lists just  a few more things, but I'd love to ask the community... am I missing a key concept about AJAX? If not, it seems like that listing it on a resume is just fluff.

答:
You are thinking like a programmer. Instead, try to think like a Human Resources Director.

Senior Developer to Human Resources Director: We need to hire a web developer.

HRD: Okay, what skills do they need to have?

SRD: Well, PHP, Javascript, MVC frameworks, git...

HRD: Anything else?

SRD: Well, experience with AJAX would be a plus...

Adding technologies like AJAX into resumes works as grease to facilitate Human Resources filtering out potential job applications and to write accurate job listings.

Otherwise, you are correct. If I were hiring a web developer, I would assume that PHP + Javascript on a resume would imply having written code with asynchronous calls. But I would still ask during an interview if it wasn't explicitly stated.


问:
How to define "or" logically
Recently, I came across a problem that required me to define the logical "OR" operator programmatically, but without using the operator itself.

What I came up with is this:

OR(arg1, arg2)
  if arg1 = True and arg2 = True
     return True

  else if arg1 = True and arg2 = False
     return True

  else if arg1 = False and arg2 = True
     return True

  else:
     return False
```

Is this logic correct, or did I miss something?

答:
One way to define or is via a lookup table.  We can make this explicit:

```<code>bool Or( bool a, bool b } {
  bool retval[] = {b,true}; // or {b,a};
  return retval[a];
}
</code>```

we create an array with the values that the return value should have depending on what a is.  Then we do a lookup.  In C++ like languages, bool promotes to a value that can be used as an array index, with true being 1 and false being 0.

We can then extend this to other logical operations:

```<code>bool And( bool a, bool b } {
  bool retval[] = {false,b}; // or {a,b};
  return retval[a];
}
bool Xor( bool a, bool b } {
  bool retval[] = {b,!b};
  return retval[a];
}
</code>```

Now a downside of all of these is that it requires prefix notation.

```<code>namespace operators {
  namespace details {
    template<class T> struct is_operator {};
    template<class Lhs, Op> struct half_expression { Lhs&& lhs; };
    template<class Lhs, class Op>
    half_expression< Lhs, Op > operator*( Lhs&&lhs, is_operator<Op> ) {
      return {std::forward<Lhs>(lhs)};
    }
    template<class Lhs, class Op, class Rhs>
    auto operator*( half_expression<Lhs, Op>&& lhs, Rhs&& rhs ) {
    return invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) );
    }
  }
  using details::is_operator;
}

struct or_tag {};
static const operators::is_operator<or_tag> OR;

bool invoke( bool a, or_tag, bool b ) {
  bool retval[] = {b,true};
  return retval[a];
}
</code>```

and now you can type true *OR* false and it works.

The above technique requires a language that supports argument dependent lookup, and templates.  You could probably do it in a language with generics and ADL.

As an aside, you can extend the *OR* above to work with sets.  Simply create a free function invoke in the same namespace as or_tag:

```<code>template<class...Ts>
std::set<Ts...> invoke( std::set<Ts...> lhs, or_tag, std::set<Ts...> const& rhs ) {
  lhs.insert( rhs.begin(), rhs.end() );
  return lhs;
}
</code>```

and now set *OR* set returns the union of the two.

Title: How to define "or" logically

Body:
One way to define or is via a lookup table.  We can make this explicit:

bool Or( bool a, bool b } {
  bool retval[] = {b,true}; // or {b,a};
  return retval[a];
}

we create an array with the values that the return value should have depending on what a is.  Then we do a lookup.  In C++ like languages, bool promotes to a value that can be used as an array index, with true being 1 and false being 0.

We can then extend this to other logical operations:

bool And( bool a, bool b } {
  bool retval[] = {false,b}; // or {a,b};
  return retval[a];
}
bool Xor( bool a, bool b } {
  bool retval[] = {b,!b};
  return retval[a];
}

Now a downside of all of these is that it requires prefix notation.

namespace operators {
  namespace details {
    template<class T> struct is_operator {};
    template<class Lhs, Op> struct half_expression { Lhs&& lhs; };
    template<class Lhs, class Op>
    half_expression< Lhs, Op > operator*( Lhs&&lhs, is_operator<Op> ) {
      return {std::forward<Lhs>(lhs)};
    }
    template<class Lhs, class Op, class Rhs>
    auto operator*( half_expression<Lhs, Op>&& lhs, Rhs&& rhs ) {
    return invoke( std::forward<Lhs>(lhs.lhs), Op{}, std::forward<Rhs>(rhs) );
    }
  }
  using details::is_operator;
}

struct or_tag {};
static const operators::is_operator<or_tag> OR;

bool invoke( bool a, or_tag, bool b ) {
  bool retval[] = {b,true};
  return retval[a];
}

and now you can type true *OR* false and it works.

The above technique requires a language that supports argument dependent lookup, and templates.  You could probably do it in a language with generics and ADL.

As an aside, you can extend the *OR* above to work with sets.  Simply create a free function invoke in the same namespace as or_tag:

template<class...Ts>
std::set<Ts...> invoke( std::set<Ts...> lhs, or_tag, std::set<Ts...> const& rhs ) {
  lhs.insert( rhs.begin(), rhs.end() );
  return lhs;
}

and now set *OR* set returns the union of the two.


问:
REST-ful design: recommended approach for fetching related entities
Suppose I have two entities author and post, were every post has an author.
Implemented are these REST calls

Get a paginated list of posts: GET /posts?page={page}

Get a list of authors: GET /authors

Get a single author: GET /authors/{id}

Suppose I also have a client using the REST service. This client wants to show a paginated list of posts with related authors.

Now how would the REST service work regarding the related entities? There are the following methods:

Let the GET /posts?page=1 call return the posts and the related authors in a single call. Optionally make this a separate parameter, f.e. GET /posts?page=1&related=true or GET /posts/related?page=1.

Let the client loop through the posts and get the author for every post using the GET /author/{id} call.

Let the REST call for the authors accept a list of ID's as a filter, so the client can get the related authors in one call, f.e. GET /authors?ids=10,12,16,30,43,44,58.

Method 1 is the easiest one from the client's perspective since it gets all the necessary data in one call. But the REST service is limited here, it shouldn't need to fit any particular client because every client has other requirements.

Method 2 is the cleanest REST approach, but let's say that a page has 30 posts, the client has to make 30 additional REST calls to retrieve the related authors. This is very inefficient.

Method 3 is perhaps better of the three, since it is a relatively clean REST implementation (compared to method 1) and it requires only one extra call per page.

Is there a recommended approach here?

答:
That's, what links are for:

E.g. requesting the first post via GET http://example.com/posts/1

```<code>{
    "id": "1",
    "author": {
        "nickname": "me"
    },
    "links": [
        {
            "rel": "self",
            "href": "http://example.com/posts/1"
        },
        {
            "rel": "author",
            "href": "http://example.com/authors/me"
        }
    ]
}
</code>```

The response contains a link to the author (named me). If you want to retrieve all of me's posts, you would do a GET to http://example.com/posts?author=me; and if you want it paginated, you would add a queryparameter like http://example.com/posts?author=me&page=1.

Say, you have collaborations between various authors, the initial answer would've been:

```<code>{
    "id": "1",
    "authors": [
        {
            "nickname": "me"
        },
        {
            "nickname": "mo"
        },
        {
            "nickname": "ma"
        }
    ],
    "links": [
        {
            "rel": "self",
            "href": "http://example.com/posts/1"
        },
        {
            "rel": "author",
            "href": "http://example.com/authors/me"
        },
        {
            "rel": "author",
            "href": "http://example.com/authors/mo"
        },
        {
            "rel": "author",
            "href": "http://example.com/authors/ma"
        }
    ]
}
</code>```

On the other hand, under the links-section of the author, there should only be a reference to the latest post (to prevent too much data in there).

If you want to get a set of all collaborative posts from the trio above, you would query as follows:

GET http://example.com/posts?author=mo,me,ma

If you want all posts - including the collaborative - from the trio, you would query like this:

GET http://example.com/posts?author=mo|me|ma

This is a clean and straightforward approach.

To express, that something is related, you use links. If you want to filter you do it via querystring.

ContentLicense: CC BY-SA 4.0

Body:
That's, what links are for:

E.g. requesting the first post via GET http://example.com/posts/1

{
    "id": "1",
    "author": {
        "nickname": "me"
    },
    "links": [
        {
            "rel": "self",
            "href": "http://example.com/posts/1"
        },
        {
            "rel": "author",
            "href": "http://example.com/authors/me"
        }
    ]
}

The response contains a link to the author (named me). If you want to retrieve all of me's posts, you would do a GET to http://example.com/posts?author=me; and if you want it paginated, you would add a queryparameter like http://example.com/posts?author=me&page=1.

Say, you have collaborations between various authors, the initial answer would've been:

{
    "id": "1",
    "authors": [
        {
            "nickname": "me"
        },
        {
            "nickname": "mo"
        },
        {
            "nickname": "ma"
        }
    ],
    "links": [
        {
            "rel": "self",
            "href": "http://example.com/posts/1"
        },
        {
            "rel": "author",
            "href": "http://example.com/authors/me"
        },
        {
            "rel": "author",
            "href": "http://example.com/authors/mo"
        },
        {
            "rel": "author",
            "href": "http://example.com/authors/ma"
        }
    ]
}

On the other hand, under the links-section of the author, there should only be a reference to the latest post (to prevent too much data in there).

If you want to get a set of all collaborative posts from the trio above, you would query as follows:

GET http://example.com/posts?author=mo,me,ma

If you want all posts - including the collaborative - from the trio, you would query like this:

GET http://example.com/posts?author=mo|me|ma

This is a clean and straightforward approach.

To express, that something is related, you use links. If you want to filter you do it via querystring.


问:
Algorithm to test file equivalence
I'm writing a program that needs to test if a file is equivalent to one or more other files. To accomplish this, every time we see a new file we stat the file and get the size.

We use the size as a key and if we've never seen the size before than we know that's a new file.

If we have seen that size before we were planning to md5 the first 4k and last 4k of the target file and check to see if that hash has been seen in list associated with the size key.

I don't want to hash the whole file since these files can be rather large (largest I've seen so far is 90G).

The goal is to avoid spending a lot of time on redundant file comparisons. Will this algorithm work, and can it be improved?

More details on my particular problem: I'm attempting to deduplicate a decently sized set of data ( 2Pb ) that contains a large amount of time stamped files (about 40%) created from syslog on FreeBSD machines. Before I start chewing through that many files line by line I wanted to make sure that the file I was looking at hadn't been seen before.

答: Without some knowledge of the nature of the files you cannot be sure without hashing the entire file. Checking the file size and hashing only a portion of the file contents is sufficient only if you can guarantee that the contents will be unique in the hashed portions.</p>

Title: Algorithm to test file equivalence


答:
It sounds like you are trying to optimize the file comparison because that can be a potentially expensive operation:

If two files have different sizes, they must be different files.

If the first and last 4K of two files hash to different values, they must be different files. The first portion will check stuff like a file identifier commonly included in the first few bytes, while the last would help catch cases where a file is being appended to (e.g. a log file), similar to what tail checks.

Next you would have to compare the entire file just to be sure. At this point it might makes sense to store multiple hash values (MD5 if security is not a concern, SHA2, etc). You should be able to find a way to read in the file once and feed it to multiple hash algorithms. Then you store a data structure with all of the hashes, which you can very quickly compare with other data structures for other files.

If all of those tests pass (files likely but not necessarily equal) then you might need to perform a full file comparison.

I think your algorithm sounds reasonable, and I think my minor additions will help.

Based on the clarifications in the question, I think your approach will work. The odds that log files are the same size and the first and last portions hash the same is extremely low. If you use a strong hash algorithm with a large output size (compared to MD5), the chance is even lower: with SHA-512, the internal state and output range are ginormous. Given we are talking about log files that are very likely to have date/time stamps at the start of each line, the input should have enough entropy to make this a non-issue.

Title: Algorithm to test file equivalence

Body:
I'm writing a program that needs to test if a file is equivalent to one or more other files. To accomplish this, every time we see a new file we stat the file and get the size.

We use the size as a key and if we've never seen the size before than we know that's a new file.

If we have seen that size before we were planning to md5 the first 4k and last 4k of the target file and check to see if that hash has been seen in list associated with the size key.

I don't want to hash the whole file since these files can be rather large (largest I've seen so far is 90G).

The goal is to avoid spending a lot of time on redundant file comparisons. Will this algorithm work, and can it be improved?

More details on my particular problem: I'm attempting to deduplicate a decently sized set of data ( 2Pb ) that contains a large amount of time stamped files (about 40%) created from syslog on FreeBSD machines. Before I start chewing through that many files line by line I wanted to make sure that the file I was looking at hadn't been seen before.


答:
Your approach is good... if the files have completely random data. Here are some things to consider:

How bad is it if there are collisions? If you need a mission critical guarantee (e.g. those astronauts on the ISS will die if a collision occurs), your algorithm may not be good enough, even though there are 10^38 possible MD5 hashes. People do win the lottery occasionally, after all, though for random data this is probably safe.

This is the more important one: if the files are all generated in the same way, have similar formatting, records, have header/footer information, etc. then it's actually possible that these files begin and end exactly the same way - and would thus have the same hash - even though they are not the same.

So, you're barking up the right tree, but definitely pay attention to the actual details of your use case to ensure you're not overlooking something obvious.

Title: Algorithm to test file equivalence


问:
Is it good practice to inherit from generic types?
Is it better to use List<string> in type annotations or StringList where StringList

```<code>class StringList : List<String> { /* no further code!*/ }
</code>```

I ran into several of these in Irony.

答:
There are three possible reasons why someone would try to do that off the top of my head:

1)  To simplify declarations:

Sure StringList and ListString are about the same length but imagine instead you're working with a UserCollection that's actually Dictionary<Tuple<string,Type>, IUserData<Dictionary,MySerializer>> or some other large generic example.

2)  To help AOT:

Sometimes you need to use Ahead Of Time compilation not Just In Time Compilation - e.g. developing for iOS.  Sometimes the AOT compiler has difficulty figuring out all the generic types ahead of time, and this could be an attempt to provide it with a hint.

3)  To add functionality or remove dependency:

Maybe they have specific functionality that they want to implement for StringList (could be hidden in an  extension method, not added yet, or historical)  that they either can't add to List<string> without inheriting from it, or that they don't want to pollute List<string> with.

Alternatively they may wish to change the implementation of StringList down the track, so have just used the class as a marker for now (usually you'd make/use interfaces for this e.g. IList).

I'd also note that you've found this code in Irony, which is a language parser - a fairly unusual kind of application.  There may be some other specific reason that this was used.

These examples demonstrate that there can be legitimate reasons to write such a declaration - even if it's not too common.  As with anything consider several options and pick which is best for you at the time.

If you have a look at the source code it appears option 3 is the reason - they use this technique to help add functionality/specialize collections:

```<code>public class StringList : List<string> {
    public StringList() { }
    public StringList(params string[] args) {
      AddRange(args);
    }
    public override string ToString() {
      return ToString(" ");
    }
    public string ToString(string separator) {
      return Strings.JoinStrings(separator, this);
    }
    //Used in sorting suffixes and prefixes; longer strings must come first in sort order
    public static int LongerFirst(string x, string y) {
      try {//in case any of them is null
        if (x.Length > y.Length) return -1;
      } catch { }
      if (x == y) return 0;
      return 1;
    }
</code>```

Body:
There are three possible reasons why someone would try to do that off the top of my head:

1)  To simplify declarations:

Sure StringList and ListString are about the same length but imagine instead you're working with a UserCollection that's actually Dictionary<Tuple<string,Type>, IUserData<Dictionary,MySerializer>> or some other large generic example.

2)  To help AOT:

Sometimes you need to use Ahead Of Time compilation not Just In Time Compilation - e.g. developing for iOS.  Sometimes the AOT compiler has difficulty figuring out all the generic types ahead of time, and this could be an attempt to provide it with a hint.

3)  To add functionality or remove dependency:

Maybe they have specific functionality that they want to implement for StringList (could be hidden in an  extension method, not added yet, or historical)  that they either can't add to List<string> without inheriting from it, or that they don't want to pollute List<string> with.

Alternatively they may wish to change the implementation of StringList down the track, so have just used the class as a marker for now (usually you'd make/use interfaces for this e.g. IList).

I'd also note that you've found this code in Irony, which is a language parser - a fairly unusual kind of application.  There may be some other specific reason that this was used.

These examples demonstrate that there can be legitimate reasons to write such a declaration - even if it's not too common.  As with anything consider several options and pick which is best for you at the time.

If you have a look at the source code it appears option 3 is the reason - they use this technique to help add functionality/specialize collections:

public class StringList : List<string> {
    public StringList() { }
    public StringList(params string[] args) {
      AddRange(args);
    }
    public override string ToString() {
      return ToString(" ");
    }
    public string ToString(string separator) {
      return Strings.JoinStrings(separator, this);
    }
    //Used in sorting suffixes and prefixes; longer strings must come first in sort order
    public static int LongerFirst(string x, string y) {
      try {//in case any of them is null
        if (x.Length > y.Length) return -1;
      } catch { }
      if (x == y) return 0;
      return 1;
    }


答:
Data deduplication is also often called "record linkage", so you may want to also use that as a search term when researching this.

There is an article on the Eventbrite engineering blog that explains how you could greatly reduce the number of file comparisons by using Multi Index Locality Sensitive Hashing. In short, you create a special kind of hash value whereby similar documents will have hash values that are close by. You can then compare potentially similar documents byte for byte because the number of documents you have to compare to is a much smaller set.

Title: Algorithm to test file equivalence


问:
Does laziness yield more race conditions?
I recently ran into a race condition while accessing a configuration setting.  After examining what I could of the code, I came to the conclusion that the Configuration class' laziness1 was the source of the race condition.  Pondering that lead me to me wonder if laziness naturally yields a greater chance of race conditions?

Here's how I came to the initial finding:

The Configuration class is implemented as a static class, which means:

The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program.

Which, if I read it correctly, is a long way of saying that the class is lazily loaded.  I did not find anything referencing ordering of events when using additional resources.  i.e. It didn't say when the configuration file (app.config) would be read.

And while the class itself states the following for thread safety, it's not clear when it actually reads the configuration file.

Any public static members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

The bit about Any instance members are not guaranteed to be thread safe is particularly confusing since a static class cannot be instantiated.

What I believe occurred is that my program wrote to a section of the Configuration which was subsequently over-written as the static instance completed it's initialization and reading from the configuration file.

All of that led me to believe that the lazy loading of the static class with its indeterminate reading of the configuration file created the race condition I smacked into.

Which leads me to my broader question of: does laziness within an application naturally yield a greater chance of race conditions?

1 The particular class in question is System.Configuration.Configuration from the .NET framework which is defined as public static class ConfigurationManager.

For the gory details, this is the abstract version of the code:

```<code>//This first line probably isn't required, but I inherited the code and didn't test removing it.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.ConnectionStrings.ConnectionStrings[DBName].ConnectionString = passedParam;
config.Save();
...
ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings[DBName];
</code>```

The answers from here hint at my question, but don't directly address my concern with race conditions.  And this one is somewhat related but more focused on IoC.

答:
Does laziness within an application naturally yield a greater chance of race conditions?

Of course it does. Properly written multithreaded code will not have race conditions, of course; race conditions are caused by not thinking about all the possible outcomes of ordering between multiple threads. This is not to say, however, that lazy loading directly causes race conditions, it just provides one more potential failure point that needs to be considered and accounted for.

In the case of your example, your code didn't do any sort of verifyValidState in the Configuration class, and the laziness led to a race condition.

To put all this another way, one of the axioms of how to write code that avoids race conditions is IMMUTABILITY. Here's one tutorial among many that discusses this subject. By definition, a class that's lazily loaded is not immutable: it has the pre-initialization value, and then it morphs into the loaded value.

Therefore, I would advise you to exercise additional caution when using lazy loading in multithreaded applications.


问:
Standard practice to publish and source-control a single file?
I often want to publish some useful standalone script - e.g., a matlab script which converts flac files into wav files. If it were a big project I would immediately place it in Github, however it seems weird to make a repository for a single file. I could group this script with other scripts of the same subject (e.g., "audio" scripts), however that would make for a repository for miscellanea. I want other developers to use these files and also improve them. Should I simply go with the repository-of-one-file option or is there a more standard practice?</p>

答:
You're having trouble with this question because you're not thinking about the right things. Source control is a tool, it's not a means to an end. What are your plans down the road?

Do you want to have a toolkit of many scripts where people can use any or all of your package for, say, audio processing? Then group them together in the AudioMiscellanea repository.

Do you want to have this project be standalone, where it could potentially be refactored into multiple files and have features and other complexity be added to it? Then give it it's own repository.

In short: Think about your goals, and which paradigm best suits those goals, rather than "what's the best practice".


答:
Git repos are incredibly easy to set up. Move your file into a directory of its own, run git init, and start enjoying version control. There's no downside to doing this, except that you end up with a lot of repos. If you want to share that repo on GitHub or Bitbucket, just do so – after all, public repos are free.

The idea to have one big repo that contains many smaller projects is unfortunately quite common. When working with SVN, that was actually the most sane option – but with Git, this has no place: please keep separate things separate. Especially, using different repos for different projects keeps the history fairly clean, and makes it easy for other people to use the script they want without having to deal with the other cruft that crept into your catch-all repository.

Title: Standard practice to publish and source-control a single file?

Body: I often want to publish some useful standalone script - e.g., a matlab script which converts flac files into wav files. If it were a big project I would immediately place it in Github, however it seems weird to make a repository for a single file. I could group this script with other scripts of the same subject (e.g., "audio" scripts), however that would make for a repository for miscellanea. I want other developers to use these files and also improve them. Should I simply go with the repository-of-one-file option or is there a more standard practice?</p>


答:
I think Github Gists would be a perfect fit for this scenario.

Gist is a simple way to share snippets and pastes with others. All gists are Git repositories, so they are automatically versioned, forkable and usable from Git.

It even has an API to get,post, edit your files/snippets.


答:
I would lean towards using just the number, however I think one important issue hasn't been brought up: The same number can mean different things in different contexts, and this can complicate refactoring.

1024 is also the number of KiB per MiB. Suppose we use 1024 to also represent that calculation somewhere, or in multiple places, and now we need to change to it to calculate GiB instead. Changing the constant is easier than a global find/replace where you may accidentally change the wrong one in some places, or miss it in others.

Or it could even be a bit mask introduced by a lazy programmer that needs to be updated one day.

It's a bit of a contrived example but in some code bases this can cause issues when refactoring or updating for new requirements. For this particular case though, I wouldn't consider the plain number to be really bad form especially if you can enclose the calculation in a method for reuse, I would probably do it myself but consider the constant more 'correct'.

If you do use named constants though, as supercat says it is important to consider whether context matters too, and if you need multiple names.

Title: Are all magic numbers created the same?


问:
How common are use SDLC methodologies in real life?
My instructor told us that some programmers are not using SDLC methodologies for making a system. Because in our project, we used one of the methodologies. If we do not use one of them, maybe our system will not work.

How does what I'm learning now relate to what I can expect in my future life as a programmer?
How common are SDLC methodologies in the industry?

答:
What a big-M Methodology buys you is that you can ensure the following things:

You understand what the customer wants. (Remember, customers don't always know what they want.)

The customer knows exactly what you have promised to deliver and when.

You know what you will be able to deliver and when.

The customer will be able to see progress as it happens.

Neither the stuff that the customer cares about (e.g. features), nor the stuff that you care about (e.g. quality), are neglected.

You can see as early as possible if something will prevent you from delivering what you promised and when, and gives you options as to you can do about it before it's too late.

The system stays in a reasonably high-quality state most of the time, even if not all of the features are there.

These are the things which separate a coder from an engineer. An engineer builds things to order with high-quality, with respect to time and budget constraints. Adhering to a Methodology keeps the customer in the loop, and keeps you honest and on track.

Now here's the dirty secret.

Student projects are the best time to follow one of these Methodologies to the letter, because they are one of the very few real-world situations where they work exactly as advertised. The actual practice of software development has always been messy and always will be messy, because the demands are messy.

I'm going to refer you to the classic paper on this topic by David L. Parnas (who else?) and Paul Clement, A Rational Design Process: How and Why to Fake It. This should be required reading for every software engineering student right after they have tried applying a SDLC methodology to a project. The world has changed a lot since 1986, but the advice has not.

You see, the real world is on a continuum. Some projects are so small, so low-risk, or so skunkwork-like that Methodology-free "cowboy coding" is a realistic option. At the other end, with safety-critical or mission-critical systems, the risk of failure is so high that methodologies are rigidly adhered to or else.

Most software development is somewhere in the middle. So the idea is to develop as you need to, but make it look as if you followed a Methodology. No, that doesn't mean doing all the fakery at the end, you must do it as you go. If you're being agile-like, for example, once per sprint is common.

The process of faking it forces you to do the dotting-of-i's and crossing-of-t's that the Methodology demands. In return, you get the best of both worlds: the flexibility of cowboy coding and the quality of a Methodology.

OwnerDisplayName: Miramiel


答:
You can also do it in one call by embedding authors inside posts. JSON Hypertext Application Language describes how to do this, see https://datatracker.ietf.org/doc/html/draft-kelly-json-hal-06

e.g. (modified copy from the doc):

```<code>{
    "_links": {
        "self": { "href": "/posts" },
        "next": { "href": "/posts?page=2" },
        "find": { "href": "/posts{?id}", "templated": true }
    },
    "_embedded": {
        "post": [{
            "_links": {
                "self": { "href": "/posts/321" },
                "author": { "href": "/author/alan-watts" }
            },
            "_embedded": {
                "author": {
                    "_links": { "self": { "href": "/author/alan-watts" } },
                    "name": "Alan Watts",
                    "born": "January 6, 1915",
                    "died": "November 16, 1973"
                }
            }
            "title": "foo"
        }, {
            "_links": {
                "self": { "href": "/posts/123" },
                "author": { "href": "/author/alan-watts" }
            },
            "_embedded": {
                "author": {
                    "_links": { "self": { "href": "/author/alan-watts" } },
                    "name": "Alan Watts",
                    "born": "January 6, 1915",
                    "died": "November 16, 1973"
                }
            },
            "title": "bar"
        }]
    }
}
</code>```

Title: REST-ful design: recommended approach for fetching related entities

Body:
Suppose I have two entities author and post, were every post has an author.
Implemented are these REST calls

Get a paginated list of posts: GET /posts?page={page}

Get a list of authors: GET /authors

Get a single author: GET /authors/{id}

Suppose I also have a client using the REST service. This client wants to show a paginated list of posts with related authors.

Now how would the REST service work regarding the related entities? There are the following methods:

Let the GET /posts?page=1 call return the posts and the related authors in a single call. Optionally make this a separate parameter, f.e. GET /posts?page=1&related=true or GET /posts/related?page=1.

Let the client loop through the posts and get the author for every post using the GET /author/{id} call.

Let the REST call for the authors accept a list of ID's as a filter, so the client can get the related authors in one call, f.e. GET /authors?ids=10,12,16,30,43,44,58.

Method 1 is the easiest one from the client's perspective since it gets all the necessary data in one call. But the REST service is limited here, it shouldn't need to fit any particular client because every client has other requirements.

Method 2 is the cleanest REST approach, but let's say that a page has 30 posts, the client has to make 30 additional REST calls to retrieve the related authors. This is very inefficient.

Method 3 is perhaps better of the three, since it is a relatively clean REST implementation (compared to method 1) and it requires only one extra call per page.

Is there a recommended approach here?

Body:
You can also do it in one call by embedding authors inside posts. JSON Hypertext Application Language describes how to do this, see https://datatracker.ietf.org/doc/html/draft-kelly-json-hal-06

e.g. (modified copy from the doc):

{
    "_links": {
        "self": { "href": "/posts" },
        "next": { "href": "/posts?page=2" },
        "find": { "href": "/posts{?id}", "templated": true }
    },
    "_embedded": {
        "post": [{
            "_links": {
                "self": { "href": "/posts/321" },
                "author": { "href": "/author/alan-watts" }
            },
            "_embedded": {
                "author": {
                    "_links": { "self": { "href": "/author/alan-watts" } },
                    "name": "Alan Watts",
                    "born": "January 6, 1915",
                    "died": "November 16, 1973"
                }
            }
            "title": "foo"
        }, {
            "_links": {
                "self": { "href": "/posts/123" },
                "author": { "href": "/author/alan-watts" }
            },
            "_embedded": {
                "author": {
                    "_links": { "self": { "href": "/author/alan-watts" } },
                    "name": "Alan Watts",
                    "born": "January 6, 1915",
                    "died": "November 16, 1973"
                }
            },
            "title": "bar"
        }]
    }
}


问:
OpenGL vs OpenCV for beginner
I am a freshman college student currently learning C++ programming.  I am good at math and physics, so I am looking to specialize in 2D/3D graphics with OpenGL.  My question is about the differences between OpenGL and OpenCV, and the amount of overlap these areas have.  From what I have read, one creates graphics while the other processes them.  I have many books on 3D graphics and the mathematics associated with it.  What I am wondering is if the same concepts I am learning in OpenGL could be applied to OpenCV.  Is it possible to become a C++ software engineer that could specialize in both OpenGL AND OpenCV, or is this an unrealistic goal?

I ask these questions because I understand that 2D/3D graphics programming requires a tremendous amount of knowledge in math and physics, but I don't know too much about OpenCV and the prerequisite skills necessary to "get my foot in the door".

答:
I've never used OpenCV, but AFAIK, it is very different from OpenGL. OpenGL is a C API constructed around a LOT of global state (hence why it is often called a state machine), while OpenCV exposes a more Object Oriented C++ interface, with heavy use of templates.

OpenGL is intended to be a thin abstraction layer of the graphics hardware, so it can also be thought of as a device driver, in a sense. The primary focus of this API is real-time rendering, not general purpose computing. So the tools provided by OpenGL are primarily focused on drawing polygons to the screen as fast and as efficiently as possible.

I cannot make a good parallel between OpenGL and OpenCV, but my understanding is that CV is much more focused on offline image processing, so it is a different concept altogether if compared to GL. I would guess though, that OpenGL is oftentimes used in conjunction with OpenCV to implement visualization of the image processing done by CV, so if you focus on CV, you might benefit from knowing a graphics API like GL. If your main interest is in real-time graphics, such as games and CG films, then OpenGL should be enough. You are not very likely to need to know computer vision tools in those areas.

Finally, you are correct in saying that 2D/3D graphics programming requires knowledge of math and physics. If you are comfortable with the maths, life becomes a lot easier. If you like this field, learn the maths first, then learn a graphics API, such as OpenGL, to implement the theory.

Title: OpenGL vs OpenCV for beginner


答:
OpenGL is a 3D graphics API. It provides APIs describe a 3D scene and render it to a framebuffer and ultimately display it on a screen. The primitives it has are vertex lists, triangle lists, normal vector lists, etc. n.b. 2D is a special case of 3D; IIRC OpenGL doesn't have explicit 2D support (i.e. sprites and bit blit)

OpenCV is a computer vision (CV) API, and has implementations of various CV algorithms, blob detection, template matching, etc.

OpenCV generally operates on real image data, and wouldn't operate on graphics generated by OpenGL. (unless one was trying to make an AI bot that only sees the framebuffer output of a game, but that in another tangent altogether.)

"Is it possible to become a C++ software engineer that could specialize in both OpenGL AND OpenCV, or is this an unrealistic goal?"

Sure, they are different types of systems, and you could specialize in more than one thing. As for OpenGL and 3D graphics, if you learn one you can probably use any of them.

For computer vision learing one system will certianly help with another, but probably not to the same extent as computer graphics.

n.b This question probably belongs an another board.

Title: OpenGL vs OpenCV for beginner

Body:
I am a freshman college student currently learning C++ programming.  I am good at math and physics, so I am looking to specialize in 2D/3D graphics with OpenGL.  My question is about the differences between OpenGL and OpenCV, and the amount of overlap these areas have.  From what I have read, one creates graphics while the other processes them.  I have many books on 3D graphics and the mathematics associated with it.  What I am wondering is if the same concepts I am learning in OpenGL could be applied to OpenCV.  Is it possible to become a C++ software engineer that could specialize in both OpenGL AND OpenCV, or is this an unrealistic goal?

I ask these questions because I understand that 2D/3D graphics programming requires a tremendous amount of knowledge in math and physics, but I don't know too much about OpenCV and the prerequisite skills necessary to "get my foot in the door".


问:
"Comments are a code smell"
A coworker of mine believes that any use of in-code comments (ie, not javadoc style method or class comments) is a code smell.  What do you think?

答:
Here's my rule-of-thumb:

Write the code and store a short summary of the code in a separate document.

Leave the code alone for several days to work on something else.

Return to the code.  If you can't immediately understand what it's supposed to do, add the summary to the source file.

ContentLicense: CC BY-SA 2.5

Title: "Comments are a code smell"


问:
Most efficient/cleanest way to Kill a recursive thread safely
I have a number of worker threads which all perform a flood-fill task on different regions of a bitmap. They all make calls to a recursive sub-routine with different parameters(coordinates). Fyi, I am using a scan-line method.
I have implemented a reset feature which aims to kill these processes so that they would start again.

The way I have currently implemented my killing mechanism, is to use a kill Event with manual reset and make the flood-fill subroutine return if it is signaled. This way, the threads will still visit a considerable number of points on the region they are bounded to, before blissfully giving up, but nevertheless skip the relevant filling operation. I was wondering if there is a more efficient way of doing this.

P.S. Yes I know it's an over-kill for flood-fill, but this is a general question. One could imagine a matrix where you would want to perform some expensive local operations based on some local conditions and use a recursive routine of the same nature as an scanline approach.

EDIT:
Here is the current design of my framework:

```<code>m_pThread[i] = AfxBeginThread(FloodFill_Sub_ThreadProc, (LPVOID)m_pFloodFillInput[i], 0, 0, CREATE_SUSPENDED);
</code>```

with threadprocedures defined as:

```<code>UINT CTestShellDlg::FloodFill_Sub_ThreadProc(LPVOID pData)
{
...
FloodFill_Sub(mid, mid, Color_old, Color_new);
}
</code>```

and finally the FloodFill_Sub:

```<code>void CTestShellDlg::FloodFill_Sub(CPoint& node, CPoint& mid, COLORREF Color_old, COLORREF Color_new) /*Sub-routine to be used by threads*/
{
if (KillEventTriggered())
        return;
if (RecursionTerminationCondition)
        return;
//loop some scans and make recursive calls to FloodFill_Sub
...
}
</code>```

Now in the looping section, one could add further KillEventTriggered() checks, But I am wondering if there could be a better approach.

答:
There is no clean and safe way to quickly/efficiently "kill" a thread.  You can signal to the thread object that it needs to terminate, but the thread needs to be written in such a way that it checks for this and then cleans itself up.  Otherwise, you can end up with partially-completed operations, memory leaks, resource leaks, deadlocks, and all manner of chaos in your program.

Whether or not the threads involved are performing a recursive operation and spawning sub-threads really doesn't change this basic principle.


答:
There is another reason why you may want to inherit from a generic type.

Microsoft recommend avoiding nesting generic types in method signatures.

It is a good idea then, to create business-domain named types for some of your generics.  Instead of having a IEnumerable<IDictionary<string, MyClass>>, create a type MyDictionary : IDictionary<string, MyClass> and then your member becomes an IEnumerable<MyDictionary>, which is much more readable.  It also allows you to use MyDictionary in a number of places, increasing the explicitness of your code.

This may not sound like a huge benefit, but in real-world business code I've seen generics that will make your hair stand on end.  Things like List<Tuple<string, Dictionary<int, List<Dictionary<string, List<double>>>>>.  The meaning of that generic is in no way obvious.  Yet, if it were constructed with a series of explicitly created types the intention of the original developer would likely be a lot clearer.  Further still, if that generic type needed to change for some reason, finding and replacing all instances of that generic type might be a real pain, compared to changing it in the derived class.

Finally, there is another reason why someone might wish to create their own types derived from generics.  Consider the following classes:

```<code>public class MyClass
{
    public ICollection<MyItems> MyItems { get; private set; }
    // plumbing code here
}

public class MyOtherClass
{
    public ICollection<MyItems> MyItemCache { get; private set; }
    // plumbing code here
}

public class MyConsumerClass
{
    public MyConsumerClass(ICollection<MyItems> myItems)
    {
        // use the collection
    }
}
</code>```

Now how do we know which ICollection<MyItems> to pass into the constructor for MyConsumerClass? If we create derived classes class MyItems : ICollection<MyItems> and class MyItemCache : ICollection<MyItems>, MyConsumerClass can then be extremely specific about which of the two collections it actually wants.  This then works very nicely with an IoC container, which can resolve the two collections very easily.  It also allows the programmer to be more accurate - if it makes sense for MyConsumerClass to work with any ICollection, they can take the generic constructor.  If, however, it never makes business sense to use one of the two derived types, the developer can restrict the constructor parameter to the specific type.

In summary, it is often worthwhile to derive types from generic types - it allows for more explicit code where appropriate and helps readability and maintainability.

Title: Is it good practice to inherit from generic types?

Body:
Is it better to use List<string> in type annotations or StringList where StringList

```<code>class StringList : List<String> { /* no further code!*/ }
</code>```

I ran into several of these in Irony.

Body:
There is another reason why you may want to inherit from a generic type.

Microsoft recommend avoiding nesting generic types in method signatures.

It is a good idea then, to create business-domain named types for some of your generics.  Instead of having a IEnumerable<IDictionary<string, MyClass>>, create a type MyDictionary : IDictionary<string, MyClass> and then your member becomes an IEnumerable<MyDictionary>, which is much more readable.  It also allows you to use MyDictionary in a number of places, increasing the explicitness of your code.

This may not sound like a huge benefit, but in real-world business code I've seen generics that will make your hair stand on end.  Things like List<Tuple<string, Dictionary<int, List<Dictionary<string, List<double>>>>>.  The meaning of that generic is in no way obvious.  Yet, if it were constructed with a series of explicitly created types the intention of the original developer would likely be a lot clearer.  Further still, if that generic type needed to change for some reason, finding and replacing all instances of that generic type might be a real pain, compared to changing it in the derived class.

Finally, there is another reason why someone might wish to create their own types derived from generics.  Consider the following classes:

public class MyClass
{
    public ICollection<MyItems> MyItems { get; private set; }
    // plumbing code here
}

public class MyOtherClass
{
    public ICollection<MyItems> MyItemCache { get; private set; }
    // plumbing code here
}

public class MyConsumerClass
{
    public MyConsumerClass(ICollection<MyItems> myItems)
    {
        // use the collection
    }
}

Now how do we know which ICollection<MyItems> to pass into the constructor for MyConsumerClass? If we create derived classes class MyItems : ICollection<MyItems> and class MyItemCache : ICollection<MyItems>, MyConsumerClass can then be extremely specific about which of the two collections it actually wants.  This then works very nicely with an IoC container, which can resolve the two collections very easily.  It also allows the programmer to be more accurate - if it makes sense for MyConsumerClass to work with any ICollection, they can take the generic constructor.  If, however, it never makes business sense to use one of the two derived types, the developer can restrict the constructor parameter to the specific type.

In summary, it is often worthwhile to derive types from generic types - it allows for more explicit code where appropriate and helps readability and maintainability.


答:
You may take some inspiration from the ODATA protocol as a variation to your option 1. It has so called query options one of which is $expand that takes the value of the related resource to return.

The $expand system query option specifies the related resources to be included in line with retrieved resources. The request below returns people with navigation property Posts of an Author.

GET /authors/{id}/$expand=Posts

http://www.odata.org/getting-started/basic-tutorial/#expand

You may create your own one called $related.


答:
Here's another way to define OR, or indeed any logical operator, using the most traditional way of defining it: use a truth table.

This is of course quite trivial to do in higher level languages such as Javascript or Perl but I'm writing this example in C to show that the technique does not depend on high level language features:

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

int main (void) {
    // Define truth table for OR:
    int OR[2][2] = {
        {0,   // false, false
         1},  // false, true
        {1,   // true, false
         1}   // true, true
    }

    // Let's test the definition
    printf("false || false = %d\n",OR[1==2]['b'=='a']);
    printf("true || false = %d\n",OR[10==10]['b'=='a']);

    // Usage:
    if (OR[ 1==2 ][ 3==4 ]) {
        printf("at least one is true\n");
    }
    else {
        printf("both are false\n");
    }
}
</code>```

You can do the same with AND, NOR, NAND, NOT and XOR. The code is clean enough to look like syntax such that you can do stuff like this:

```<code>if (OR[ a ][ AND[ b ][ c ] ]) { /* ... */ }
</code>```

Title: How to define "or" logically

Body:
Recently, I came across a problem that required me to define the logical "OR" operator programmatically, but without using the operator itself.

What I came up with is this:

OR(arg1, arg2)
  if arg1 = True and arg2 = True
     return True

  else if arg1 = True and arg2 = False
     return True

  else if arg1 = False and arg2 = True
     return True

  else:
     return False
```

Is this logic correct, or did I miss something?

Body:
Here's another way to define OR, or indeed any logical operator, using the most traditional way of defining it: use a truth table.

This is of course quite trivial to do in higher level languages such as Javascript or Perl but I'm writing this example in C to show that the technique does not depend on high level language features:

#include <stdio.h>

int main (void) {
    // Define truth table for OR:
    int OR[2][2] = {
        {0,   // false, false
         1},  // false, true
        {1,   // true, false
         1}   // true, true
    }

    // Let's test the definition
    printf("false || false = %d\n",OR[1==2]['b'=='a']);
    printf("true || false = %d\n",OR[10==10]['b'=='a']);

    // Usage:
    if (OR[ 1==2 ][ 3==4 ]) {
        printf("at least one is true\n");
    }
    else {
        printf("both are false\n");
    }
}

You can do the same with AND, NOR, NAND, NOT and XOR. The code is clean enough to look like syntax such that you can do stuff like this:

if (OR[ a ][ AND[ b ][ c ] ]) { /* ... */ }


问:
How do I Create Automated UI test code for application developed using Domain-Driven-Design with very little concrete UI requirements?
We are developing an application using Domain-Driven-Design(DDD).

We have to come up with Automated UI Test code.

The customer has used 3rd-party GUI Administration template (https://bootstraphunter.com/smartadmin-product.php) so that the GUI can be configured for the most part using the aforementioned 3rd-party tool.

For Automated UI Testing, I'm going to use NUnit with Selenium because I have experience using the said tools.

Sadly,  the specifics about the Business-Side is left out.

In other words, customers has Not provided us with any use-cases or use case diagrams.

So far, a lot of the backend development(database stuff) deals with Generating New tables using Code-Generation Tools.

This basically suggests that the Customer is creating specific development tools for the application.  As time goes on, I feel that the customer will configure the development tools to generate code and/or database tables.

Since a lot of the Business-specific requirements are vague, the customers communicates with our GUI development team to discuss how some module should be configured, but the problem is that I end up creating the Automated test code after the GUI module development is complete which is kind of pointless.

What steps should I take to make my Automated UI testing be significant in terms of usefulness in the development of the application?

答:
At some point in time, someone has to make a decision how the UI has to look like. If this is done iteratively step-by-step in a dicussion between the customer and your team, fine - that is a feasible, pragmatic way. Whenever the decision is made for a particular part of your UI, you can start creating the tests.

I end up creating the Automated test code after the GUI module development is complete which is kind of pointless

Why do you think this is pointless? Automated tests are primarily regression tests,  verifying your application Version 2.0 still works like Version 1.0, after you added some new features. If you need tests only once or twice to to verify a written spec, it would be pointless to automate them, since it would most probably be much more efficient to do the tests manually.


问:
Periodically polling an API, are there alternatives?
I'm currently working on a service that is supposed to aggregate data from a number of APIs, unify the data, and offer it through another API to the users. I had a couple of ideas for solving this, but I'm not confident my best solution is the best possible solution.

Solutions I considered:

Let the browser poll our API through javascript, which in turn polls the third party APIs. This introduces quite a bit of lag between the request and the user seeing the data, but doesn't waste resources on users that rarely log in.

Let the browser poll the third party APIs and afterwards send the data to our API. This is potentially insecure, and requires me to provide extra API endpoints and a lot more data cleanup.

The option I currently consider the most optimal is letting a service on the server (an actual executable) periodically poll the third party APIs. I would, for example, poll some endpoints every 30 minutes, and others maybe once a day. This is the safest option, and introduces little lag to user requests, and prevents users from reaching the request limit of the API. But data will only be up-to-date right after polling.

Are there any alternatives? If not, is my current optimal solution good enough?

答: If you have control over any of the apis, and for your own api if you are expecting the browser to display "live" updates, you may want to consider implementing "long polling", also known as "comet". In long polling, whena request is made, the server checks to see if anything has changed since the client last polled (it can be helpful if the client includes a time stamp from the response to its last poll for working this out) and if so returns the changed data immediately. Otherwise, it waits until data does change before returning.  Therefore, the client only needs to make a single request and wait for the data to come back, rather than n having to continuously poll. This reduces load on the server and makes clients respond faster.</p>


问:
Java Unit testing multiple test cases in one test
Is it good practice to have multiple test cases in one test or should I always create one test for single test case in every situation even if it is redundant? Why? </p>

答:
The common approach is to put each independent test in its own test method. The main reason for this is to make the list of passing/failing tests as self-documenting as possible. Ideally you should be able to look at which test failed and have a good idea what is wrong with the code from that alone. If single test methods test multiple things, this is not possible.

Sometimes it happens that two tests have identical setup; in this case it is recommended to factor out the common code into a helper method.


问:
Why do we have to use break in switch?
Who decided (and based on what concepts) that switch construction (in many languages) has to use break in each statement?

Why do we have to write something like this:

```<code>switch(a)
{
    case 1:
        result = 'one';
        break;
    case 2:
        result = 'two';
        break;
    default:
        result = 'not determined';
        break;
}
</code>```

(noticed this in PHP and JS; there are probably many other languages using this)

If switch is an alternative of if, why we can't use the same construction as for if? I.e.:

```<code>switch(a)
{
    case 1:
    {
        result = 'one';
    }
    case 2:
    {
        result = 'two';
    }
    default:
    {
        result = 'not determined';
    }
}
</code>```

It is said that break prevents the execution of the block following the current one. But, does someone really run into the situation, where there was any need for execution of the current block and following ones? I didn't. For me, break is always there. In every block. In every code.

答:
To answer two of your questions.

Why does C need breaks?

It comes down to Cs roots as a "portable assembler". Where psudo code like this was common:-

```<code>    targets=(addr1,addr2,addr3);
    opt = 1  ## or 0 or 2
switch:
    br targets[opt]  ## go to addr2
addr1:
    do 1stuff
    br switchend
addr2:
    do 2stuff
    br switchend
addr3
    do 3stuff
switchend:
    ......
</code>```

the switch statement was designed to provide similar functionality at a higher level.

Do we ever have switches without breaks?

Yes this is quite common and there are a few use cases;

Firstly you may want to take the same action for several cases. We do this by stacking the cases on top of each other:

```<code>case 6:
case 9:
    // six or nine code
</code>```

Another use case common in state machines is that after processing one state we immediately want to enter and process another state:

```<code>case 9:
    crashed()
    newstate=10;
case 10:
    claim_damage();
    break;
</code>```

Title: Why do we have to use break in switch?

Body:
To answer two of your questions.

Why does C need breaks?

It comes down to Cs roots as a "portable assembler". Where psudo code like this was common:-

    targets=(addr1,addr2,addr3);
    opt = 1  ## or 0 or 2
switch:
    br targets[opt]  ## go to addr2
addr1:
    do 1stuff
    br switchend
addr2:
    do 2stuff
    br switchend
addr3
    do 3stuff
switchend:
    ......

the switch statement was designed to provide similar functionality at a higher level.

Do we ever have switches without breaks?

Yes this is quite common and there are a few use cases;

Firstly you may want to take the same action for several cases. We do this by stacking the cases on top of each other:

case 6:
case 9:
    // six or nine code

Another use case common in state machines is that after processing one state we immediately want to enter and process another state:

case 9:
    crashed()
    newstate=10;
case 10:
    claim_damage();
    break;


问:
What's the etiquette on looking at the other person's email when pair programming?
To me - if you're pair programming - then you don't open your email, or you decide you're cool with the other person looking at it.

I've worked with a person who looks away, and expects you not to look when they look at their email. I'm not familiar with this "code of practice".

My question is: What's the etiquette on looking at the other person's email when pair programming?

答:
Communication is key. You have to ask the person if:

Spending time reading e-mails is OK. The person may not be happy to remain idle for a few minutes waiting for you to read your e-mails. I worked with persons who were against doing anything disturbing during the pair programming session, such as reading/sending text messages or answering phone calls. This is a good approach when working on critical parts of the code base which require strong focus.

Although this is not what your question is about, I still think this is an important point to highlight, maybe more important than reading your colleague's e-mails, especially since some people won't dare telling you that they are unhappy waiting for you to read your e-mails (and asking themselves whether they can read them too).

Reading your colleague's e-mails is OK. Some people don't care. They leave their session opened when leaving for a 10-minutes break with their Skype and e-mail client turned on. They wouldn't care less if you will watch their browser history or their e-mails. Other people will lock their machine every time they are not in front of it and won't appreciate if you start reading their e-mails or explore the files on their machine.

Finally, the nature of the e-mails is important too:

While the person is not expected to receive personal e-mails at work, some people still do it and you probably shouldn't read them.

Some company e-mails may be confidential (and in the worst case, you won't know it until you read the message).

If unsure (and you can't discuss the subject with your colleague), just look somewhere else when your colleague is reading his e-mails, or ask to do it outside pair programming sessions.

Also, reading e-mails on a mobile device can be an easy solution to the problem. The pair programming session is not interrupted and the confidentiality is preserved.


答:
There is no general rule: you have to discuss it with your pair.

Pair-programming is a pretty invasive practice. You do not decide to invite a colleague into your private space to discuss something. Instead, you are supposed to give up your private space and share your desktop, screen, thoughts, on a regular basis: you work very close to each other. You set up rules along the way by telling your pair what he / she can do and what not. For each pair it is different. Some pairs work well together from day 1, some pairs take weeks or months to find common rules, some never do.

The specific case of email really depends on your pair: some just don't care, some expect you to look away, some will read email during a break so you don't have a chance to see it, and so on.

Body:
To me - if you're pair programming - then you don't open your email, or you decide you're cool with the other person looking at it.

I've worked with a person who looks away, and expects you not to look when they look at their email. I'm not familiar with this "code of practice".

My question is: What's the etiquette on looking at the other person's email when pair programming?


问:
What is the hierarchical DB schema for this xml?
As per this link, this is the xml that maintains "BookStore" data.

I see that number of occurences of author are varying for any book.

xml's hierarchical representation of BookStore looks more meaningful/intuitive for me to visualise the data unlike relational table tuples. It is rather more difficult(kind of tweek) to map such hierarchical information in tables.

It is strange to see that real world(hierarchical) data(for example, SNMP MIBs of network devices or BookStore etc...) are mapped to tables of records in many commercial softwares. For me, it is not-intuitive(rather unnecessary skill) to convert such hierarchical data to tables, despite relational DB(like MSSQL) support massive/safe/multi-user/convenient/efficient/reliable unlike  xml file format.

So, we are trying to fit hierarchical ordered data into table tuples which is an overhead. Do we have any commercial database that companies use to maintain schema in hierarchical fashion?

Note: am currently part of database course.

答:
If you choose to maintain a hierarchy in a relational database, you need to look into the Nested Set design pattern.  (See Wikipedia)

This model involves some programming, and it involves some overhead at insert or update time.  The benefit comes at retrieval time.  Retrieving the path or the subtree for any given node is easy and fast, when compared to the traditional approach, called Adjacency List.


问:
Calculating physical address given only an offset for my process
Learning about virtual memory with an program assignment. Currently this is what I have:

Main memory has 60 bytes and virtual memory another 60 bytes. The size of a frame/page is 10 bytes. So there are 6 frames for main and 6 for virtual memory.

I have a process that uses 40 bytes, so it needs 4 pages. By assignment specifications, when I load a process its four pages must be allocated randomly, so suppose this is how it looks now:

I've managed to do most things, like paging something, restoring a page with LFU and LRU, loading more processes etc. But there is one particular point that confuses me:

Given an offset for your process, you must return the physical
  address. You must verify that the offset is within the size of your
  process.

As far as I am concerned, you can calculate a physical address if you are given an offset AND a page number. But I am only given an offset number.

My guess is that you can get the page number using this same offset number too. For instance, if the offset is 36, then the page number would be 3 (because each page is 10 bytes large) with an offset of 6 bytes. Therefore the physical address would be 56? But then I have a bigger question:

What if I am given the number 25? It would be page 2 with offset 5. But such page is in virtual memory. Do I have to MOVE this page to main memory first?

答:
You have a basic misunderstanding of how virtual memory works.

The virtual memory space of a process is a linear list of addresses, 0 to N. The addresses within the virtual memory space are segmented into pages, and those pages may reside either in RAM or on disk (although they must be moved to RAM to execute).

So your diagram needs three blocks:

To "calculate a physical address" given a virtual address (which is the closest interpretation I have of "offset"), you use the page table to find out where a page resides. The result is a tuple that identifies where the pages resides (RAM or disk), and where in that space it resides (this could be an absolute address, as long as you consider swap to be a contiguous memory space).


问:
How can I encrypt or remove readability of source code before publishing it?
I am working on a collaborative project, for which I have to submit source code, which will be used/embedded in the main repository for re-compilation. Is there any way, I can encrypt the source code or may apply some other technique so that I can remove the readability of my code completely, but it still compiles well after applying decryption or anti-pattern.

Nature of my Project is an enterprise level distributed application, having different clients being written for cloud,desktop,web,mobile etc.

So, is there any general purpose technique/design pattern or some concept, by applying which I can publish my source and still not exposing it.

答:
This is called obfuscation.

What it does is that it performs a series of operations which don't affect the execution of the source code, but make it more difficult to read of a human.

For example, here are some commonly used obfuscation techniques:

Remove whitespace.

Remove comments.

Replace meaningful names of variables and members by names such as a, b, c.

With only those three basic techniques, this code:

public string GenerateFileName()
{
    var basePath = this.FindBasePath();
    do
    {
        var counter = this.CounterExists ? this.GetCounter() : 0;
        var name = this.GenerateName(counter);

        // If the file limit was exceeded, it indicates that something went wrong.
        // Possible causes include two services running side by side on the same machine
        // or two machines running the service using a share. Remember that the service
        // should be bound to a directory which is not used by any other application.
        if (counter > MaximumAllowedFiles)
        {
            throw new StorageThresholdException();
        }
    }
    while (File.Exists(Path.Combine(basePath, name)));
}
```

<p>becomes:</p>

```public string c(){var a=this.h();do{var b=this.k?this.b():0;var c=this.d(b);if(b>i){throw
new af();}}while(File.Exists(Path.Combine(a,c)));}
```

Less frequently used obfuscation techniques include but not limited to:

Encryption of strings,

Inlining (i.e. moving the body of a method in the method which was calling the first one),

Control flow obfuscation,

Encryption of source code (the effectiveness of this technique is highly disputed, since if the machine running the application can decrypt the source code in order to run it, the user of this machine can do it as well).

Of course, you shouldn't do the obfuscation yourself, but rather search for a tool which makes this for the language of your choice.

Note that some tools don't have obfuscation as their primary goal, but still can be used for that. Google Closure Compiler, for example, is intended to (1) perform static checking of the code and to (2) reduce the size of JavaScript files, but has a side effect of making source code quite unreadable.

Body:
This is called obfuscation.

What it does is that it performs a series of operations which don't affect the execution of the source code, but make it more difficult to read of a human.

For example, here are some commonly used obfuscation techniques:

Remove whitespace.

Remove comments.

Replace meaningful names of variables and members by names such as a, b, c.

With only those three basic techniques, this code:

public string GenerateFileName()
{
    var basePath = this.FindBasePath();
    do
    {
        var counter = this.CounterExists ? this.GetCounter() : 0;
        var name = this.GenerateName(counter);

        // If the file limit was exceeded, it indicates that something went wrong.
        // Possible causes include two services running side by side on the same machine
        // or two machines running the service using a share. Remember that the service
        // should be bound to a directory which is not used by any other application.
        if (counter > MaximumAllowedFiles)
        {
            throw new StorageThresholdException();
        }
    }
    while (File.Exists(Path.Combine(basePath, name)));
}

becomes:

public string c(){var a=this.h();do{var b=this.k?this.b():0;var c=this.d(b);if(b>i){throw
new af();}}while(File.Exists(Path.Combine(a,c)));}

Less frequently used obfuscation techniques include but not limited to:

Encryption of strings,

Inlining (i.e. moving the body of a method in the method which was calling the first one),

Control flow obfuscation,

Encryption of source code (the effectiveness of this technique is highly disputed, since if the machine running the application can decrypt the source code in order to run it, the user of this machine can do it as well).

Of course, you shouldn't do the obfuscation yourself, but rather search for a tool which makes this for the language of your choice.

Note that some tools don't have obfuscation as their primary goal, but still can be used for that. Google Closure Compiler, for example, is intended to (1) perform static checking of the code and to (2) reduce the size of JavaScript files, but has a side effect of making source code quite unreadable.


问:
What is the value of workflow tools?
I'm new to Workflow developement, and I don't think I'm really getting the "big picture". Or perhaps to put it differently, these tools don't currently "click" in my head.

So it seems that companies like to create business drawings to describe processes, and at some point someone decided that they could use a state machine like program to actually control processes from a line and boxes like diagram. Ten years later, these tools are huge, extremely complicated (my company is currently playing around with WebSphere, and I've attended some of the training, its a monster, even the so called "minimalist" versions of these workflow tools like Activiti are huge and complicated although not nearly as complicated as the beast that is WebSphere afaict).

What is the great benefit in doing it this way? I can kind of understand the simple lines and boxes diagrams being useful, but these things, as far as I can tell, are visual programming languages at this point, complete with conditionals and loops. Programmers here appear to be doing a significant amount of work in the lines and boxes layer, which to me just looks like a really crappy, really basic visual programming language.

If you're going to go that far, why not just use some sort of scripting language? Have people thrown the baby out with the bathwater on this? Has the lines and boxes thing been taken to an absurd level, or am I just not understanding the value in all this?

I'd really like to see arguments in defense of this by people that have worked with this technology and understand why its useful. I don't see the value in it, but I recognize that I'm new to this as well and may not quite get it yet.

答:
In simple example by history.

Stone age

At first you had small menhir companies where people just where told what to do, and they did it. Sometimes things wend wrong, and Person X or Y got blamed (never sure who really did it).

Next internet and Email was invented.

People now wrote others what to do, and those people often had problems with their Email, read it wrongly, or just simply deleted an Email without ever reading it; so often things where not don blaming it on bad Email

Workflow evolved out of administration
By standardizing the actions, finally people could see at what phase who halted a process, and at the same time, got a digital overview of what actually had been done.
This worked nice till people wanted to change standard processes, or till some unknown X Y person caused an improper database request resulting in database corruption, sending production back to stone age..

Title: What is the value of workflow tools?


问:
Is Exploratory testing Context Driven testing?
I do not think so, yet many sources say it is.

As I understand it:

Context-driven testing means that when planning testing on our project, I choose the methods, practices, etc. in order to fit the context. I choose the approach

While exploratory testing is a just a method of testing, where testers explore certain part of the application and dynamically design and run test cases,possibly exploring new areas and new tests.

I know Exploratory testing is related to context-driven but I do not believe it means the same.

Is that correct understanding?

答:
I think that's a bit like asking if emacs is agile. The two don't really equate. If you are into the context-driven testing movement, then exploratory testing is one sort of testing you might do given the current context.

Exploratory testing, in and of itself, isn't context-driven testing. It is exploratory testing, much like unit testing also isn't context-driven testing. Exploratory testing is one of many types of testing one can do for a software project.


问:
Why can't the Scala compiler give pattern matching warning for nonsealed classes/traits?
If I use an unsealed trait or abstract class in Scala and then use pattern matching, I wonder, does the compiler not know at compile time for this particular patternmatch what possible implementations of this trait/class are available? So, if it does, could it not give pattern match warnings even though that the trait/abstract class is not sealed because he knows which types could be used, by checking all the possible dependencies/imports?

E.g. if I have an Option[A] and I do pattern matching only for Some[A] but not for None, the compiler will complain, because Option is sealed.

If the compiler can't know/resolve that, then why can't he?
And if the compiler (theoretically) can do that, what are the reasons for that it is not used in Scala?
Are there other languages which support that kind of behaviour?

答:
Figuring out all subclasses of a class is called Class Hierarchy Analysis, and doing static CHA in a language with dynamic code loading is equivalent to solving the Halting Problem.

Plus, one of the goals of Scala is separate compilation and deployment of independent modules, so the compiler simply cannot know whether or not a class is subclassed in another module, because it never looks at more than one module. (After all, you could compile a module against the interface of some other module without that module even existing on your system!) That's why sealed requires all subclasses to be defined in the same compilation unit.

That's also one of the reasons why JVMs can compete so favorably with C++ compilers: C++ compilers are typically static compilers, so they can't in general figure out whether a method is overridden or not, and thus can't inline it. JVMs OTOH, typically are dynamic compilers, they don't need to perform CHA to figure out whether a method is overridden or not, they can just look at the Class Hierarchy at runtime. And even if at a later point in the execution of the program a new subclass comes along that wasn't there before, no big deal, just recompile that piece of code without inlining.

Note: all of this only applies within Scala. The JVM has no notion of sealed, so it is perfectly possible to subclass sealed classes from another JVM language, since there is no way to communicate this to another language. The sealed property is recorded in the ScalaSig annotation, but other languages' compilers don't take those annotations into account, obviously.


答:
It can be done (at least for all classes known at compile time), it's just expensive.  You'd completely destroy incremental compilation, because everything that contains a pattern match would effectively have to be recompiled every time any other file changed.

And what are you buying?  It's a code smell to write pattern matches that need to change frequently when a new derived class is added.  It's a violation of the open/closed principle.  Use inheritance properly and you won't need to write those kinds of pattern matches.  And yes, the open/closed principle also applies to functional languages without class-based inheritance. In fact between features like type classes, multimethods, and just plain higher-order functions, functional languages make extension without modification much easier.

Title: Why can't the Scala compiler give pattern matching warning for nonsealed classes/traits?

Body:
If I use an unsealed trait or abstract class in Scala and then use pattern matching, I wonder, does the compiler not know at compile time for this particular patternmatch what possible implementations of this trait/class are available? So, if it does, could it not give pattern match warnings even though that the trait/abstract class is not sealed because he knows which types could be used, by checking all the possible dependencies/imports?

E.g. if I have an Option[A] and I do pattern matching only for Some[A] but not for None, the compiler will complain, because Option is sealed.

If the compiler can't know/resolve that, then why can't he?
And if the compiler (theoretically) can do that, what are the reasons for that it is not used in Scala?
Are there other languages which support that kind of behaviour?


答:
Several people have already mentioned the notion of matching multiple conditions, which is very valuable from time to time.  However the ability to match multiple conditions does not necessarily require that you do the exact same thing with each condition that matches.  Consider the following:

```<code>switch (someCase)
{
    case 1:
    case 2:
        doSomething1And2();
        break;

    case 3:
        doSomething3();

    case 4:
        doSomething3And4();
        break;

    default:
        throw new Error("Invalid Case");
}
</code>```

There are two different ways sets of multiple conditions are being matched here.  With conditions 1 and 2, they simply fall through to the exact same plot of code and do the exact same thing.  With conditions 3 and 4, however, although they both end by calling doSomething3And4(), only 3 calls doSomething3().

Title: Why do we have to use break in switch?

Body:
Who decided (and based on what concepts) that switch construction (in many languages) has to use break in each statement?

Why do we have to write something like this:

```<code>switch(a)
{
    case 1:
        result = 'one';
        break;
    case 2:
        result = 'two';
        break;
    default:
        result = 'not determined';
        break;
}
</code>```

(noticed this in PHP and JS; there are probably many other languages using this)

If switch is an alternative of if, why we can't use the same construction as for if? I.e.:

```<code>switch(a)
{
    case 1:
    {
        result = 'one';
    }
    case 2:
    {
        result = 'two';
    }
    default:
    {
        result = 'not determined';
    }
}
</code>```

It is said that break prevents the execution of the block following the current one. But, does someone really run into the situation, where there was any need for execution of the current block and following ones? I didn't. For me, break is always there. In every block. In every code.

Body:
Several people have already mentioned the notion of matching multiple conditions, which is very valuable from time to time.  However the ability to match multiple conditions does not necessarily require that you do the exact same thing with each condition that matches.  Consider the following:

switch (someCase)
{
    case 1:
    case 2:
        doSomething1And2();
        break;

    case 3:
        doSomething3();

    case 4:
        doSomething3And4();
        break;

    default:
        throw new Error("Invalid Case");
}

There are two different ways sets of multiple conditions are being matched here.  With conditions 1 and 2, they simply fall through to the exact same plot of code and do the exact same thing.  With conditions 3 and 4, however, although they both end by calling doSomething3And4(), only 3 calls doSomething3().