问:
Does implicit and explicit cast operator overloading violate the D in SOLID principles of OO?
I'm looking at different patterns and techniques for implementing logic to convert object from one class to another, and the most elegant seems to be explicit cast operator overloading (in C#). However, it seems to me that it violates the Dependency Inversion principle, as it requires one concrete class to have references to another concrete class.

Is this assessment accurate? Is it problematic? Is there a way to implement explicit cast operator overloading without violating the DI principle?

```<code>public class Model
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

public class ViewModel
{
    public string PropOne { get; set; }

    public static explicit operator ViewModel(Model model)
    {
        // Conversion logic that references both classes
    }
}

public class Program
{
    public void Main()
    {
        var model = new Model{ Prop1 = "SomeValue", Prop2 = "SomeOtherValue" };
        var viewModel = (ViewModel) model;

        Console.WriteLine(viewModel.PropOne); // Outputs "SomeValue" to the console
        Console.ReadKey();
    }
}
</code>```

答:
No matter what, you're going to have references to the other class if you want to convert between them - you either have your class know about the class you need to convert itself into, or you put a constructor on the other class which means it has to know about your class (or has to accept a heap of property parameters that just happen to match the individual properties of your class which will just be very ugly)

You could create a "factory" class that exists solely to turn objects of one class into another, but I'd say that was just getting silly. It also would need to know about both classes but at least each of those classes could exist in their own isolated bubbles. This maybe very important or useful in some circumstances.

But the general case, no matter what, you have to interact with the rest of the world so there will always be interface points you ave to deal with.


问:
If Java allows immutable classes, then why cannot it be used as a functional language
I have been struggling with functional programming concepts for a while. I read that in functional programming, variable immutability is a fundamental thing. You don't change the state of a variable.

But I can achieve the same effect in Java by using the keyword 'final'?
So why cannot Java be used as a functional language?

答:
Sure, you can do programming in a functional style in Java.  It's just really difficult, because there's a lot more to it than just immutability.  One of the big ones is first-class functions, (being able to treat a function reference as a variable, without it having to be tied to an object,) which the Java language has provided no functionality for up until very recently, when lambdas were introduced.

Even now that it's possible, there's still 20 years of legacy Java code hanging around that has no concept of functional programming, that your code will probably have to interact with, so that makes any use of it more difficult than it probably should be.

ContentLicense: CC BY-SA 3.0


问:
How to Handle Duplicate Web Requests on Server
I'm running a Twisted web server and trying to figure out a good way to handle retries from the client. In normal operation the client makes a request of the server with some JSON data and receives a JSON response. Every request includes a header with a unique identifier.

I'm trying to handle the case where the client doesn't receive the response (might time out) and needs to resubmit the request. Since the request can change the server state I don't want it to reprocess if it's already been processed.

Possible approaches:

What I'm thinking of is caching every JSON response and if the client
submits a request with a duplicate request ID then just return the cached
data. The thing is I'm not sure how often this situation will
actually come up in the wild and caching every response and
inspecting every request might be a lot of overhead (some responses
are quite large JSON structures).

I could minimize much of the caching by just returning a HTTP response
that indicates it was a duplicate request, but then the client won't know
what the original response was.

Is there a best-practice for handling duplicate requests from a server?

答:
A lot depends on how much traffic you expect to see and how often this situation will occur.

To avoid premature optimization, I'd first go with a variation of your 2nd choice - treat the duplicate request as an error (and log it as such).

If you see it happening often enough to warrant action, then your 1st choice - cache the output - seems reasonable.  You can set rules on how long the data is to be cached - it doesn't need to be that long.

For that matter, I think there are HTTP headers you can include with your output to indicate that the various servers & firewalls are allowed to cache the response for a time.  That might be easier than cooking up your own cache mechanism.


问:
What is your favorite whiteboard interview problem?
Just as the title says, what is your favorite whiteboard interview problem, and why has it proven effective for you?

Junior, senior, Java, C, Javascript, PHP, SQL, pseudo-code, etc.

答:
Implement function/method(on c/c++/c# whatever), which calculates n-th item of Fibonacci sequence

Many guys could stuck on this.
If some solution is given - usually it uses recursion.
After that:

Implement the same via 'for'-loop

Can't tell you, how many fellows fail to complete both tasks - 50% of candidates.

That's why I like it :)

ContentLicense: CC BY-SA 2.5


问:
How to draw programmer's attentions in certain conditions?
Let's start with an example.

Let's say, I have a method called export that depends heavily on the DB schema. And by “depends heavily” I mean I know that adding a new column to a certain table often (very often) leads to the corresponding export method change (usually you should add the new field to the export data as well).

Programmers often forget to change export method since it's not really clear you should even look at this. My goal is to force programmer explicitly make a decision to determine whether he forgot to look at the export method or just don't want to add a field to the export data. And I'm looking for the design solution for this problem.

I have two ideas, but both of them have flaws.

Smart “Read all” wrapper

I can create the smart wrapper that makes sure all data is explicitly read.

Something like this:

```<code>def export():
    checker = AllReadChecker.new(table_row)

    name    = checker.get('name')
    surname = checker.get('surname')
              checker.ignore('age') # explicitly ignore the "age" field

    result = [name, surname] # or whatever

    checker.check_now() # check all is read

    return result
</code>```

So, checker asserts if table_row contains another fields that were not read. But all this thing looks kind of heavy and (maybe) affects perfomance.

“Check that method” unittest

I can just create the unittest that remembers the last table schema and fails every time the table is changed. In that case programmer would see something like “don't forget to check out the export method”. To hide the warning  programmer would (or wouldn't — that's a problem) check out export and manually (that's another problem) fix the test by adding new fields into it.

I have a few other ideas but they are too troublesome to implement or too difficult to understand (and I don't want the project to become a puzzle).

The above problem is just an example of the more wide class of problems I encounter from time to time. I want to bind some pieces of code and/or infrastructure so changing one of them immediately alerts programmer to check another one. Usually you have some simple tools like extracting common logic or writing reliable unittest, but I'm looking for the tool for more complex cases: maybe some design patterns I'm now aware of.

答:
You're on a right track with your unit test idea, but your implementation is wrong.

If the export is related to the schema and the schema changed, there are two possible cases:

Either the export still works perfectly well, because it was unaffected by a slight change in the schema,

Or it breaks.

In both cases, it's the goal of the build to track down this possible regression. A bunch of tests—would it be integration tests, or system tests, or functional tests or something else—ensure that your export procedure works with the current schema, independently of the fact that it changed or not since the previous commit. If those tests pass, great. If they fail, this is a sign to the developer that he may have missed something, and a clear indication where to look.

Why is your implementation wrong? Well, for several reasons.

It has nothing to do with unit tests...

... and, actually, it's not even a test.

The worst part is that fixing the “test” requires to, well, actually changing the “test”, that is doing an operation which is completely unrelated to the export.

Instead, by making actual tests for export procedure, you make sure that the developer will fix the export.

More generally, when you encounter a situation where a change in one class always or usually requires a change in a completely different class, this is a good sign that you did your design wrong and are violating the Single Responsibility Principle.

While I talk specifically about classes, it applies more or less to other entities as well. For instance, a change in database schema should be either reflected automatically in your code, for instance through code generators used by many ORMs, or should at least be easily localized: if I add Description column to Product table and I use no ORMs or code generators, I at least expect to make a single change within Data.Product class of the DAL, without the need to search through all the code base and find some occurrences of Product class in, say, presentation layer.

If you can't reasonably restrict the change to one location (either because you're in a case where it simply doesn't work, or because it requires a huge amount of development), then you create a risk of regressions. When I change class A, and class B somewhere in the code base stops working, it's a regression.

Testing lowers the risk of regressions and, which is far more important, shows you the location of a regression. This is why when you know that changes in one location cause issues in a completely different part of the code base, make sure you have enough tests which raise alarms as soon as a regression appears at this level.

In all cases, avoid relying in such cases just on the comments. Something like:

```<code>// If you change the following line, make sure you also change the corresponding
// `measure` value in `Scaffolding.Builder`.
</code>```

never works. Not only developers won't read it in most cases, but it will often end either removed or moved far away from the concerned line, and become impossible to understand.

Body:
You're on a right track with your unit test idea, but your implementation is wrong.

If the export is related to the schema and the schema changed, there are two possible cases:

Either the export still works perfectly well, because it was unaffected by a slight change in the schema,

Or it breaks.

In both cases, it's the goal of the build to track down this possible regression. A bunch of tests—would it be integration tests, or system tests, or functional tests or something else—ensure that your export procedure works with the current schema, independently of the fact that it changed or not since the previous commit. If those tests pass, great. If they fail, this is a sign to the developer that he may have missed something, and a clear indication where to look.

Why is your implementation wrong? Well, for several reasons.

It has nothing to do with unit tests...

... and, actually, it's not even a test.

The worst part is that fixing the “test” requires to, well, actually changing the “test”, that is doing an operation which is completely unrelated to the export.

Instead, by making actual tests for export procedure, you make sure that the developer will fix the export.

More generally, when you encounter a situation where a change in one class always or usually requires a change in a completely different class, this is a good sign that you did your design wrong and are violating the Single Responsibility Principle.

While I talk specifically about classes, it applies more or less to other entities as well. For instance, a change in database schema should be either reflected automatically in your code, for instance through code generators used by many ORMs, or should at least be easily localized: if I add Description column to Product table and I use no ORMs or code generators, I at least expect to make a single change within Data.Product class of the DAL, without the need to search through all the code base and find some occurrences of Product class in, say, presentation layer.

If you can't reasonably restrict the change to one location (either because you're in a case where it simply doesn't work, or because it requires a huge amount of development), then you create a risk of regressions. When I change class A, and class B somewhere in the code base stops working, it's a regression.

Testing lowers the risk of regressions and, which is far more important, shows you the location of a regression. This is why when you know that changes in one location cause issues in a completely different part of the code base, make sure you have enough tests which raise alarms as soon as a regression appears at this level.

In all cases, avoid relying in such cases just on the comments. Something like:

// If you change the following line, make sure you also change the corresponding
// `measure` value in `Scaffolding.Builder`.

never works. Not only developers won't read it in most cases, but it will often end either removed or moved far away from the concerned line, and become impossible to understand.


问:
Is there a specific reason for the poor readability of regular expression syntax design?
Programmers all seem to agree that readability of code is far more important than short-syntaxed one-liners which work, but require a senior developer to interpret with any degree of accuracy - but that seems to be exactly the way regular expressions were designed. Was there a reason for this?

We all agree that selfDocumentingMethodName() is far better than e(). Why should that not apply to regular expressions as well?

It seems to me that rather than designing a syntax of one-line logic with no structural organization:

```<code>var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})(0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
</code>```

And this isn't even strict parsing of a URL!

Instead, we could make a some pipeline structure organized and readable, for a basic example:

```<code>string.regex
   .isRange('A-Z' || 'a-z')
   .followedBy('/r');
</code>```

What advantage does the extremely terse syntax of a regular expression offer other than the shortest possible operation and logic syntax? Ultimately, is there a specific technical reason for the poor readability of regular expression syntax design?

答:
The regular expression you cite is a terrible mess and I don't think anyone agrees that it's readable. At the same time, much of that ugliness is inherent to the problem being solved: There are several layers of nesting and the URL grammar is relatively complicated (certainly too complicated to communicate succinctly in any language). However, it's certainly true that there are better ways to describe what this regex is describing. So why aren't they used?

A big reason is inertia and ubiquity. It doesn't explain how they became so popular in the first place, but now that they are, anyone who knows regular expressions can use these skills (with very few differences between dialects) in a hundred different languages and an additional thousand software tools (e.g., text editors and command line tools). By the way, the latter wouldn't and couldn't use any solution that amounts to writing programs, because they are heavily used by non-programmers.

Despite that, regular expressions are often overused, that is, applied even when another tool would be much better. I don't think regex syntax is terrible. But it is clearly much better at short and simple patterns: The archetypal example of identifiers in C-like languages, [a-zA-Z_][a-zA-Z0-9_]* can be read with an absolute minimum of regex knowledge and once that bar is met it is both obvious and nicely succinct. Requiring fewer characters is not inherently bad, quite the opposite. Being concise is a virtue provided you remain comprehensible.

There are at least two reasons why this syntax excels at simple patterns like these: It doesn't require escaping for most characters, so it reads relatively naturally, and it uses all available punctuation to express a variety of simple parsing combinators. Perhaps most importantly, it does not require anything at all for sequencing. You write the first thing, then the thing that comes after it. Contrast this with your followedBy, especially when the following pattern is not a literal but a more complicated expression.

So why do they fall short in more complicated cases? I can see three main problems:

There are no abstraction capabilities. Formal grammars, which originate from the same field of theoretical computer science as regexes, have a set of productions, so they can give names to intermediate parts of the pattern:

```<code># This is not equivalent to the regex in the question
# It's just a mock-up of what a grammar could look like
url      ::= protocol? '/'? '/'? '/'? (domain_part '.')+ tld
protocol ::= letter+ ':'
...
</code>```

As we could see above, whitespace having no special significance is useful to permit formatting that is easier on the eyes. Same thing with comments. Regular expressions can't do that because a space is just that, a literal ' '. Note though: some implementations allow a "verbose" mode where whitespace is ignored and comments are possible.

There is no meta-language to describe common patterns and combinators. For example, one can write a digit rule once and keep using it in a context free grammar, but one cannot define a "function" so to speak that is given a production p and creates a new production that does something extra with it, for example create a production for a comma separated list of occurrences of p.

The approach that you propose certainly solves these problems. It just doesn't solve them very well, because it trades in far more conciseness for it than is necessary. The first two problems can be solved while remaining within a relatively simple and terse domain-specific language. The third, well... a programmatic solution requires a general purpose programming language of course, but in my experience the third is by far the least of the those problems. Few patterns have enough occurrences of the same complex task that the programmer yearns for the ability to define new combinators. And when this is necessary, the language is often complicated enough that it can't and shouldn't be parsed with regular expressions anyway.

Solutions for those cases exist. There are approximately ten thousand parser combinator libraries which do roughly what you propose, just with a different set of operations, often different syntax, and almost always with more parsing power than regular expressions (i.e., they deal with context-free languages or some sizable subset of those). Then there are parser generators, which go with the "use a better DSL" approach described above. And there's always the option of writing some of the parsing by hand, in proper code. You can even mix-and-match, using regular expressions for simple sub-tasks and doing the complicated things in the code invoking the regexes.

I don't know enough about the early years of computing to explain how regular expressions came to be so popular. But they're here to stay. You just have to use them wisely, and not use them when that is wiser.

Body:
The regular expression you cite is a terrible mess and I don't think anyone agrees that it's readable. At the same time, much of that ugliness is inherent to the problem being solved: There are several layers of nesting and the URL grammar is relatively complicated (certainly too complicated to communicate succinctly in any language). However, it's certainly true that there are better ways to describe what this regex is describing. So why aren't they used?

A big reason is inertia and ubiquity. It doesn't explain how they became so popular in the first place, but now that they are, anyone who knows regular expressions can use these skills (with very few differences between dialects) in a hundred different languages and an additional thousand software tools (e.g., text editors and command line tools). By the way, the latter wouldn't and couldn't use any solution that amounts to writing programs, because they are heavily used by non-programmers.

Despite that, regular expressions are often overused, that is, applied even when another tool would be much better. I don't think regex syntax is terrible. But it is clearly much better at short and simple patterns: The archetypal example of identifiers in C-like languages, [a-zA-Z_][a-zA-Z0-9_]* can be read with an absolute minimum of regex knowledge and once that bar is met it is both obvious and nicely succinct. Requiring fewer characters is not inherently bad, quite the opposite. Being concise is a virtue provided you remain comprehensible.

There are at least two reasons why this syntax excels at simple patterns like these: It doesn't require escaping for most characters, so it reads relatively naturally, and it uses all available punctuation to express a variety of simple parsing combinators. Perhaps most importantly, it does not require anything at all for sequencing. You write the first thing, then the thing that comes after it. Contrast this with your followedBy, especially when the following pattern is not a literal but a more complicated expression.

So why do they fall short in more complicated cases? I can see three main problems:

There are no abstraction capabilities. Formal grammars, which originate from the same field of theoretical computer science as regexes, have a set of productions, so they can give names to intermediate parts of the pattern:

# This is not equivalent to the regex in the question
# It's just a mock-up of what a grammar could look like
url      ::= protocol? '/'? '/'? '/'? (domain_part '.')+ tld
protocol ::= letter+ ':'
...

As we could see above, whitespace having no special significance is useful to permit formatting that is easier on the eyes. Same thing with comments. Regular expressions can't do that because a space is just that, a literal ' '. Note though: some implementations allow a "verbose" mode where whitespace is ignored and comments are possible.

There is no meta-language to describe common patterns and combinators. For example, one can write a digit rule once and keep using it in a context free grammar, but one cannot define a "function" so to speak that is given a production p and creates a new production that does something extra with it, for example create a production for a comma separated list of occurrences of p.

The approach that you propose certainly solves these problems. It just doesn't solve them very well, because it trades in far more conciseness for it than is necessary. The first two problems can be solved while remaining within a relatively simple and terse domain-specific language. The third, well... a programmatic solution requires a general purpose programming language of course, but in my experience the third is by far the least of the those problems. Few patterns have enough occurrences of the same complex task that the programmer yearns for the ability to define new combinators. And when this is necessary, the language is often complicated enough that it can't and shouldn't be parsed with regular expressions anyway.

Solutions for those cases exist. There are approximately ten thousand parser combinator libraries which do roughly what you propose, just with a different set of operations, often different syntax, and almost always with more parsing power than regular expressions (i.e., they deal with context-free languages or some sizable subset of those). Then there are parser generators, which go with the "use a better DSL" approach described above. And there's always the option of writing some of the parsing by hand, in proper code. You can even mix-and-match, using regular expressions for simple sub-tasks and doing the complicated things in the code invoking the regexes.

I don't know enough about the early years of computing to explain how regular expressions came to be so popular. But they're here to stay. You just have to use them wisely, and not use them when that is wiser.


问:
Motivating yourself to actually write the code after you've designed something
Does it happen only to me or is this familiar to you too?

It's like this: You have to create something; a module, a feature, an entire application... whatever. It is something interesting that you have never done before, it is challenging.

So you start to think how you are going to do it. You draw some sketches. You write some prototypes to test your ideas. You are putting different pieces together to get the complete view.

You finally end up with a design that you like, something that is simple, clear to everybody, easy maintainable... you name it. You covered every base, you thought of everything. You know that you are going to have this class and that file and that database schema. Configure this here, adapt this other thingy there etc.

But now, after everything is settled, you have to sit down and actually write the code for it. And is not challenging anymore.... Been there, done that! Writing the code now is just "formalities" and makes it look like re-iterating what you've just finished.

At my previous job I sometimes got away with it because someone else did the coding based on my specifications, but at my new gig I'm in charge of the entire process so I have to do this too ('cause I get payed to do it).

But I have a pet project I'm working on at home, after work and there is just me and no one is paying me to do it. I do the creative work and then when time comes to write it down I just don't feel like it (lets browse the web a little, see what's new on P.SE, on SO etc).

I just want to move to the next challenging thing, and then to the next, and the next...

Does this happen to you too? How do you deal with it?

How do you convince yourself to go in and write the freaking code?

I'll take any answer.

答:
You need rapid prototyping, at home.

When you apply the same level of professional rigor on a private personal project, it easily results in over-engineering.

It is perfectly acceptable to set a high standard for a personal project, but you must understand that you may not have enough resources (coding hours, in addition to your 8 hours of daily work) to make progress on the project.

What is the most essential goal in your pet project? To prove the usefulness of one of your insights? If this is the case, then trim down the project until it becomes a proof-of-concept project. Then, use rapid prototyping so that you can accomplish more with less coding time.


答:
Historical perspective

The Wikipedia article is quite detailed about the origins of regular expressions (Kleene, 1956). The original syntax was relatively simple with only *, +, ?, | and grouping (...). It was terse (and readable, the two are not necessarily opposed), because formal languages tend to be expressed with terse mathematical notations.

Later, the syntax and capabilities evolved with editors and grew with Perl, which was trying to be terse by design ("common constructions should be short"). This complexified the syntax a lot, but note that people are now accustomized to regular expressions and are good at writing (if not reading) them. The fact that they are sometimes write-only suggest that when they are too long, they are generally not the right tool.
Regular expressions tend to be unreadable when being abused.

Beyond string-based regular expressions

Speaking about alternative syntaxes, let's have a look at one that already exists (cl-ppcre, in Common Lisp). Your long regular expression can be parsed with ppcre:parse-string as follows:

(let ((*print-case* :downcase)
      (*print-right-margin* 50))
  (pprint
   (ppcre:parse-string "^(?:([A-Za-z]+):)?(\\/{0,3})(0-9.\\-A-Za-z]+)(?::(\\d+))?(?:\\/([^?#]*))?(?:\\?([^#]*))?(?:#(.*))?$")))
```

<p>... and results in the following form:</p>

<pre class="lang-lisp prettyprint-override"><code>(:sequence :start-anchor
 (:greedy-repetition 0 1
  (:group
   (:sequence
    (:register
     (:greedy-repetition 1 nil
      (:char-class (:range #\A #\Z)
       (:range #\a #\z))))
    #\:)))
 (:register (:greedy-repetition 0 3 #\/))
 (:register
  (:sequence "0-9" :everything "-A-Za-z"
   (:greedy-repetition 1 nil #\])))
 (:greedy-repetition 0 1
  (:group
   (:sequence #\:
    (:register
     (:greedy-repetition 1 nil :digit-class)))))
 (:greedy-repetition 0 1
  (:group
   (:sequence #\/
    (:register
     (:greedy-repetition 0 nil
      (:inverted-char-class #\? #\#))))))
 (:greedy-repetition 0 1
  (:group
   (:sequence #\?
    (:register
     (:greedy-repetition 0 nil
      (:inverted-char-class #\#))))))
 (:greedy-repetition 0 1
  (:group
   (:sequence #\#
    (:register
     (:greedy-repetition 0 nil :everything)))))
 :end-anchor)
</code>```

This syntax is more verbose, and if you look at comments below, not necessarily more readable. So don't assume that because you have a less compact syntax, things will be automatically clearer.

However, if you start having troubles with your regular expressions, turning them into this format might help you decipher and debug your code.
This is one advantage over string-based formats, where a single character error can be difficult to spot.
The main advantage of this syntax is to manipulate regular expressions using a structured format instead of a string-based encoding. That allows you to compose and build such expressions like any other data-structure in your program.
When I use the above syntax, this is generally because I want to build expressions from smaller parts (see also my CodeGolf answer). For your example, we may write1:

`(:sequence
   :start-anchor
   ,(protocol)
   ,(slashes)
   ,(domain)
   ,(top-level-domain) ... )
```

<p>String-based regular expressions can also be composed, using string concatenation and or interpolation wrapped in helper functions. However, there are limitations with string manipulations which tend to clutter the code (think about nesting problems, not unlike backticks vs. <code>$(...)</code> in bash; also, escape characters may give you headaches).</p>

<p>Note also that the above form allows <code>(:regex "string")</code> forms so that you can mix terse notations with trees. All of that leads IMHO to good readability and composability; it addresses the three problems expressed by delnan, indirectly (i.e. not in the language of regular expressions itself).</p>

<h3>To conclude</h3>

<ul>
<li><p>For most purpose, the terse notation is in fact readable. There are difficulties when dealing with extended notations which involves backtracking, etc., but their used are rarely justified. The unwarranted use of regular expressions can lead to unreadable expressions.</p></li>
<li><p>Regular expressions need not be encoded as strings. If you have a library or a tool that can help you build and compose regular expressions, you'll <em>avoid</em> a lot of potential bugs related to string manipulations.</p></li>
<li><p>Alternatively, formal grammars are more readable and are better at naming and abstracting sub-expressions. Terminals are generally expressed as simple regular expressions.</p></li>
</ul>

<hr>

<p><strong>1.</strong> You may prefer to build your expressions at read-time, because regular expressions tend to be constants in an application. See <code>create-scanner</code> and <code>load-time-value</code>:</p>

<pre class="lang-lisp prettyprint-override"><code>'(:sequence :start-anchor #.(protocol) #.(slashes) ... )
</code>```

Title: Is there a specific reason for the poor readability of regular expression syntax design?

Body:
Programmers all seem to agree that readability of code is far more important than short-syntaxed one-liners which work, but require a senior developer to interpret with any degree of accuracy - but that seems to be exactly the way regular expressions were designed. Was there a reason for this?

We all agree that selfDocumentingMethodName() is far better than e(). Why should that not apply to regular expressions as well?

It seems to me that rather than designing a syntax of one-line logic with no structural organization:

```<code>var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})(0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
</code>```

And this isn't even strict parsing of a URL!

Instead, we could make a some pipeline structure organized and readable, for a basic example:

```<code>string.regex
   .isRange('A-Z' || 'a-z')
   .followedBy('/r');
</code>```

What advantage does the extremely terse syntax of a regular expression offer other than the shortest possible operation and logic syntax? Ultimately, is there a specific technical reason for the poor readability of regular expression syntax design?

Body:
Historical perspective

The Wikipedia article is quite detailed about the origins of regular expressions (Kleene, 1956). The original syntax was relatively simple with only *, +, ?, | and grouping (...). It was terse (and readable, the two are not necessarily opposed), because formal languages tend to be expressed with terse mathematical notations.

Later, the syntax and capabilities evolved with editors and grew with Perl, which was trying to be terse by design ("common constructions should be short"). This complexified the syntax a lot, but note that people are now accustomized to regular expressions and are good at writing (if not reading) them. The fact that they are sometimes write-only suggest that when they are too long, they are generally not the right tool.
Regular expressions tend to be unreadable when being abused.

Beyond string-based regular expressions

Speaking about alternative syntaxes, let's have a look at one that already exists (cl-ppcre, in Common Lisp). Your long regular expression can be parsed with ppcre:parse-string as follows:

(let ((*print-case* :downcase)
      (*print-right-margin* 50))
  (pprint
   (ppcre:parse-string "^(?:([A-Za-z]+):)?(\\/{0,3})(0-9.\\-A-Za-z]+)(?::(\\d+))?(?:\\/([^?#]*))?(?:\\?([^#]*))?(?:#(.*))?$")))

... and results in the following form:

(:sequence :start-anchor
 (:greedy-repetition 0 1
  (:group
   (:sequence
    (:register
     (:greedy-repetition 1 nil
      (:char-class (:range #\A #\Z)
       (:range #\a #\z))))
    #\:)))
 (:register (:greedy-repetition 0 3 #\/))
 (:register
  (:sequence "0-9" :everything "-A-Za-z"
   (:greedy-repetition 1 nil #\])))
 (:greedy-repetition 0 1
  (:group
   (:sequence #\:
    (:register
     (:greedy-repetition 1 nil :digit-class)))))
 (:greedy-repetition 0 1
  (:group
   (:sequence #\/
    (:register
     (:greedy-repetition 0 nil
      (:inverted-char-class #\? #\#))))))
 (:greedy-repetition 0 1
  (:group
   (:sequence #\?
    (:register
     (:greedy-repetition 0 nil
      (:inverted-char-class #\#))))))
 (:greedy-repetition 0 1
  (:group
   (:sequence #\#
    (:register
     (:greedy-repetition 0 nil :everything)))))
 :end-anchor)

This syntax is more verbose, and if you look at comments below, not necessarily more readable. So don't assume that because you have a less compact syntax, things will be automatically clearer.

However, if you start having troubles with your regular expressions, turning them into this format might help you decipher and debug your code.
This is one advantage over string-based formats, where a single character error can be difficult to spot.
The main advantage of this syntax is to manipulate regular expressions using a structured format instead of a string-based encoding. That allows you to compose and build such expressions like any other data-structure in your program.
When I use the above syntax, this is generally because I want to build expressions from smaller parts (see also my CodeGolf answer). For your example, we may write1:

`(:sequence
   :start-anchor
   ,(protocol)
   ,(slashes)
   ,(domain)
   ,(top-level-domain) ... )

String-based regular expressions can also be composed, using string concatenation and or interpolation wrapped in helper functions. However, there are limitations with string manipulations which tend to clutter the code (think about nesting problems, not unlike backticks vs. $(...) in bash; also, escape characters may give you headaches).

Note also that the above form allows (:regex "string") forms so that you can mix terse notations with trees. All of that leads IMHO to good readability and composability; it addresses the three problems expressed by delnan, indirectly (i.e. not in the language of regular expressions itself).

To conclude

For most purpose, the terse notation is in fact readable. There are difficulties when dealing with extended notations which involves backtracking, etc., but their used are rarely justified. The unwarranted use of regular expressions can lead to unreadable expressions.

Regular expressions need not be encoded as strings. If you have a library or a tool that can help you build and compose regular expressions, you'll avoid a lot of potential bugs related to string manipulations.

Alternatively, formal grammars are more readable and are better at naming and abstracting sub-expressions. Terminals are generally expressed as simple regular expressions.

1. You may prefer to build your expressions at read-time, because regular expressions tend to be constants in an application. See create-scanner and load-time-value:

'(:sequence :start-anchor #.(protocol) #.(slashes) ... )


答:
There is one big reason why regular expressions were designed as terse as they are: they were designed to be used as commands to a code editor, not as a language to code in. More precisely, ed was one of the first programs to use regular expressions, and from there regular expressions started their conquest for world domination. For instance, the ed command g/<regular expression>/p soon inspired a separate program called grep, which is still in use today. Because of their power, they subsequently were standardized and used in a variety of tools like sed and vim

But enough for the trivia. So why would this origin favor a terse grammar? Because you don't type an editor command to read it even one more time. It suffices that you can remember how to put it together, and that you can do the stuff with it that you want to do. However, every character you have to type slows down your progress editing your file. The regular expression syntax was designed to write relatively complex searches in a throw-away fashion, and that is precisely what gives people headaches who use them as code to parse some input to a program.


问:
C++ Extensible namespaces - how to force declarations back into global namespace
It is good programming style to include all necessary dependencies in a header that references them. Often this includes declarations that are placed in the STD & global namespaces (like cstdio). However, this creates problems when a second programmer wants to wrap such an include file in a new namespace to encapsulate the first one.

With this scenario in mind, is there a way to force declarations into the global name space? As a conceptual example (this won't actually compile):

```<code>foo.h --> original definition
// force global namespace, this is redundant when foo is in the global space
//   but could be important if foo included into another namespace.
namespace :: {
  #include <cstdio>
}
namespace foo {
  FILE *somefile;
}

bar.h --> New file, by a new programmer, encapsulating foo.
namespace bar {
  # include "foo.h"
  FILE *somefile;  // bar:somefile, as opposed to bar::foo::somefile
}
</code>```

Without the putative namespace ::{} we end up with declarations like foo::FILE, and foo::printf(), when we just want ::FILE and ::printf().

Popular libraries like boost resolve this by defining an explicit hierarchy. That would require that foo know it will be part of bar, and place global namespace includes outside of the local namespace definition.

However, good extensibility requires that we be able to use foo directly, OR wrap foo in a new namespace, without having to change foo or its includes.

Does anyone know how to accomplish this?

答:
Simple- don't do that shit.

Including a header into a namespace is a dumb thing to do and should not be done. If you're not happy with the namespacing of a header, then either complain to the author or fork the header. Including the header into a namespace is completely ineffective and pointless.


问:
How useful are function points?
How useful is it to measure function points?

We use function points at my new job.  I've heard of function points but haven't had any training or experience... but I don't have much confidence in things that cannot be explained succinctly.

答:
When dealing with the scope of a project, generally it is better to use a measure of Function Points rather than Lines of Code.  Because software projects can have upwards of millions of LOC (including LOC in libraries) the number becomes relatively meaningless.

How do you measure LOC if you're calling functionality from libraries?  Do you include LOC from libraries?  If you don't include LOC from libraries, does your boss not thing you're writing enough LOC?

Generally, it is better to say "I completed XXX functionality" rather than "I wrote XXX lines of code".

But I suggest you see for yourself.  Is it easier for you to estimate Function Points or Lines of Code?  Plug those results into the COCOMO II model, and see which is easier to use.

Also, this COCOMO II Manual gives a detailed description of Function Points and LOC around page 11.  Hopefully that's enough for you to go on.

Title: How useful are function points?


问:
Synchronize database with external API
I currently own a website where players can look-up their statistics of a game. When someone that is not in my database yet requests their statistics, I am calling the API with a PHP cURL request and storing them in my database.

Then I have a cronjob that runs every minute, takes 1/5th of the players in the database and updates every user in the database with the external API (20 users each request).

This worked fine when my mysql database was small (1000/2000 users) but the amount of users is increasing really fast and will become a lot more soon, so I need to change how I am updating the users.

My cronjob currently calls a php script that sends cURL requests and updates the database with the response.

Would it be better to update the players every hour and change the php cronjob to a python cronjob? I could call the API when the user requests their statistics but the external API is very slow sometimes or does not respond and this won't allow me to create graphs.

Looking forward to some thoughts about this.

答:
runs every minute

First I'd make sure if that's required. Querying an API aggressively will sometimes throttle you or drop your queries. (Depends on who is running it).

Regarding PHP and cURL that should be fine. I've written a similar system that queried over 200K character stats that way, but I just did it hourly in blocks of like 500 characters I think it was.

20 users each request

Find the minimum amount of data you need and try to query the maximum amount of characters you can query and use that. If 20 is it then that seems very low. Ensure you're building the query optimally also for their system. Sometimes, depending on the API, rather than querying for individual characters or groups of characters it's much faster to query for all the characters sorted by id (with a last login time > than say a few months back) with a start (offset from the beginning) and limit. (If the API supports that feature). This tends to allow you to query large blocks of characters quickly.

Also if possible query for different data at different rates. There's usually a lot of API data that rarely changes.

Lastly look for or request a WebSocket based API. A lot of games with real-time data are setting them up. These usually function like a message queue where you can subscribe to certain stat changes.

(Also one last comment. Look for their API discussion forum. Often the person managing it will post there and just tell you the optimal way they wish people to use the API. Your use case is fairly common for a lot of sites).

Title: Synchronize database with external API


问:
Why do we have to wait for I/O?
It's always been known that Disk operations are slow and we know the reasons why they are slow.
So the question here is why do we have to wait for I/O or why is there such a thing as IOWait, etc.?

I mean I've noticed that when you're doing some I/O tasks in the background, your computer basically gets a lot slower, I've especially noticed that when using Linux, if you're doing some longer I/O tasks, the OS becomes almost unusable until they are completed.

Indeed, I also found this topic in an article, there's a snippet:

I/O wait is 12.1%. This server has 8 cores (via cat /proc/cpuinfo). This is very close to (1/8 cores = 0.125)

So basically it means it's slowing down the computer a LOT, why is that? I mean OK, now the normal computer are at least 2 cores, sometimes 4 or sometimes they have more because of hyperthreading or something like that. But now the question is why the CPU actually has to stay there, practically not doing anything else than just waiting for IO? I mean the basic idea or architecture of the process managament, now I don't know whether it's the OS who's responsible for that, or does it come down to the hardware part, but it should be made possible for the cpu to wait or to check regularly, while actually performing lots of other tasks and only going back to the IO process when it's ready. Indeed, if that's such a difficult task and the cpu would have to wait, why isn't that managed by hardware more efficiently then? Like for instance there could be some kind of mini cpu which would just wait for it and deliver the small part of data to the real cpu as soon as it gets back to the process and so the process would be repeated and we wouldn't have to practically dedicate a whole cpu core for the data copy process... Or would I be the one who should invent this kind of stuff and get a nobel prize for that? :S

Now okay, I'm really putting it now from an observers perspective and I really haven't gone that deep into the topic, but I really don't understand why the cpu has to work with the speed of HDD, while it could just do something else and come back to HDD once it's ready. The idea is not to speed up the application who needs that IO operation or the copy process or whatever, but the idea is to just minimally affect the CPU consumption while performing that operation, so that the OS could utilise it for other processes and the user wouldn't have to feel general computer lag when doing some copying operations...

答:
I add other viewpoint than others, maybe controversial:

Its typical problem of Linux operating systems. Lagging specifically (Search for "Linux mouse lag" ). Windows does not have this problem. I have dual boot Windows 7 and Linux Mint. Even when doing intensive disk operation in Windows, Windows feels smoot, mouse is moving normally. In Linux oppositelly it does not feels so smoots and mouse sometimes lag even during normal web browsing.

Its probably because different philosophy and history of these two systems. Windows is from beginning designed for ordinary users, its principially graphical operatings systems. And for Windows users, non-smooth system behavior and mouse stopping moving is signal that something is wrong. So Microsofts programmers worked hard to design whole system to minimize cases when systems feels slow. In opposite Linux is not initially graphical system, desktop is only 3rd party addition here. And Linux is principially designed for hackers using command line. Get things done philosophy. Linux is simply not designed for smooth behavior in mind, feelings does not matter here.

Note: I am not saying that Windows is better than Linux, i say they simply have different overall philosophy, which in complex environment can lead to different high level behavior/feeling of these systems.

Title: Why do we have to wait for I/O?


问:
How to protect source code from being copied or leaked by employes
I'm a Java Developer, I created a Desktop Application , that is Free, and now I'm about to finish the payed version. my question is when I create a startup and other developers work on my code. How can I prevent them from copying the source code and take it home or leak it?? and is there is a software for that, what there names are?? and I need the name of some kind of software that keep track of every activity the user make (keyboard keys pressed, website visited even if history is deleted, software installed ...). I will be using Windows. Thanks a lot</p>

答:
What you're anticipating is a social problem; trying to create a technological solution to it is a bad idea.  All that does is put you in a technological arms race against the attacker--assuming anyone actually does try to do that, of course.

The way you keep your employees from doing harmful things to screw you over is to put in their contract that they can't do harmful things to screw you over.  Then, if they violate that, you have the law on your side, which is a lot more useful than having some technology (that a determined attacker is probably going to find a way to circumvent) on your side.


答:
As @cmaster says, regexps were originally designed to be used only on-the-fly, and it is simply bizarre (and slightly depressing) that the line-noise syntax is still the most popular one.  The only explanations I can think of involve either inertia, masochism, or machismo (it's not often that ‘inertia’ is the most appealing reason for doing something...)

Perl makes a rather weak attempt at making them more readable by allowing whitespace and comments, but doesn't do anything remotely imaginative.

There are other syntaxes.  A good one is the scsh syntax for regexps, which in my experience produces regexps which are reasonably easy to type, but still readable  after the fact.

[scsh is splendid for other reasons, just one of which is its famous acknowledgements text]


问:
What are good reasons to use explicit interface implementation for the sole purpose of hiding members?
During one of my studies into the intricacies of C#, I came across an interesting passage concerning explicit interface implementation.

While this syntax is quite helpful when you need to resolve name clashes,
    you can use explicit interface implementation simply to hide more "advanced"
    members from the object level.

The difference between allowing the use of object.method() or requiring the casting of ((Interface)object).method() seems like mean-spirited obfuscation to my inexperienced eyes. The text noted that this will hide the method from Intellisense at the object level, but why would you want to do that if it was not necessary to avoid name conflicts?

答:
If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation. In the following example, all the calls to Paint invoke the same method.
C#

```<code>class Test
{
    static void Main()

    {
        SampleClass sc = new SampleClass();
        IControl ctrl = (IControl)sc;
        ISurface srfc = (ISurface)sc;

        // The following lines all call the same method.
        sc.Paint();
        ctrl.Paint();
        srfc.Paint();
    }
}

interface IControl
{
    void Paint();
}
interface ISurface
{
    void Paint();
}
class SampleClass : IControl, ISurface
{
    // Both ISurface.Paint and IControl.Paint call this method.
    public void Paint()
    {
        Console.WriteLine("Paint method in SampleClass");
    }
}
</code>```

In contrast, explicit implementation of one (or both) of them allows you to specify different behavior for each.

Body:
If a class implements two interfaces that contain a member with the same signature, then implementing that member on the class will cause both interfaces to use that member as their implementation. In the following example, all the calls to Paint invoke the same method.
C#

class Test
{
    static void Main()

    {
        SampleClass sc = new SampleClass();
        IControl ctrl = (IControl)sc;
        ISurface srfc = (ISurface)sc;

        // The following lines all call the same method.
        sc.Paint();
        ctrl.Paint();
        srfc.Paint();
    }
}

interface IControl
{
    void Paint();
}
interface ISurface
{
    void Paint();
}
class SampleClass : IControl, ISurface
{
    // Both ISurface.Paint and IControl.Paint call this method.
    public void Paint()
    {
        Console.WriteLine("Paint method in SampleClass");
    }
}

In contrast, explicit implementation of one (or both) of them allows you to specify different behavior for each.


问:
Does class inheritance (in C#) violate the Open/Closed Principle?
I typically make all my methods private unless and until they need to be overriden by a sub-class. At that point I modify the base class to make that particular method protected virtual. Is it accurate to say that this is a violation of the "Closed to Modification" principal? If  so, that would imply that I should choose protected virtual as my default (similar to Java, in which methods are virtual by default). Is that really what the OCP recommends?

Personally, such an interpretation seems a bit daft to me, but I want to know if I am missing something.

答:
First, I think there's a fundamental difference between initial development (here of a base class) and later stages of development.

If you find yourself in the initial development category, you will often need some refactoring to make the base class accommodate its first subclass (sometimes add a parameter, split a method, etc...), so regarding a need refactoring, I wouldn't worry about the OCP at such an early stage.

Further, we cannot and should not try to foresee all possible and potential future uses of something; doing that is an anti-pattern in itself.

Also, there's a fundamental difference between internal classes and externally exposed classes.  In the case of internal classes, they may well be all versioned together (e.g. in the same DLL), so there is no reason to disallow refactoring to accommodate new sub classes as the design evolves.

However, for externally exposed APIs that have the maturity of a number of sub classes (or third party plugins) already implemented (which also can be expected to be added to in different versioning units (e.g. different DLLs), one should take the OCP seriously: a better design will accommodate more third party sub classing without changes.

However, regarding externally exposed API's, we're better off using interfaces instead of sub-classing anyway.  Subclassing seriously limits an implementors options by comparison with interfaces, while also complicating the interactions & dependencies between producers and consumers.  Using an interface, we simply avoid the issue of whether to mark a method as virtual or not.  When we choose interfaces, designs become more decoupled, all of which is the more in the spirit of the OCP.


答: I guess it's just me, but I have the opposite problem.  I usually have trouble thinking of all the details before I start writing the code and actually run into the relevant issues.  Realistically, I usually have only a vague design in my head when I start coding something.  My big challenge is getting myself to think of all the details and have a design upfront.</p>

Title: Motivating yourself to actually write the code after you've designed something

Body:
Does it happen only to me or is this familiar to you too?

It's like this: You have to create something; a module, a feature, an entire application... whatever. It is something interesting that you have never done before, it is challenging.

So you start to think how you are going to do it. You draw some sketches. You write some prototypes to test your ideas. You are putting different pieces together to get the complete view.

You finally end up with a design that you like, something that is simple, clear to everybody, easy maintainable... you name it. You covered every base, you thought of everything. You know that you are going to have this class and that file and that database schema. Configure this here, adapt this other thingy there etc.

But now, after everything is settled, you have to sit down and actually write the code for it. And is not challenging anymore.... Been there, done that! Writing the code now is just "formalities" and makes it look like re-iterating what you've just finished.

At my previous job I sometimes got away with it because someone else did the coding based on my specifications, but at my new gig I'm in charge of the entire process so I have to do this too ('cause I get payed to do it).

But I have a pet project I'm working on at home, after work and there is just me and no one is paying me to do it. I do the creative work and then when time comes to write it down I just don't feel like it (lets browse the web a little, see what's new on P.SE, on SO etc).

I just want to move to the next challenging thing, and then to the next, and the next...

Does this happen to you too? How do you deal with it?

How do you convince yourself to go in and write the freaking code?

I'll take any answer.


答:
Explicit interfaces are handy when either an object has two or more very distinct forms of communication.

For example, an object that maintains a collection of child objects that need to communicate with parent.

There are some actions we only want accessible to external callers and some actions we only want accessible to the child objects.

Explicit interfaces help ensure this divide.

```<code>    static void Main(string[] args)
    {
        var parent = new Parent();
        parent.DoExternalStuff();
    }

    interface IExternal {
        void DoExternalStuff();
    }

    interface IInternal {
        void DoInternalStuff();
    }

    class Parent : IExternal, IInternal
    {
        public Parent()
        {
            var child = new Child(this);
        }

        public void DoExternalStuff()
        {
           // do something exciting here for external callers
        }

        void IInternal.DoInternalStuff()
        {
            // do something exciting here for internal callers
        }
    }

    class Child
    {
        public Child(IInternal parent)
        {
            parent.DoInternalStuff();
        }
    }
</code>```

Title: What are good reasons to use explicit interface implementation for the sole purpose of hiding members?

Body:
During one of my studies into the intricacies of C#, I came across an interesting passage concerning explicit interface implementation.

While this syntax is quite helpful when you need to resolve name clashes,
    you can use explicit interface implementation simply to hide more "advanced"
    members from the object level.

The difference between allowing the use of object.method() or requiring the casting of ((Interface)object).method() seems like mean-spirited obfuscation to my inexperienced eyes. The text noted that this will hide the method from Intellisense at the object level, but why would you want to do that if it was not necessary to avoid name conflicts?

Body:
Explicit interfaces are handy when either an object has two or more very distinct forms of communication.

For example, an object that maintains a collection of child objects that need to communicate with parent.

There are some actions we only want accessible to external callers and some actions we only want accessible to the child objects.

Explicit interfaces help ensure this divide.

    static void Main(string[] args)
    {
        var parent = new Parent();
        parent.DoExternalStuff();
    }

    interface IExternal {
        void DoExternalStuff();
    }

    interface IInternal {
        void DoInternalStuff();
    }

    class Parent : IExternal, IInternal
    {
        public Parent()
        {
            var child = new Child(this);
        }

        public void DoExternalStuff()
        {
           // do something exciting here for external callers
        }

        void IInternal.DoInternalStuff()
        {
            // do something exciting here for internal callers
        }
    }

    class Child
    {
        public Child(IInternal parent)
        {
            parent.DoInternalStuff();
        }
    }


问:
Big O Nested For Loop Breakdown
I understand how to get a general picture of the big O of a nested loop, but what would be the operations for each loop in a nested for loop?

If we have:

```<code>for(int i=0; i<n; i++)
{
    for(int j=i+1; j<1000; j++)
    {
        do something of constant time;
    }
}
</code>```

How exactly would we get T(N)? The outer for loop would be n operations, the inner would be 1000(n-1) and the inside would just be c is that right?

So T(n)=cn(1000(n-1)) is that right?

答:
The limit as n approaches infinity reveals big O(n). The internal loop only executes for the first 999 n. For n > 999 the internal loop does not run and the instructions become constant.

How to write this all as a function T(n)? Of that I am not certain.

Title: Big O Nested For Loop Breakdown


问:
Java abstract class naming
Example:

You create an abstract class for Ajax actions. Different Ajax actions will all extend this class.

Problem:

Do you name the class AjaxAction or AbstractAjaxAction?

When you create subclasses, do you name them:

Action

AjaxAction

Just name them what they are

I have not been able to find what the "official" convention is. I don't see a need for the "Abstract" prefix or any required naming convention in the subclasses. (It may fit anyway, depending.)

Is there an official convention? Could you link me to it? And what are your opinions on this subject?

答:
Choose something, and be consistent. Whether you use the suffix Base to indicate an intended base class, or the prefix Abstract, just be consistent about it.

There are as many opinions on this kind of thing as there are, well, programmers. My opinion, for what it's worth, as that consistency in naming, within a project (or development group or whatever) is more important than any specific naming scheme.

Title: Java abstract class naming


问:
Why do we need a seed in Random Number Generators?
I want to know how Random number generator(RNG) works in any PL(Programming language).
I know the random methods has short periods. i.e they start repeating the values after specific number of time.

Seeds are used to initialise the random numbers generated by the RNG.
IF any PL uses its own SEEDS, how specifying my seed will make any difference. I heard people saying that specifying the seed help in better control over the sequence Generated. I don't understand it as a whole.
Could any one please help. with the same,

答:
Let's say that you wrote an encryption algorithm that uses a pseudo-random sequence of numbers to generate the encrypted content.  Your encryption function works two ways; you can encrypt using a random number sequence, and then decrypt using the same random number sequence.

Wouldn't it be nice if you could later specify the same seed so that you could get the same set of numbers to decrypt with?  That's why we have seeds; to produce the same sequence of "random" numbers.

Of course, if you just need any sequence of random numbers, you can use a semi-random seed like the millisecond digits of the current time.


问:
Struggling about the benefits of using a plugin approach in a Industrial Software Architecture
I'm trying to design an application, something quite generic over a .NET C# Stack.

It's supposed to be an desktop application intended to control industrial equipment and to perform measurements and testing, however it's planned to be able to switch later on different UIs dealing with different

I'm trying to have a pretty generic approach:

UI Agnostic: Webpages / Winforms / WPF / GTK# / Whathever, etc. using naked objects in order to avoid the hassles of a lot boiler-plate UI code.

DB Agnostic for storing Data (ADO.NET & EF can deal with that)

Remote Control and Monitoring (that's really tricky but I guess with WCF I should manage to have a remote access with service running on the remote client)

User Management

External Industrial Resources (devices)

Logging and bug reporting

Reporting and data exportation

Licensing

The business layer of the application is split into three main parts and leveraging the other parts described above:

Edition: define a set of tests (flowchart) with conditions (user interactions, results fetching during the tests) using the industrial resources available

Operation: perform the tests defined above with user interaction (if any defined in during the previous step)

Analysis: deal with the data (DB) that have been recorded accordingly to the test definition given in the edition part and provide some statistical computations: data mining features (clustering, anomaly detection, etc.) and reporting feature (that can also be defined to be generated automatically at different moment of the operation).

My problem is that I would like to have a modular approach and I'm wondering whether this is really desirable in my case. The approach is sound but at the same time it seems like providing a lot of issues.

Theoretically, it means you can test your modules independently from each others but actually in most cases even though you can mock the inputs / outputs required for the tests, the reality is still that it requires other dependencies to make it run and this is for me the real bottom line in this approach.
The fact that you can load and unload some are for me only applicable in a couple of situations but not that many.

For instance, the User Management is using the Database Module which probably also going to use another enciphering module and so on and on and on.

Later on the remote control and monitoring would also eventually use that so... my point is that it seems pretty hard to have modules fully independent here.

The plugin / modular approach would work like a charm for external industrial resources where those devices would have to implement a certain interface to be compatible with the system.

But about the rest I'm really suspicious whether it worth the hassle of using MEF or any other plugin / extension framework.

What do you think? Is the modular approach really applicable to everything in my case? Or just a couple of features can take advantage of it.

答:
We are working on same Architecture with different approaches. Currently we working with plug-in approaches with EF because when we talking about Licensing and Reporting that’s should be customer based need or requirement, For example currently some customer need some basic feature of application that’s based on licensing and some require some more feature and custom base report so every time you don’t need to build whole project and update or upload on server .
    Plug in based Architect is good when some existing customer wants some new feature so you can develop and upload and plug so there is no need to set for every customer
I hope this will help you.
Thanks</p>


答:
Including a header into a namespace is prone to break various assumptions, and should not be done. Problems that come to mind are:

It breaks include guards. If a header can only be included once, and you include it into the wrong namespace, then other code can't include it into the correct namespace within the same compilation unit. Or the other way round: if it was already included by a library, you can't re-include it somewhere else. E.g.:

someLib/A.h

```<code>#ifndef SOMELIB_A_H_
#define SOMELIB_A_H_
// assume this will be included into namespace someLib
class A {};
#endif
</code>```

someLib/B.h

```<code>#ifndef SOMELIB_B_H_
#define SOMELIB_B_H_
namespace someLib
{
    # include "A.h"
    int b(const A& a) { return 42; }
}
#endif
</code>```

usercode.cpp

```<code>// defines someLib::b and somelib::A
#include <somelib/B.h>
// include A into global namespace
// – won't work because someLib/A.h was already included
#include <somelib/A.h>
#include <iostream>
int main()
{
    std::cout << someLib::b(A()) << '\n';
    return 0;
}
</code>```

This will fail because #include <someLib/A.h> is a no-op in the main program, and does not include anything. Therefore, A is undefined in the main program. If the files were included the other way round, it would work since the someLib::b declaration can also see symbols in the global scope. However, the order of includes should not matter in a well-designed library!

You won't be able to link. Most header files have an associated .cpp file that includes private implementation details. If you include a header into a different namespace, then it can't link with the implementation.

It breaks macros. If a library-provided macro calls back into a library, it will always have to use the fully namespace-qualified name, since we do not know from which namespace it will be used. If you manage to include a symbol foo::bar::BazException as qux::BazException, then a perfectly reasonable macro such as

```<code>#define FOO_BAR_BAZEXCEPTION(expr) foo::bar::BazException(expr, __FILE__, __LINE__)
</code>```

will stop working.

It breaks argument-dependent lookup, which only works if the function and its arguments share a namespace.

If including a file into a namespace is such a horrible idea and will break more stuff than it fixes, what are the alternatives?

First of all, namespaces are good. They help us to give structure to the overall architecture, even if they are very open. We use namespaces not only because they impose a convenient hierarchy that avoids name clashes, but also because some features such as argument-depedent lookup depend on it. The only reason why the standard library puts some symbols into the global scope is compatibility with C. Even then, you can access the symbols through the std:: namespace, which should be preferred.

Some people feel that namespaces might become inconveniently long. This is no problem because we can define shorter aliases in the scope where they are needed with using foo::bar::Baz. This is also the solution when putting symbols into the global scope: an alias does not hide the original, fully-qualified name, so all the problems mentioned above do not apply. The using directive has lots of uses, and can alias namespace, typenames, and values such as variables or member functions.

When you include a file, always assume that it is properly namespaced. Therefore, include it in global scope before you open any namespace of your own. Even if the headers are from your own project, make sure they declare their own namespaces. This also means that the structure of namespaces is fairly difficult to change once it is fixed. But that is good – any change to your public interface (which includes the namespace structure) would also require all dependent code to change. I do not see how “good extensibility” would require us to give up this structure.

Title: C++ Extensible namespaces - how to force declarations back into global namespace

Body:
It is good programming style to include all necessary dependencies in a header that references them. Often this includes declarations that are placed in the STD & global namespaces (like cstdio). However, this creates problems when a second programmer wants to wrap such an include file in a new namespace to encapsulate the first one.

With this scenario in mind, is there a way to force declarations into the global name space? As a conceptual example (this won't actually compile):

```<code>foo.h --> original definition
// force global namespace, this is redundant when foo is in the global space
//   but could be important if foo included into another namespace.
namespace :: {
  #include <cstdio>
}
namespace foo {
  FILE *somefile;
}

bar.h --> New file, by a new programmer, encapsulating foo.
namespace bar {
  # include "foo.h"
  FILE *somefile;  // bar:somefile, as opposed to bar::foo::somefile
}
</code>```

Without the putative namespace ::{} we end up with declarations like foo::FILE, and foo::printf(), when we just want ::FILE and ::printf().

Popular libraries like boost resolve this by defining an explicit hierarchy. That would require that foo know it will be part of bar, and place global namespace includes outside of the local namespace definition.

However, good extensibility requires that we be able to use foo directly, OR wrap foo in a new namespace, without having to change foo or its includes.

Does anyone know how to accomplish this?

Body:
Including a header into a namespace is prone to break various assumptions, and should not be done. Problems that come to mind are:

It breaks include guards. If a header can only be included once, and you include it into the wrong namespace, then other code can't include it into the correct namespace within the same compilation unit. Or the other way round: if it was already included by a library, you can't re-include it somewhere else. E.g.:

someLib/A.h

#ifndef SOMELIB_A_H_
#define SOMELIB_A_H_
// assume this will be included into namespace someLib
class A {};
#endif

someLib/B.h

#ifndef SOMELIB_B_H_
#define SOMELIB_B_H_
namespace someLib
{
    # include "A.h"
    int b(const A& a) { return 42; }
}
#endif

usercode.cpp

// defines someLib::b and somelib::A
#include <somelib/B.h>
// include A into global namespace
// – won't work because someLib/A.h was already included
#include <somelib/A.h>
#include <iostream>
int main()
{
    std::cout << someLib::b(A()) << '\n';
    return 0;
}

This will fail because #include <someLib/A.h> is a no-op in the main program, and does not include anything. Therefore, A is undefined in the main program. If the files were included the other way round, it would work since the someLib::b declaration can also see symbols in the global scope. However, the order of includes should not matter in a well-designed library!

You won't be able to link. Most header files have an associated .cpp file that includes private implementation details. If you include a header into a different namespace, then it can't link with the implementation.

It breaks macros. If a library-provided macro calls back into a library, it will always have to use the fully namespace-qualified name, since we do not know from which namespace it will be used. If you manage to include a symbol foo::bar::BazException as qux::BazException, then a perfectly reasonable macro such as

#define FOO_BAR_BAZEXCEPTION(expr) foo::bar::BazException(expr, __FILE__, __LINE__)

will stop working.

It breaks argument-dependent lookup, which only works if the function and its arguments share a namespace.

If including a file into a namespace is such a horrible idea and will break more stuff than it fixes, what are the alternatives?

First of all, namespaces are good. They help us to give structure to the overall architecture, even if they are very open. We use namespaces not only because they impose a convenient hierarchy that avoids name clashes, but also because some features such as argument-depedent lookup depend on it. The only reason why the standard library puts some symbols into the global scope is compatibility with C. Even then, you can access the symbols through the std:: namespace, which should be preferred.

Some people feel that namespaces might become inconveniently long. This is no problem because we can define shorter aliases in the scope where they are needed with using foo::bar::Baz. This is also the solution when putting symbols into the global scope: an alias does not hide the original, fully-qualified name, so all the problems mentioned above do not apply. The using directive has lots of uses, and can alias namespace, typenames, and values such as variables or member functions.

When you include a file, always assume that it is properly namespaced. Therefore, include it in global scope before you open any namespace of your own. Even if the headers are from your own project, make sure they declare their own namespaces. This also means that the structure of namespaces is fairly difficult to change once it is fixed. But that is good – any change to your public interface (which includes the namespace structure) would also require all dependent code to change. I do not see how “good extensibility” would require us to give up this structure.


答:
The biggest problem with regex isn't the overly terse syntax, it's that we try to express a complex definition in a single expression, instead of composing it from smaller building blocks. This is similar to programming where you never use variables and functions and instead embed your code all in a single line.

Compare regex with BNF. Its syntax isn't that much cleaner than regex, but it's used differently. You start by defining simple named symbols and compose them until you arrive at a symbol describing the whole pattern you want to match.

For example look at the URI syntax in rfc3986:

```<code>URI           = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
scheme        = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
hier-part     = "//" authority path-abempty
              / path-absolute
              / path-rootless
              / path-empty
...
</code>```

You could write nearly the same thing using a variant of the regex syntax that supports embedding named sub-expressions.

Personally I think that a terse regex like syntax is fine for commonly used features like character-classes, concatenation, choice or repetition, but for more complex and rarer features like look-ahead verbose names are preferable. Quite similar to how we use operators like + or * in normal programming and switch to named functions for rarer operations.

Body:
The biggest problem with regex isn't the overly terse syntax, it's that we try to express a complex definition in a single expression, instead of composing it from smaller building blocks. This is similar to programming where you never use variables and functions and instead embed your code all in a single line.

Compare regex with BNF. Its syntax isn't that much cleaner than regex, but it's used differently. You start by defining simple named symbols and compose them until you arrive at a symbol describing the whole pattern you want to match.

For example look at the URI syntax in rfc3986:

URI           = scheme ":" hier-part [ "?" query ] [ "#" fragment ]
scheme        = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
hier-part     = "//" authority path-abempty
              / path-absolute
              / path-rootless
              / path-empty
...

You could write nearly the same thing using a variant of the regex syntax that supports embedding named sub-expressions.

Personally I think that a terse regex like syntax is fine for commonly used features like character-classes, concatenation, choice or repetition, but for more complex and rarer features like look-ahead verbose names are preferable. Quite similar to how we use operators like + or * in normal programming and switch to named functions for rarer operations.


问:
What is the bug workflow on your agile/Scrum team?
What is the bug workflow on your agile/Scrum team?

Here is ours:
- If the bug is related to a story in the current sprint, we fix it.
- If the bug is not related to a story in the current sprint and it is not critical, it is sent to the product owner for prioritization.
- If the bug is not related to a story in the sprint and it is critical, we fix it.

答:
I always thought a bug is just a story that already has a failing test, thus it's better defined than the typical first draft of stories for features.

So if you are convinced that bugs are stories, you treat them as you would other stories in regards to estimations and priorities.


答:
Regex is like lego pieces. At first glance, you see some differently shaped plastic parts that can be joined. You might think there would not be too many possible different things you can shape but then you see the amazing things other people do and you just wonder how an amazing toy it is.

Regex is like lego pieces. There are few arguments that can be used but chaining them in different forms will form millions of different regex patterns which can be used for many complicated tasks.

People rarely used regex parameters alone. Many languages offers you functions to check the length of a string or split the numeric parts out of it. You can use string functions to slice texts and reform them. The power of regex is noticed when you use complex forms to do very specific complex tasks.

You can found tens of thousands of regex questions on SO and they rarely marked as duplicate. This alone shows the possible unique use-cases which are very different from each other.

And it is not easy to offer pre-defined methods to handle this much different unique tasks. You have string functions for those kind of tasks, but if those functions are not enough for your specifix task, then it is time to use regex


答:
selfDocumentingMethodName() is far better than e()

is it? There's a reason most languages have { and } as block delimiters rather than BEGIN and END.

People like terseness, and once you know the syntax, short terminology is better. Imagine your regex example if d (for digit) was 'digit' the regex would be even more horribe to read. If you made it more readily parseable with control characters, then it would look more like XML. Neither are as good once you know the syntax.

To answer your question properly though, you have to realise that regex comes from the days when terseness was mandatory.Its easy to think a 1 MB XML document is no big deal today, but we're talking about days when 1 MB was pretty much your entire storage capacity. There were also fewer languages used back then, and regex isn't a million miles away from perl or C, so the syntax would be familiar to programmers of the day who would be happy with learning the syntax. So there was no reason to make it more verbose.


答:
I recognize this is a problem of practise rather than potency. The problem usually arises when regular expressions are directly implemented, instead of assuming a composite nature. Similarly, a good programmer will decompose the functions of his program into concise methods.

For example, a regex string for an URL could be reduced from approximately:

```<code>UriRe = [scheme][hier-part][query][fragment]
</code>```

to:

```<code>UriRe = UriSchemeRe + UriHierRe + "(/?|/" + UriQueryRe + UriFragRe + ")"
UriSchemeRe = [scheme]
UriHierRe = [hier-part]
UriQueryRe = [query]
UriFragRe = [fragment]
</code>```

Regular expressions are nifty things, but they are prone to abuse by those who turn absorbed in their apparent complexity. The resulting expressions are rhetoric, absent of a long-term value.

Body:
I recognize this is a problem of practise rather than potency. The problem usually arises when regular expressions are directly implemented, instead of assuming a composite nature. Similarly, a good programmer will decompose the functions of his program into concise methods.

For example, a regex string for an URL could be reduced from approximately:

UriRe = [scheme][hier-part][query][fragment]

to:

UriRe = UriSchemeRe + UriHierRe + "(/?|/" + UriQueryRe + UriFragRe + ")"
UriSchemeRe = [scheme]
UriHierRe = [hier-part]
UriQueryRe = [query]
UriFragRe = [fragment]

Regular expressions are nifty things, but they are prone to abuse by those who turn absorbed in their apparent complexity. The resulting expressions are rhetoric, absent of a long-term value.


答:
I want to know how Random number generator(RNG) works in any PL(Programming language).

Languages tend to have their own implementations of pseudo-random number generators, so you cannot know how a pseudo-random number generator works in any programming language.  Also, there is not much value that we could add here besides pointing you to the relevant article in Wikipedia.

The simplest approach, however, which produces fairly good results and is very fast, is to keep track of the last integer issued, and each time a new pseudo-random integer is requested, increment it by one and then multiply it by a huge prime constant before returning it. This multiplication usually results in substantial overflow, which is ignored. The effect is that the resulting bit pattern is for all practical purposes random. The increment by one is necessary in order to ensure that if the number ever reaches zero, subsequent multiplications will not keep yielding zero.

I know the random methods has short periods. i.e they start repeating the values after specific number of time.

I do not know how you got the impression that pseudo-random numbers have short periods, because this is simply not true.  Pseudo-random number generators tend to have huge periods.

Seeds are used to initialise the random numbers generated by the RNG. IF any PL uses its own SEEDS, how specifying my seed will make any difference.

A pseudo-random number generator will use its own seed only if you do not specify your own seed.  If you specify your own seed, then the pseudo-random number generator will use your seed.

I heard people saying that specifying the seed help in better control over the sequence Generated. I don't understand it as a whole. Could any one please help. with the same,

Do try this at home:

Write a program which draws a starry sky and then clears it, using only GetPixel() and SetPixel().

So, what you have to do is write a loop which generates, say, 1000 pseudo-random pairs of coordinates, and inverts each pixel at those coordinates.  If the pixel was black, it makes it white.  If it was white, it makes it black.  If the screen was initially all black, about 1000 white stars should appear.

Now, to clear the stars, you could clear the entire screen, but there is a cooler way to do it.

Initialize your pseudo-random number generator with the exact same seed, and then re-apply the above loop.  The exact same sequence of pseudo-random numbers will be generated, therefore the exact same set of coordinates will be visited, so each one of those pixels will be re-inverted, resulting in a black sky again.

Title: Why do we need a seed in Random Number Generators?

Body:
I want to know how Random number generator(RNG) works in any PL(Programming language).
I know the random methods has short periods. i.e they start repeating the values after specific number of time.

Seeds are used to initialise the random numbers generated by the RNG.
IF any PL uses its own SEEDS, how specifying my seed will make any difference. I heard people saying that specifying the seed help in better control over the sequence Generated. I don't understand it as a whole.
Could any one please help. with the same,


问:
Algorithm for optimized variable generation without collisions?
I'm looking for an algorithm that can generate optimized syntactically valid variable names (for javascript in this case) without collisions.

So as general rule I would want something that generated

aa, ab, ac .... az, a1, a2, a3, a4, a5, a6, a7, a8, a9
ba, bb, bc.... bz, b1....
zz...z9...
aaa,aab....

it does not generate them at once, it does it going through a code base and does it whenever certain conditions are found (This will actually be done using a gulp plugin so this doesn't need to take walking the AST into account). Therefore it needs to be able to know what the current variable to be generated should be based on what the last variable was.

So that if the last variable is aaz it would know to do aa1 and if the last variable is azz it would know to do az1 and so forth.

答:
There are many more valid variable names than those generated by the series in your question, but I'll be going along with it because it is simple and might be good enough.

Ideally we would to keep track of how many variables have been generated and simply map that number to the next variable name. Dealing with the incrementing nameSeed variable should be easy, and there's a very handy function for the next step in JavaScript, which matches our desired functionality almost exactly: Number#toString(radix). radix is 10 by default (giving the decimal representation of the number) but can be up to 36, which includes not only the digits 0-9 but also the letters a-z.

For example, (30).toString(36) gives u. (400).toString(36) gives b4. Unfortunately, (1).toString(36) gives 1, which is not a valid identifier and there are infinitely more cases where the same kind of failure happens...

If you only want "kind of minimal", you can prepend _ and have a valid identifier.

If you really want minimal (within the bounds of 0-9, a-z), we need to modify the algorithm to avoid those invalid names. We also need to avoid things like undefined, var, etc.. There may be a good strategy to do this "pre-emptively", but I will simply be validating the result and fixing it (as well as the nameSeed) if it needs fixing.

The function below takes a seed to use for the name, and returns the generated name as well as the next potential seed. If the given seed would produce an invalid result, it uses the first valid seed larger than the given seed (if all seeds were valid, we would not have to return the "next" one, but now it is necessary since we may have skipped some).

```<code>function generateName( seed ) {
  var name = seed.toString( 36 );
  if ( isNaN( name.substring( 0, 1 ) ) ) {
    // The name starts with a letter, now see if it collides with any builtins
    if ( builtins.indexOf( name ) < 0 ) {
      // Got a good name
      return { nextSeed: seed + 1, name: name };
    } else {
      // There's a collision, try the next seed
      return generateName( seed + 1 );
    }
  } else {
    // The name starts with a digit, just replace it with 'a' and try again
    // We could use the same strategy as above (just increment seed), but that might take a long time... better to jump to something with a good chance of working.
    name = "a" + name.substring( 1 );
    var newSeed = parseInt( name, 36 );
    return generateName( newSeed );
  }
}
</code>```

Constructing the builtins array is left as an exercise for the reader...

Body:
There are many more valid variable names than those generated by the series in your question, but I'll be going along with it because it is simple and might be good enough.

Ideally we would to keep track of how many variables have been generated and simply map that number to the next variable name. Dealing with the incrementing nameSeed variable should be easy, and there's a very handy function for the next step in JavaScript, which matches our desired functionality almost exactly: Number#toString(radix). radix is 10 by default (giving the decimal representation of the number) but can be up to 36, which includes not only the digits 0-9 but also the letters a-z.

For example, (30).toString(36) gives u. (400).toString(36) gives b4. Unfortunately, (1).toString(36) gives 1, which is not a valid identifier and there are infinitely more cases where the same kind of failure happens...

If you only want "kind of minimal", you can prepend _ and have a valid identifier.

If you really want minimal (within the bounds of 0-9, a-z), we need to modify the algorithm to avoid those invalid names. We also need to avoid things like undefined, var, etc.. There may be a good strategy to do this "pre-emptively", but I will simply be validating the result and fixing it (as well as the nameSeed) if it needs fixing.

The function below takes a seed to use for the name, and returns the generated name as well as the next potential seed. If the given seed would produce an invalid result, it uses the first valid seed larger than the given seed (if all seeds were valid, we would not have to return the "next" one, but now it is necessary since we may have skipped some).

function generateName( seed ) {
  var name = seed.toString( 36 );
  if ( isNaN( name.substring( 0, 1 ) ) ) {
    // The name starts with a letter, now see if it collides with any builtins
    if ( builtins.indexOf( name ) < 0 ) {
      // Got a good name
      return { nextSeed: seed + 1, name: name };
    } else {
      // There's a collision, try the next seed
      return generateName( seed + 1 );
    }
  } else {
    // The name starts with a digit, just replace it with 'a' and try again
    // We could use the same strategy as above (just increment seed), but that might take a long time... better to jump to something with a good chance of working.
    name = "a" + name.substring( 1 );
    var newSeed = parseInt( name, 36 );
    return generateName( newSeed );
  }
}

Constructing the builtins array is left as an exercise for the reader...


问:
How do you name your private variables in C#?
What is the best practice, most commonly accepted naming conventions for private variables in C#?

private int myInteger;

private int MyInteger;

private int mMyInteger;

private int _myInteger;

private int _MyInteger;

Mysterious other option

Which do you use and why?  (My company is fairly new to C# and I would like to pick the most "industry accepted" method to try and get into our coding standard.)

答: I have ReSharper name my variables, not only mine but everyone else does this as well. There is a great amount of consistency trough the project.</p>


问:
How to draw programmer's attentions in certain conditions?
Let's start with an example.

Let's say, I have a method called export that depends heavily on the DB schema. And by “depends heavily” I mean I know that adding a new column to a certain table often (very often) leads to the corresponding export method change (usually you should add the new field to the export data as well).

Programmers often forget to change export method since it's not really clear you should even look at this. My goal is to force programmer explicitly make a decision to determine whether he forgot to look at the export method or just don't want to add a field to the export data. And I'm looking for the design solution for this problem.

I have two ideas, but both of them have flaws.

Smart “Read all” wrapper

I can create the smart wrapper that makes sure all data is explicitly read.

Something like this:

```<code>def export():
    checker = AllReadChecker.new(table_row)

    name    = checker.get('name')
    surname = checker.get('surname')
              checker.ignore('age') # explicitly ignore the "age" field

    result = [name, surname] # or whatever

    checker.check_now() # check all is read

    return result
</code>```

So, checker asserts if table_row contains another fields that were not read. But all this thing looks kind of heavy and (maybe) affects perfomance.

“Check that method” unittest

I can just create the unittest that remembers the last table schema and fails every time the table is changed. In that case programmer would see something like “don't forget to check out the export method”. To hide the warning  programmer would (or wouldn't — that's a problem) check out export and manually (that's another problem) fix the test by adding new fields into it.

I have a few other ideas but they are too troublesome to implement or too difficult to understand (and I don't want the project to become a puzzle).

The above problem is just an example of the more wide class of problems I encounter from time to time. I want to bind some pieces of code and/or infrastructure so changing one of them immediately alerts programmer to check another one. Usually you have some simple tools like extracting common logic or writing reliable unittest, but I'm looking for the tool for more complex cases: maybe some design patterns I'm now aware of.

答: Almost always, when creating an export I also create a corresponding import. As I have other tests which fully populate the data structure being exported, I can then build a round-trip unit test which compares a fully populated original with an exported then imported copy. If they are the same, then the export/import is complete; if they are not the same then the unit test fails and I know that the export mechanism needs updating. </p>